repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
maplewolf/kg-adv-models
targeted_attack/attack_triple_iter_target_class.py
Python
gpl-3.0
11,966
0.004179
""" LGPL v3 License More information from the user maplewolf on Kaggle.Implementation of sample attack.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import numpy as np from scipy.misc import imread, imsave import tensorflow as ...
alse, reuse=True) if model_mode == 3: aux_weight = AUX_ENS_V2 else: aux_weight = AUX_INC_V3 cross_en
tropy = tf.losses.softmax_cross_entropy(one_hot_target_class, logits, label_smoothing=label_smoothing, weights=1.0) cross_entrop...
byron1655/spider
spider.py
Python
gpl-3.0
496
0.008065
# -*- coding: utf-8 -*- __author__ = 'byron' import datetime import traceback import os import re import time from spider_core import SpiderCore url = "http://www.lagou.com/" maxcount = 2000 maxlevel = 5 SpiderCore = SpiderCore(url, maxcount, maxlevel) SpiderCore.start() d
ef getAutomaticId
(name): global db item = db.ids.findAndModify({ 'query':{'spider': name}, 'update':{'$inc': 1} }) if 'id' in item: return item['id'] return None
jptomo/rpython-lang-scheme
rpython/rtyper/lltypesystem/rstr.py
Python
mit
43,498
0.001494
from weakref import WeakValueDictionary from rpython.annotator import model as annmodel from rpython.rlib import jit, types from rpython.rlib.debug import ll_assert from rpython.rlib.objectmodel import (malloc_zero_filled, we_are_translated, _hash_string, keepalive_until_here, specialize, enforceargs) from rpython...
uf._always_inline_ = True @jit.oopspec('stroruni.copy_contents(src, dst, srcstart, dststart, length)') @signature(types.any(), types.any(), types.int(), types.int(), types.int(), returns=types.none()) def copy_string_contents(src
, dst, srcstart, dststart, length): """Copies 'length' characters from the 'src' string to the 'dst' string, starting at position 'srcstart' and 'dststart'.""" # xxx Warning: don't try to do this at home. It relies on a lot # of details to be sure that it works correctly in all cases. ...
tzhaoredhat/automation
pdc/apps/release/views.py
Python
mit
29,999
0.0008
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # import json from django.shortcuts import render, get_object_or_404 from django.conf import settings from kobo.django.views.generic import DetailView, SearchView from rest_framework import viewsets, mixins, stat...
%(WRITABLE_SERIALIZER)s Please note that if you update the `short` field, the URL of this product will change. The change of short name is *not* propagated to product
versions nor releases. __Response__: %(SERIALIZER)s """ return super(ProductViewSet, self).update(*args, **kwargs) class ProductVersionViewSet(ChangeSetCreateModelMixin, ChangeSetUpdateModelMixin, StrictQueryParamMixin, ...
projecthamster/hamster-dbus
tests/storage/test_dbus_store.py
Python
gpl-3.0
1,981
0
# -*- coding: utf-8 -*- """ Unittests for DBusStore. Please refer to ``__init__.py`` for general details. """ from __future__ import absolute_import, unicode_literals import subprocess from hamster_dbus import storage from . import common class TestDBusStore(common.HamsterDBusManagerTestCase): def setUp(se...
ags_manager(self): """Make sure a ``storage.TagManager`` is instantiated.""" self.assertIsInstance(self.store.tags, storage.TagManager) def test_facts_manager(self): """Make sure a ``storage.FactManager`` is instantiated.""" self.assertIsInstance(self.store.facts, storage.FactManage...
None(self.store.cleanup()) def test_explicit_bus(self): """Make sure that an explicitly passed bus is really used.""" self.store = storage.DBusStore({}, bus=self.dbus_con) self.assertEqual(self.store._bus, self.dbus_con)
thesgc/chembiohub_ws
cbh_core_model/migrations/0031_auto_20160112_0307.py
Python
gpl-3.0
2,204
0.006352
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.core.exceptions import ObjectDoesNotExist def migrate_old_permissions_to_new_ones(apps, schema_editor): """Idempotent function to migrate the old permissions to the new ones. Old custom content...
perm.content_type = new_ct perm.content_type_id = new_ct.id perm.save() except ObjectDoesNotExist: pass if ct.app_label == "_can_see": perm.co
ntent_type = skin_ct perm.content_type_id = skin_ct.id perm.save()# except ObjectDoesNotExist: print("No contenttypes therefore nothing to migrate") class Migration(migrations.Migration): dependencies = [ ('cbh_core_model', '0030_auto_20151215_0548'), ] ...
ReproducibleBuilds/diffoscope
diffoscope/comparators/odt.py
Python
gpl-3.0
1,450
0
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2017
Chris Lamb <lamby@debian.org> # # diffoscope is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # diffoscope is distribu
ted in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with diffoscope. If not, ...
samuelmaudo/yepes
yepes/exceptions.py
Python
bsd-3-clause
1,875
0.000533
# -*- coding:utf-8 -*- from __future__ import unicode_literals class LookupTypeError(TypeError): def __init__(self, lookup_type): msg = "Lookup type '{0}' not supported" super(LookupTypeError, self).__init__(msg.format(lookup_type)) self.lookup_type = lookup_type class MissingAttribute...
TypeError): def __init__(self, expected_type, received_object): if not isinstance(expected_type, (tuple, list)): expected_type = (expected_type, ) args = ( ' or '.join(cls.__name__ for cls in expected_type), received_object.__class__.__name__, ) m...
{1}' super(UnexpectedTypeError, self).__init__(msg.format(*args)) self.expected_type = expected_type self.received_object = received_object
davidzchen/tensorflow
tensorflow/python/keras/layers/dense_attention_test.py
Python
apache-2.0
34,547
0.002403
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
42137 # softmax_scores002 = 0
expected_scores = np.array( [[[0.73105857863, 0.26894142137, 0.]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 1, 1]. # expected000 = 0.73105857863 * 1.6 + 0.26894142137 * 0.7 - 0 * 0.8 # = 1.35795272077 expected = np.arr...
SNoiraud/gramps
gramps/gen/lib/test/date_test.py
Python
gpl-2.0
22,594
0.015535
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007 Donald N. Allingham # Copyright (C) 2013-2014 Vassilii Khachaturov # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; eit...
al def __enter__(self): return self.retval def __exit__(self, *args, **kwargs): pass with Context(Date.CAL_SWEDISH) as calendar: for quality in (Date.QUAL_NONE, Date.QUAL_ESTIMATED, Date.QUAL_CALCULATED): for modifier in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, Date.MOD_ABOU...
Date() d.set(quality,modifier,calendar,(4,11,1700,False),"Text comment") dates.append( d) for modifier in (Date.MOD_RANGE, Date.MOD_SPAN): d = Date() d.set(quality,modifier,calendar,(4,10,1701,False, 5,11,1702,False),"...
ddico/odoo
addons/website_sale_stock/models/stock_picking.py
Python
agpl-3.0
467
0.004283
# -*- coding: utf-8 -*- # Pa
rt of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, api, fields from odoo.tools.translate import _ class StockPicking(models.Model): _inherit = 'stock.picking' website_id = fields.Many2one('website', related='sale_id.website_id', string='Website', ...
store=True, readonly=True)
nuagenetworks/nuage-openstack-horizon
nuage_horizon/dashboards/project/networks/workflows.py
Python
apache-2.0
19,029
0
# Copyright 2020 Nokia. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
id'].choices = [('', _("Choose a Zone"))]
self.fields['sub_id'].choices = [('', _("Choose a Subnet"))] self.fields['ip_version_'].choices = [('', _("Choose a cidr"))] type_choices = [('os', _("OpenStack Managed Subnet")), ('vsd_manual', _("VSD Managed Subnet (Manual)")), ('vsd...
Thraxis/pymedusa
sickbeard/indexers/indexer_config.py
Python
gpl-3.0
1,348
0.001484
# coding=utf-8 from tvdb_api.tvdb_api import Tvdb from sickbeard import helpers initConfig = { 'valid_languages': [ "da", "fi", "nl", "de", "it", "es", "fr", "pl", "hu", "el", "tr", "ru", "he", "ja", "pt", "zh", "cs", "sl", "hr", "ko", "en", "sv", "no" ], 'langabbv_to_id': { 'el': ...
} } INDEXER_TVDB = 1 I
NDEXER_TVRAGE = 2 # Must keep indexerConfig = { INDEXER_TVDB: { 'id': INDEXER_TVDB, 'name': 'theTVDB', 'module': Tvdb, 'api_params': { 'apikey': 'F9C450E78D99172E', 'language': 'en', 'useZip': True, }, 'session': helpers.make_sess...
monikagrabowska/osf.io
addons/wiki/views.py
Python
apache-2.0
20,751
0.001108
# -*- coding: utf-8 -*- import httplib as http import logging from bs4 import BeautifulSoup from flask import request from framework.mongo.utils import to_mongo_key from framework.exceptions import HTTPError from framework.auth.utils import privacy_info_handle from framework.auth.decorators import must_be_logged_in ...
ettings': node.api_url_for('edit_wiki_settings'), 'grid': node.api_url_for('project_wiki_g
rid_data', wname=name) } if additional_urls: urls.update(additional_urls) return urls def _get_wiki_web_urls(node, key, version=1, additional_urls=None): urls = { 'base': node.web_url_for('project_wiki_home', _guid=True), 'edit': node.web_url_for('project_wiki_view', wname=key,...
yil8/NNtoolbox
bin/plot.py
Python
gpl-2.0
551
0.012704
#!/usr/bin/env python import sys import numpy as np from matplotlib import pyplot as plt def main(): infile = open(sys.argv[1]) data = np.array(map(lambda x:map(float, x.strip('\n').split('\t')), infile.readlines())) X
= data[:, 0:-1] (N, D) = X.shape
Y = data[:, -1].reshape((N, 1)) plt.plot(X[np.where(Y == 0)[0]][:, 0], X[np.where(Y == 0)[0]][:, 1], 'b.') plt.plot(X[np.where(Y == 1)[0]][:, 0], X[np.where(Y == 1)[0]][:, 1], 'r.') plt.show() infile.close() if __name__ == '__main__': main()
ikben/troposphere
troposphere/elasticloadbalancingv2.py
Python
bsd-2-clause
11,035
0
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, If, Tags from .validators import ( elb_name, exactly_one, network_port, tg_healthcheck_port, integer, one_of, boolean ) class LoadBalancerAttributes(AWS...
HealthCheckPort': (tg_healthcheck_port, False), 'HealthCheckProtocol': (basestring, False), 'HealthCheckTimeoutSeconds': (integer, False), 'HealthyThresholdCount': (integer, False), 'Matcher': (Matcher, False), 'Name': (basestring, False), 'Port': (network_port, False), ...
'Targets': ([TargetDescription], False), 'TargetType': (basestring, False), 'UnhealthyThresholdCount': (integer, False), 'VpcId': (basestring, False), } def validate(self): one_of(self.__class__.__name__, self.properties, 'TargetType', ...
CoutinhoElias/danibraz
danibraz/bolsa/views.py
Python
mit
5,742
0.008188
# Create your views here. from danibraz.bolsa.models import PlanoDeContas from django.core.files.storage import FileSystemStorage from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render import xlrd # def simple_upload(request): # if request.method == 'POST' and request.FILE...
by_name("Plan1") worksheet = workbook.sheet_by_index(0) lista = [] #print(worksheet.nrows) for r in range(1, worksheet.nrows): lista.append( PlanoDeContas(classification=remove(str(worksheet.cell(r, 0).value)),
name=remove(str(worksheet.cell(r, 1).value)), reduced_account=remove(str(worksheet.cell(r, 2).value)), account_type=remove(str(worksheet.cell(r, 4).value)), source=remove(str(worksheet.cell(r, 3).value)), ) ...
dstufft/sessions
setup.py
Python
apache-2.0
2,121
0
#!/usr/bin/env python # Copyright 2014 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
e is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function import os import setupt
ools base_dir = os.path.dirname(__file__) about = {} with open(os.path.join(base_dir, "sessions", "__about__.py")) as f: exec(f.read(), about) with open(os.path.join(base_dir, "README.rst")) as f: long_description = f.read() setuptools.setup( name=about["__title__"], version=about["__version__"], ...
mathieudesro/pathos
examples/nested.py
Python
bsd-3-clause
629
0.027027
def g(x): import random return int(x * random.random()) def h(x): return sum(tmap(g, x)) def f(x,y): return x*y x = range(10) y = range(5) if __name__ == '__main__': from pathos.helpers import freeze_support freeze_support() from pathos.pools import ProcessPool, ThreadPool amap = ProcessPo...
p = ThreadPool().map print amap(f, [h(x),h(x),h(x),h(x),h(x)], y).get() def _f(m, g, x, y): return sum(m(g,x))*y print amap(_f, [tmap]*len(y), [g]*len(y), [x]*len(y), y).get() from math import sin
, cos print amap(tmap, [sin,cos], [range(10),range(10)]).get()
florinn/veryfay-python
veryfay/tests/features/steps/steps_public_api.py
Python
mit
9,490
0.006006
from behave import when, then from hamcrest import assert_that, calling, raises from veryfay import * from fixtures import * @when('action target not found') def step_impl(context): pass @then('it should fail when action target not found') def step_impl(context): result = context.ae(Create(SomeClass)).is_a...
iter')), raises(NotImplementedError)) assert_that(calling(context.ae(Delete(SomeOtherClass)).verify).with_args(PrincipalClass('commiter')), raises(NotImplementedError)) @
then('it should fail when a matching allow role definition has a "contains" method that does not return a boolean value') def step_impl(context): assert_that(calling(context.ae(Delete(OtherClass)).is_allowing).with_args(PrincipalClass('commiter')), raises(NotImplementedError)) assert_that(calling(context.ae(Del...
trendelkampschroer/PyEMMA
pyemma/msm/models/msm_sampled.py
Python
bsd-2-clause
15,417
0.002724
from __future__ import absolute_import __author__ = 'noe' from pyemma._base.model import SampledModel from pyemma.msm.models.msm import MSM from pyemma.util.types import is_iterable class SampledMSM(MSM, SampledModel): def __init__(self, samples, ref=None, conf=0.95): r""" Constructs a sampled MSM ...
ecomposition of reversible transition matrices. # ncv is the number of Lanczos vectors generated, `ncv` must be greater than k; # it is recommended that ncv > 2*k # #
""" # from msmtools.analysis import rdl_decomposition # from pyemma.util import linalg # # # left eigenvectors # self.sample_Ls = np.empty((self._nsample), dtype=object) # # eigenvalues # self.sample_eigenvalues = np.empty((self._nsample), dtype=object) # # right ...
wandec/grr
lib/flows/general/checks.py
Python
apache-2.0
3,098
0.006456
#!/usr/bin/env python """A flow to run checks for a host.""" from grr.lib import aff4 from grr.lib import flow from grr.lib import rdfvalue from grr.lib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRF...
ing in checks.CheckHost(self.state.host_data,
os_type=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding)
shohamp/Gobi
runner/gobi_runner.py
Python
gpl-3.0
3,321
0.002108
from glob import glob import subprocess import vagrant from fabric.api import execute, env, quiet from fabric.state import connections from logger import init_logger, debug, info VM_NAME = "default" def clear_fabric_cache(): """ Fabric caches it's connections, so it won't have to re-connect every time you...
runs the machine, connects to them, and runs the tests """ init_logger() info("Welcome to gobi. Sit back and relax :)") vclient = vagrant.Vagrant() test_funcs = get_all_test_functions() assert test_funcs > 0, "No tests found. What do you want me to run?" info("Found %d tests to run" % len...
info("Setting up the environment...") vclient.up() info("Environment is up and ready") debug("Taking snapshot...") vagrant_take_snapshot() debug("Snapshot taken") init_fabric(vclient) counter = 1 for task in test_funcs: # After the first test, clean - delete cache and re...
trac-ja/trac-ja
tracopt/perm/config_perm_provider.py
Python
bsd-3-clause
2,233
0.000448
# -*- coding: utf-8 -*- # # Copyright (C) 2009 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists o...
ry contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. from trac.core import * from trac.config import ConfigSection from trac.perm import IPermissionRequestor class ExtraPermissionsProvider(Component):
"""Extra permission provider.""" implements(IPermissionRequestor) extra_permissions_section = ConfigSection('extra-permissions', doc="""This section provides a way to add arbitrary permissions to a Trac environment. This can be useful for adding new permissions to use for workflow a...
eoogbe/api-client-staging
generated/python/proto-google-cloud-logging-v2/google/cloud/proto/logging/v2/logging_metrics_pb2_grpc.py
Python
bsd-3-clause
5,957
0.005372
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities import google.cloud.proto.logging.v2.logging_metrics_pb2 as google_dot_cloud_dot_proto_dot_logging_dot_v2_dot_logging__m...
etric. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CreateLogMetric(self, request, context): """Creates a logs-based metric. """
context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UpdateLogMetric(self, request, context): """Creates or updates a logs-based metric. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) ...
david-farrar/exaproxy
lib/exaproxy/html/menu.py
Python
bsd-2-clause
3,102
0.039329
# encoding: utf-8 """ menu.py Created by Thomas Mangin on 2012-02-25. Copyright (c) 2011-2013 Exa Networks. All rights reserved. """ import sys import time from .img import png from .images import logo python = '%s %s' % ('Pypy' if 'PyPy' in sys.version else 'Python', sys.version.split()[0]) def html (title,header...
tworks">%s</a>' % png(logo) def Menu (options): menu = '<div class="vmenu">\n' menu += '\t<h1><a href="/index.html">Home</a></h1>\n' for name, url, section in options: menu += '\t<h1>%s</h1>\n' % name if section: menu += '\t<ul>\n' for name, url, new in section: if new: menu +
= '\t\t<li><a href="%s" target="%s">%s</a></li>\n' % (url,name,name) else: menu += '\t\t<li><a href="%s">%s</a></li>\n' % (url,name) menu += '\t</ul>\n' menu += '</div>\n' _html = html(_title,'','#9999FF',_image).replace('*text*','%s').replace('*menu*',menu) def _lambda (page): return _html.replace(...
shodimaggio/SaivDr
appendix/torch_nsolt/nsoltLayerExceptions.py
Python
bsd-2-clause
819
0.030525
class InvalidDirection(Exception): def __init__(self,msg): super().__init__(self,msg) class InvalidTargetChannels(Exception): def __init__(self,msg):
super().__init__(self,msg) class InvalidMode(Exception): def __init__(self,msg): super().__init__(self,msg) class InvalidMus(Exception): def __init__(self,msg): super().__init__(self,msg) class InvalidNumberOfChannels(Exception): def __init__(self,msg): super().__init__(...
elf,msg) class InvalidNumberOfVanishingMoments(Exception): def __init__(self,msg): super().__init__(self,msg) class InvalidNumberOfLevels(Exception): def __init__(self,msg): super().__init__(self,msg)
ihacklog/osdlyrics
daemon/player.py
Python
gpl-3.0
19,960
0.002455
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Tiger Soldier # # This file is part of OSD Lyrics. # # OSD Lyrics is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
break if detected: break except: pass if detected and self._detect_timer: glib.source_remove(self._detect_timer) self._detect_timer = None return detected def _connect_proxy(self, bus_name, activate): if...
_PREFIX): return logging.info('Connecting to player proxy %s', bus_name) proxy_name = bus_name[len(osdlyrics.PLAYER_PROXY_BUS_NAME_PREFIX):] if activate: try: self.connection.activate_name_owner(bus_name) except Exception, e: lo...
chandler14362/panda3d
direct/src/distributed/DistributedSmoothNode.py
Python
bsd-3-clause
22,204
0.004909
"""DistributedSmoothNode module: contains the DistributedSmoothNode class""" from panda3d.core import * from panda3d.direct import * from .ClockDelta import * from . import DistributedNode from . import DistributedSmoothNodeBase from direct.task.Task import cont from direct.showbase import DConfig as config # This nu...
DistributedSmoothNodeBase.DistributedSmoothNodeBase): """ This specializes DistributedNode to add functionality to smooth motion over time, via the SmoothMover C++ object defined in DIRECT. """ def __init__(self, cr): try: self.DistributedSmoothNode_initialized ex...
oothNode_initialized = 1 DistributedNode.DistributedNode.__init__(self, cr) DistributedSmoothNodeBase.DistributedSmoothNodeBase.__init__(self) self.smoothStarted = 0 # Set this True to assert that the local process has # complete authority over the position o...
kylerbrown/pyjack
setup.py
Python
lgpl-2.1
1,661
0.020482
#!/usr/bin/python # -*- coding: utf-8 -*- # Distutils installer for PyJack # Test for Jack2 #---------------------------------------------------# import os if os.path.exists("/usr/local/include/jack/jack.h"): path = "/usr/local/include/jack/jack.h" elif os.path.exists("/usr/include/jack/jack.h"): path = "/usr/incl...
der, falkTX, IOhannes m zmölnig", author_email = "andy@a2hd.com", url = "http://sourceforge.net/projects/py-jack", long_description = '''PyJack is a module written in C which exposes the Jack API to Python. For information about Jack see http://jackaudio.org. This enables a Python program to connect to and...
_modules = [Extension("jack", ["pyjack.c"], libraries=["jack", "dl"], include_dirs=numpy_include_dirs, define_macros=pyjack_macros, )], )
atagh/gavel-clone
gavel/controllers/admin.py
Python
agpl-3.0
6,919
0.001734
from gavel import app from gavel.models import * from gavel.constants import * import gavel.settings as settings import gavel.utils as utils from flask import ( redirect, render_template, request, url_for, ) import urllib.parse @app.route('/admin/') @utils.requires_auth def admin(): annotators = An...
url_for('admin')) @app.route('/admin
/setting', methods=['POST']) @utils.requires_auth def setting(): key = request.form['key'] if key == 'closed': action = request.form['action'] new_value = SETTING_TRUE if action == 'Close' else SETTING_FALSE Setting.set(SETTING_CLOSED, new_value) db.session.commit() return re...
rapidpro/tracpro
tracpro/polls/maps.py
Python
bsd-3-clause
2,550
0.001569
from __future__ import unicode_literals from collections import Counter from itertools import groupby from operator import itemgetter import numpy from django.db.models import F from tracpro.charts.formatters import format_number from .utils import get_numeric_values from . import rules def get_map_data(response...
nnotate(boundary=F('response__contact__region__boundary')) answers = answers.exclude(boundary=None) return answers def numeric_map_data(answers, question): """For each boundary, display the category of the average answer value.""" map_data = {} answer_data = [ { 'boundary': ans...
for answer in answers.order_by('boundary') ] for boundary_id, _answers in groupby(answer_data, itemgetter('boundary')): values = get_numeric_values(a['value_to_use'] for a in _answers) if len(values) > 0: average = round(numpy.mean(values), 2) map_data[boundary_id] =...
Lotterleben/desvirt
desvirt/vm.py
Python
gpl-3.0
5,090
0.005894
import sys import os import pty, shlex import signal import subprocess import socket import time import atexit import re import string import logging import random from .vif import VirtualInterface from .vnet import VirtualNet from .riotnative import RIOT from string import Template import libvirt import hashlib a...
self.vm_instance = None self.fullname = self.name if self.vmgroup_name: self.fullname = "%s_%s" % (self.vmgroup_name, name) def lookup(self,
conn=None): global all_domains if self.nodeType == "meshrouter": if not all_domains: all_domains = {} for id in conn.listDomainsID(): dom = conn.lookupByID(id) all_domains[dom.name()] = dom for id in conn...
saltstack/salt
tests/pytests/unit/modules/test_pdbedit.py
Python
apache-2.0
4,278
0.001403
from textwrap import dedent import pytest import salt.modules.pdbedit as pdbedit from tests.support.mock import MagicMock, patch @pytest.fixture(autouse=True) def setup_loader(request): setup_loader_modules = {pdbedit: {}} with pytest.helpers.loader_mock(request, setup_loader_modules) as loader_mock: ...
NT username: bottia User SID: 42 ------------- Unix username: srilyk NT username: srilyk User SID: 99 Account desc: trololol\x1dlol ------------- Unix username: jewlz NT
username: flutterbies User SID: 4 ------------- ------------- ------------- """ ).strip() with patch.dict( pdbedit.__salt__, { "cmd.run_all": MagicMock( return_value={"stdout": pdb_output, "stderr": "", "re...
dacarlin/TSkunkel
transform.py
Python
mit
2,849
0.005616
import math from autoprotocol import UserError from modules.utils import * def transform(protocol, params): # general paramet
ers constructs = params['constructs'] num_constructs = len(constructs) plates = list(set([construct.container for construct in constructs])) if len(plates) !=
1: raise UserError('You can only transform aliquots from one common container.') # **** need to be able to check if plate is sealed to add run-chaining **** mm_mult = 1.3 transformation_plate = protocol.ref("transformation_plate", None, "96-pcr", discard=True) protocol.incubate(transformation_...
scottgreenup/wiki
main.py
Python
gpl-2.0
592
0.008446
#!/usr/bin/env python """ Fast Card
A wikipedia like system where information is kept in a card format. The main audience for this project are individuals who repeatably refer to references online. Those references can be pulled in and the data stored as a card, and can then be easily searched. It is akin to a mind palace, but on the in...
, 'POST']) def home_page(): return render_template('index.html') if __name__ == "__main__": app.run()
jreback/pandas
pandas/tests/groupby/test_quantile.py
Python
bsd-3-clause
9,272
0.001833
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index import pandas._testing as tm @pytest.mark.parametrize( "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"] ) @pytest.mark.parametrize( "a_vals,b_vals", [ # Ints ([1, 2, 3, 4, 5], [5,...
_product([[0, 1], [0.25, 0.75]]) result = df.groupby([0, 0, 1, 1]).quantile([0.25, 0.75]) expected = DataFrame( {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index ) tm.assert_frame_equal(result, expected) def test_quantile_array2(): # https://github.com/pandas-dev...
) result = df.groupby("A").quantile([0.3, 0.7]) expected = DataFrame( { "B": [0.9, 2.1, 2.2, 3.4, 1.6, 2.4, 2.3, 2.7, 0.0, 0.0], "C": [1.2, 2.8, 1.8, 3.0, 0.0, 0.0, 1.9, 3.1, 3.0, 3.0], }, index=pd.MultiIndex.from_product( [[0, 1, 2, 3, 4], [0.3, ...
tanyaweaver/data-structures
setup.py
Python
mit
496
0
# -*- coding: utf -8*- fr
om setupt
ools import setup setup( name="linked list, stack, double linked list, queue, deque implementation", description="This package implements a linked list", version=0.1, license='MIT', author="Steven Than, Tatiana Weaver", author_email="email@email.com", py_modules=['linked_list', 'stack', 'dl...
carquois/blobon
blobon/blogs/migrations/0008_auto__del_category__del_tag__del_field_blog_status.py
Python
mit
6,240
0.008173
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Category' db.delete_table('blogs_category') # Deleting model 'Tag' db.del...
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']
", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), ...
ablifedev/ABLIRC
ABLIRC/bin/public/circos_plot.py
Python
mit
9,818
0.00309
#!/usr/bin/env python3 # coding: utf-8 #################################################################################### ### Copyright (C) 2015-2019 by ABLIFE #################################################################################### ###################################################################...
7 white -----karyotype file chrset.add(line[0]) w.writelines('chr - ' + line[0] + ' ' + line[0] + ' 0 ' + line[1] + ' white\n') w.close() return file, temp_chr def make_gene_file(gff, chrset): file = 'gene.txt' w = open(file, 'w') for eachline in open(gff, 'r'): if eachl...
continue if line[2] == "gene": w.writelines(line[0] + '\t' + line[3] + '\t' + line[4] + '\n') w.close() return file def make_circos_conf(karyotype_file, gene_file, chr): file = 'circos.conf' w = open(file, 'w') temp = """<<include colors_fonts_patterns.conf>> <<include ideogr...
tylere/earthengine-api
python/ee/tests/ee_test.py
Python
apache-2.0
15,097
0.002716
#!/usr/bin/env python """Test for the ee.__init__ file.""" import six i
mport unittest import ee from ee import apitestcase class EETestCase(apitestcase.ApiTestCase): def setUp(self): ee.Reset() def testInitialization(self): """Verifies library initialization.""" def MockSend(path, params, unused_method=None, unused_raw=None): if path == '/algorithms': r...
: raise Exception('Unexpected API call to %s with %s' % (path, params)) ee.data.send_ = MockSend # Verify that the base state is uninitialized. self.assertFalse(ee.data._initialized) self.assertEqual(ee.data._api_base_url, None) self.assertEqual(ee.ApiFunction._api, None) self.assertFal...
Marcelpv96/SITWprac2017
sportsBetting/features/steps/register_teams.py
Python
gpl-3.0
1,654
0.000605
from behave import * use_step_matcher("parse") @given('Exists a team created by "{username}"') def step_impl(context, username): from django.contrib.auth.models import User user = User.objects.get(username=username) from sportsBetting.models import Team for row in context.table: team = Team(cr...
m_name).id context.browser.visit(context.get_url('/teams/edit/' + str(id))) @when('I edit the team') def step_impl(context): for
row in context.table: if context.browser.url.startswith(context.get_url('/teams/edit/')): form = context.browser.find_by_tag('form').first for heading in row.headings: context.browser.fill(str(heading), str(row[heading])) form.find_by_id('team_submit').first....
Akagi201/learning-python
pyramid/Pyramid Web开发入门/2. Python语言基础/fun_return.py
Python
mit
172
0
def
my_max(a, b): if a > b: return a elif b > a: return b else: return None x = my_max(1, 2) print x print my_max(3, 2
)
spladug/sutro
sutro/config.py
Python
bsd-3-clause
1,192
0
class ConfigurationError(Exception): def __init__(self, key, error): self.key = key self.error = error def __str__(self): return "%s: %s" % (self.key, self.error) def parse_config(config, spec, root=None): parsed = {} for key, parser_or_spec in spec.iteritems(): if roo...
= config[key_path] excep
t KeyError: raise ConfigurationError(key, "not found") try: parsed[key] = parser(raw_value) except Exception as e: raise ConfigurationError(key, e) elif isinstance(parser_or_spec, dict): subspec = parser_or_spec par...
yhoogstrate/segmentation-fold
scripts/energy-estimation-utility/segmentation_fold_utils/RNA.py
Python
gpl-3.0
1,466
0.006821
#!/usr/bin/env python """ segmentation-fold can predict RNA 2D structures including K-turns. Copyright (C) 2012-2016 Youri Hoogstrate This file is part of segmentation-fold and originally taken from yh-kt-fold. segmentation-fold is free software: you can redistribute it and/or modify it under the terms of the GNU Ge...
TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ class RNA: def __init__(self,name,sequence,organism,structures): self.
name = name self.organism = organism self.sequence = sequence self.structures = structures def get_sequence(self): return self.sequence def get_structures(self): return self.structures def get_unique_associated_segments(self): segments = [] ...
renmengye/imageqa-public
src/nn/selector.py
Python
mit
1,219
0.005742
from stage import * class Selector(Stage): def __init__(self, name, inputNames, start, end, axis=-1): Stage.__init__( self, name=name, inputNames=inputNam...
raise Exception('Selector axis=%d not supported' % axis) def forward(self, X): self.X = X if self.axis == -1: self.axis = len(X.shape) - 1 if self.axis == 0: return X[self.start:self.end] elif self.axis == 1: return X[:, self.star...
backward(self, dEdY): dEdX = np.zeros(self.X.shape) if self.axis == 0: dEdX[self.start:self.end] = dEdY elif self.axis == 1: dEdX[:, self.start:self.end] = dEdY elif self.axis == 2: dEdX[:, :, self.start:self.end] = dEdY return dEdX
renyi533/tensorflow
tensorflow/python/eager/context.py
Python
apache-2.0
74,821
0.007351
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ter_context_fn: (function.) A callable that executes the context switch. For example, `graph.as_default` or `eager_mode`. device_sta
ck: If applicable, the device function stack for this graph. When breaking out of graphs in init_scope, the innermost nonempty device stack is used. Eager contexts put `None` here and the value is never used. """ self.stack.append( ContextSwitch(is_b
ESOedX/edx-platform
common/djangoapps/static_replace/migrations/0001_initial.py
Python
agpl-3.0
1,125
0.004444
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
verbose_name='Enabled')), ('base_url', models.TextField(help_text=b'The alternative hostname to serve static assets from. Should be in the form of hostname[:port].', blank=True)), ('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings....
null=True, verbose_name='Changed by')), ], ), ]
qsheeeeen/Self-Driving-Car
06_have_fun.py
Python
mit
501
0
from rl_toolbox import Runner from rl_toolbox.agent import PPOAgent from rl_toolbox.policy import VAEPolicy, CNNPolicy def main(): fo
r fun in (VAEPolicy, CNNPolicy): runner = Runner( 'CarRacing-v0', PPOAgent, fun, record_data=False, data_path=None, save=False, load=True, weight_path='./weights/') runner.run({'tra
in': False}, num_episode=2) if __name__ == '__main__': main()
mirestrepo/voxels-at-lems
dbrec3d/bof/pca/learn_codebook/refined_init_k_means/k_means_on_CM_means.py
Python
bsd-2-clause
4,760
0.033613
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Mon Feb 14, 2011 @author:Isabel Restrepo A script to run (fast) k-means on J sets of random subsamples """ import os; import dbrec3d_batch import multiprocessing import Queue import time import random import optparse import sys from numpy import log, ceil from...
************The Main Algorithm ************************# if __name__=="__main__": dbrec3d_batch.register_processes(); dbrec3d_batch.register_datatypes(); #Parse inputs parser = optparse.OptionParser(description='bof Statistics Pass 0'
); parser.add_option('--init_k_means_dir', action="store", dest="init_k_means_dir"); parser.add_option('--num_cores', action="store", dest="num_cores", type="int", default=4); parser.add_option('--max_it', action="store", dest="max_it", type="int", default=100); options, args = parser.parse_args() init_...
carlgonz/u-fit
src/python/u_fit/modules/__init__.py
Python
mit
25
0
__aut
hor
__ = 'cgonzalez'
ncrmro/reango
server/users/schema/mutations.py
Python
mit
3,252
0.000615
from django.contrib.auth import authenticate, get_user_model from graphene import AbstractType, relay, Field, String, ObjectType, Union, List from users.jwt_schema import TokensSuccess from users.jwt_util import get_jwt_token from users.schema.definitions import Viewer class Error(ObjectType): """Form Errors ...
ername=email, password=password) jwt_token = get_jwt_token(user) if user and jwt_token: tokens = T
okensSuccess( jwt_token ) viewer = Viewer( user=user, tokens=tokens ) return LoginMutation(viewer) class SignupUserMutation(relay.ClientIDMutation): class Input: email = String(required=True) password =...
PythonCharmers/FunkLoad
src/funkload/tests/test_monitor_plugins.py
Python
gpl-2.0
1,940
0.008763
import unittest import time from ConfigParser import ConfigParser from funkload.MonitorPlugins import MonitorPlugins class TestMonitorPlugins(unittest.TestCase): default_plugins=['MonitorCPU', 'MonitorNetwork', 'MonitorMemFree', 'MonitorCUs'] def test_register_default(self): """ Make sure all default p...
plugins_loaded=p.MONITORS.keys() for plugin in self.default_plugins: self.assertTrue(plugin in plugins_loaded) def test_getStat(self): """ Make sure getStat does not raise any exception """ p=MonitorPlugins() p.registerPlugins() for plugin in self.default...
lf): """ Make sure self.interface is properly read from config in MonitorNetwork plugin """ conf=ConfigParser() conf.add_section('server') conf.set('server', 'interface', 'eth9') p=MonitorPlugins(conf) p.registerPlugins() self.assertTrue(p.MONITORS['MonitorNetwo...
neil-davis/penfold
src/plugins/PortCheckerPluginMock.py
Python
gpl-3.0
470
0
from random im
port randint from yapsy.IPlugin import IPlugin class PortCheckerPlugin(IPlugin): """ Mocked Version: Return random 0 or 1 as exit_code Takes an ip address and a port as inputs and trys to make a TCP connection to that port. Output is success 0 or failure > 0 """ def execute(self...
dint(0, 1)
mosra/m.css
plugins/m/test/test_gl.py
Python
mit
1,575
0.000636
# # This file is part of m.css. # # Copyright © 2017, 2018, 2019, 2020, 2021, 2022 # Vladimír Vondruš <mosra@centrum.cz> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Softwar...
UT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WI...
H THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # from . import PelicanPluginTestCase class Gl(PelicanPluginTestCase): def __init__(self, *args, **kwargs): super().__init__(__file__, '', *args, **kwargs) def test(self): self.run_pelican({ 'PLUGINS': ['m.htmlsanity...
madgik/exareme
Exareme-Docker/src/exareme/exareme-tools/madis/src/functions/row/termsetops.py
Python
mit
2,487
0.001206
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("sel...
ns operator: no input") tset = args[0] if not isinstance(args[1], int): raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: second argument s
hould be integer") yield ("C1",) for p in itertools.combinations(sorted(tset.split(' ')), args[1]): first = False yield [' '.join(p)] if first: yield [''] tsetcombinations.registered = True tsetcombinations.multiset = True if not ('.' in __name__): """ This is needed to...
hms-dbmi/fourfront
src/encoded/types/file.py
Python
mit
77,254
0.002291
import boto3 import datetime import json import logging import os import pytz import requests import structlog import transaction import urllib.parse from botocore.exceptions import ClientError from copy import deepcopy from pyramid.httpexceptions import ( HTTPForbidden, HTTPTemporaryRedirect, HTTPNotFound...
'FileSet'] + Item.base_types item_type = 'file_set_microscope_qc' schema = load_schema('encoded:schemas/file_set_microscope_qc.json') name_key = 'accession' embedded_list = Item.embedded_list + [ # User linkTo 'files_in_set.submitted_by.first_name', 'files_in_set.submitted_by.las...
tle', # Lab linkTo 'files_in_set.lab.title', 'files_in_set.lab.name', # File linkTo 'files_in_set.accession', 'files_in_set.href', 'files_in_set.file_size', 'files_in_set.upload_key', 'files_in_set.file_classification', # FileFormat link...
markofu/scripts
nmap/nmap/zenmap/zenmapGUI/DiffCompare.py
Python
gpl-2.0
22,982
0.000044
#!/usr/bin/env python # -*- coding: utf-8 -*- # ***********************IMPORTANT NMAP LICENSE TERMS************************ # * * # * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is * # * also a registered trademark of Inse...
ny of the * # * above.
* # * * # * o Executes a helper program, module, or script to do any of the above. * # * * # * This list is not exclusive,...
andybalaam/poemtube
server/src/poemtube/jsonapi/json_whoami.py
Python
gpl-2.0
644
0.037267
import json from poemtube.errors import InvalidRequest from poemtube.jsonapi.json_errors import JsonInvalidRequest def my_whoami( user ): if user: return { "userid": "http://example.com/oid/andy" } return { "userid": user } else: return { "anonymous" : "" } def do( fn, *args, **kwar...
ting the return value to JSON, and converting any exceptions to JSON exceptions. """ try: return json.dumps( fn( *args, **kwargs ) ) except Invalid
Request, e: raise JsonInvalidRequest( e ) def GET( user ): return do( my_whoami, user )
sgenoud/scikit-learn
sklearn/datasets/base.py
Python
bsd-3-clause
17,305
0.000058
""" Base IO code for all datasets """ # Copyright (c) 2007 David Cournapeau <cournape@gmail.com> # 2010 Fabian Pedregosa <fabian.pedregosa@inria.fr> # 2010 Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import os import csv import shutil from os import environ from os....
ively, it can be set by the 'SCIKIT_LEARN_DATA' environment variable or programatically by giving an explit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automat
ically created. """ if data_home is None: data_home = environ.get('SCIKIT_LEARN_DATA', join('~', 'scikit_learn_data')) data_home = expanduser(data_home) if not exists(data_home): makedirs(data_home) return data_home def clear_data_home(data_home=None)...
dcorio/l10n-italy
l10n_it_ipa/model/__init__.py
Python
agpl-3.0
301
0
# -*- coding: utf-8 -*- # Copyright 20
14 KTec S.r.l. # (<http://www.ktec.it>). # Copyright 2014 Associazione Odoo Italia # (<http://www.odoo-italia.org>). # Copyright 2016 Lorenzo Battistini - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import par
tner
FrozenPigs/Taigabot
plugins/_disabled/wordoftheday.py
Python
gpl-3.0
672
0.002976
import re from util import hook, http, misc from BeautifulSoup import Beauti
fulSoup @hook.command(autohelp=False) def word(inp, say=False, nick=False): "word -- Gets the word of the day." page = http.get('http://merriam-webster.com/word-of-the-day') soup = BeautifulSoup(page) word = soup.find('strong', {'class': 'main_entry_word'}).renderContents() function = soup.find(...
.renderContents() #definitions = re.findall(r'<span class="ssens"><strong>:</strong>' # r' *([^<]+)</span>', content) say("(%s) The word of the day is:"\ " \x02%s\x02 (%s)" % (nick, word, function))
shmup/miniboa
setup.py
Python
apache-2.0
2,304
0
import codecs import os import re from setuptools import setup, find_packages ################################################################### NAME = "miniboa" PACKAGES = find_packages(where="src") META_PATH = os.path.join("src", "miniboa", "__init__.py") KEYWORDS = ["mud", "tcp", "telnet"] CLASSIFIERS = [ "...
ntainer_email=find_meta("email"), keywords=KEYWORDS, long_description=read("README.rst"), packages=PACKAGES, package_dir={"": "s
rc"}, zip_safe=False, classifiers=CLASSIFIERS, install_requires=INSTALL_REQUIRES, )
FreedomCoop/valuenetwork
general/models.py
Python
agpl-3.0
55,292
0.006511
#encoding=utf-8 from django.utils.safestring import mark_safe from django.db import models from django.utils.six import python_2_unicode_compatible from mptt.models import MPTTModel from mptt.fields import TreeForeignKey, TreeManyToManyField from datetime import date, timedelta from datetime import datetime from dja...
import gettext_lazy as __ from decimal import Decimal from itertools import chain # Create your models here. a_strG = "<a onclick='return showRelatedObjectLookupPopup(this);' href='/admin/general/" a_strW = "<a onclick='return showRelatedObjectLookupPopup(this);' href='/admin/Welcome/" #a_str2 = "?_popup=1&_changeli...
filters=_popup=1&t=human' target='_blank' style='margin-left:-100px'>" a_str2 = "?_popup=1&t=human' target='_blank' >" a_str3 = "?_popup=1&t=human' target='_blank'>" a_edit = '<b>Edit</b>' ul_tag1 = '<ul style="margin-left:-10em;">' ul_tag = '<ul>' str_none = __('(none)') str_remove = 'erase' def erase_id_link(fiel...
Distrotech/bzr
tools/rst2html.py
Python
gpl-2.0
1,883
0.003717
#! /usr/bin/env python # Originally by Dave Goodger, from the docutils, distribution. # # Modified for Bazaar to accommodate options containing dots # # This file is in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL,...
x.replace('id="tags"', 'id="tags_"') y = y.replace('name="tags"', 'name="tags_"') y = y.replace('
href="#tags"', 'href="#tags_"') return y mywriter = html4css1.Writer() mywriter.translator_class = IESafeHtmlTranslator publish_cmdline(writer=mywriter, description=description)
bcbnz/pylabels
labels/specifications.py
Python
gpl-3.0
17,105
0.001812
# This file is part of pylabels, a Python library to create PDFs for printing # labels. # Copyright (C) 2012, 2013, 2014, 2015 Blair Bonnett # # pylabels is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either ...
precedence. Raises ------ InvalidDimension If any given dimension is invalid (i.e., the labels cannot fit on the sheet). """ # Compulsory arguments. self._sheet_width = Decimal(sheet_width) self._sheet_height = Decimal(sheet_height) ...
self._columns = int(columns) self._rows = int(rows) self._label_width = Decimal(label_width) self._label_height = Decimal(label_height) # Optional arguments; missing ones will be computed later. self._left_margin = kwargs.pop('left_margin', None) self._column_gap = kwar...
GHubgenius/clusterd
src/platform/jboss/fingerprints/JBoss5WC.py
Python
mit
196
0.005102
from src.platform.jboss.inter
faces import WebConsoleInterface class FPrint(WebConsoleInterface): def __init__(self): super(FPrint, self).__init__() self.version = "
5.0"
immanetize/nikola
nikola/plugins/task/sources.py
Python
mit
3,426
0.00146
# -*- coding: utf-8 -*- # Copyright © 2012-2015 Roberto Alsina and others. # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including without limitation # the rights t...
urces into the output.""" name = "render_sources" def gen_tasks(self): """Publish the page sources into the output. Required keyword arguments: translations default_lang post_pages output_folder """ kw = { "translations": self.site....
ow_untranslated_posts": self.site.config['SHOW_UNTRANSLATED_POSTS'], } self.site.scan_posts() yield self.group_task() if self.site.config['COPY_SOURCES']: for lang in kw["translations"]: for post in self.site.timeline: if not kw["show_untr...
arpith/zulip
zerver/management/commands/realm_filters.py
Python
apache-2.0
2,982
0.003689
from __
future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from optparse import make_option from django.core.management.base import BaseCommand from zerv
er.models import RealmFilter, all_realm_filters, get_realm_by_string_id from zerver.lib.actions import do_add_realm_filter, do_remove_realm_filter import sys class Command(BaseCommand): help = """Create a link filter rule for the specified domain. NOTE: Regexes must be simple enough that they can be easily transl...
ryancoleman/autodock-vina
boost_1_54_0/tools/build/v2/tools/msvc.py
Python
apache-2.0
55,098
0.008766
# Copyright (c) 2003 David Abrahams. # Copyright (c) 2005 Vladimir Prus. # Copyright (c) 2005 Alexey Pakhunov. # Copyright (c) 2006 Bojan Resnik. # Copyright (c) 2006 Ilya Sokolov. # Copyright (c) 2007 Rene Rivera # Copyright (c) 2008 Jurko Gospodnetic # Copyright (c) 2011 Juraj Ivancic # # Use, modification and distri...
r Create "a.b" Create "a.b" # # "x.y" - refers to a detected version; # "a.b" - refers to an undetected version. # # FIXME: Currently the command parameter and the <compiler> property parameter # seem to overlap in duties. Remove this duplication. This seems to be related # to why someone started preparin...
element list i.e. ['x.0'], # but when specified from the command line we get a string i.e. 'x.0'. # We want to work with a string, so unpack the list if needed. is_single_element_list = (isinstance(version,list) and len(version) == 1) assert(version==None or isinstance(version,str) or is_single_element_...
iamahuman/angr
tests/test_concrete_packed_elf32.py
Python
bsd-2-clause
3,926
0.006113
import angr import claripy import nose import os import subprocess try: import avatar2 from angr_targets import AvatarGDBConcreteTarget except ImportError: raise nose.SkipTest() binary_x86 = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.join('..', '..', 'bina...
@nose.with_setup(setup_x86, teardown) def test_concrete_engine_linux_x86_no_simprocedures(): #print("test_concrete_engine_linux_x86_no_simprocedures") global avatar_gdb # pylint: disable=no-member avatar_gdb = AvatarGDBConcreteTarget(avatar2.archs.x86.X86, GDB_SERVER_IP, GDB_SERVER_PORT) p = angr.Pr...
entry_state = p.factory.entry_state() solv_concrete_engine_linux_x86(p, entry_state) @nose.with_setup(setup_x86, teardown) def test_concrete_engine_linux_x86_unicorn_no_simprocedures(): #print("test_concrete_engine_linux_x86_unicorn_no_simprocedures") global avatar_gdb # pylint: disable=no-member ...
kleebaum/bayeosraspberrypi
bayeosraspberrypi/bayeosraspberrypiclient.py
Python
gpl-2.0
3,774
0.005299
"""Python script to measure temperature, humidity and CO2 concentration with a Raspberry Pi. A SHT21 sensor and a MCP3424 analog digital converter are connected to gpio pins, i.e. to the I2C bus. The BayEOSGatewayClient class is extended to transfer data to the BayEOSGateway. The sender runs in a separate process. Orig...
ared = lin_model[2]*lin_model[2] slope_err = lin_model[4] return [mean_temp, var_temp, mean_hum, var_hum, slope, intercept, r_squared, slope_err] OPTIONS = bayeos_confparser('../config/baye
osraspberrypi.ini') client = RaspberryPiClient(OPTIONS['name'], OPTIONS) client.run(thread=False) # sender runs in a separate process
peterwilletts24/Monsoon-Python-Scripts
vort_and_div/vorticity_and_diverg.py
Python
mit
613
0.022838
""" Load winds on pressure levels and calculate vorticity and divergence """ import os, sys import datetime import iris import iris.unit as unit diag = '30201' cube_name_u='eastward_wind' cube_name_v='northward_wind' pp_file_path='/projects/cascade/pwille/moose_retriev
als/' #experiment_ids = ['djznw', 'djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu'
, 'dklzq'] # All minus large 3 experiment_ids = ['djznw'] for experiment_id in experiment_ids: expmin1 = experiment_id[:-1] #fu = '/projects/cascade/pwille/moose_retrievals/%s/%s/%s.pp' % (expmin1, experiment_id, diag) try: print 'hello'
CingHu/neutron-ustack
neutron/tests/unit/ofagent/test_arp_lib.py
Python
apache-2.0
13,264
0.000075
# Copyright (C) 2014 VA Linux Systems Japan K.K. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
g.buffer_id = self.ofproto.OFP_NO_BUFFER self.arplib._send_unknown_packet(self.msg, in_port, out_port) actions = [self.ofp
p.OFPActionOutput(self.ofproto.OFPP_TABLE, 0)] self.ofpp.OFPPacketOut.assert_called_once_with( datapath=self.datapath, buffer_id=self.msg.buffer_id, in_port=in_port, actions=actions, data=self.msg_data) def test__send_unknown_packet_existence_buff...
artdent/jgments
lib/pygments-1.2.2-patched/pygments/lexers/web.py
Python
bsd-2-clause
31,156
0.001605
# -*- coding: utf-8 -*- """ pygments.lexers.web ~~~~~~~~~~~~~~~~~~~ Lexers for web-related languages and markup. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re try: set except NameError: from sets import Set as set ...
lter|Grad
ientType|Graphics|GridFitType|HTTPStatusEvent|' r'IBitmapDrawable|ID3Info|IDataInput|IDataOutput|IDynamicPropertyOutput' r'IDynamicPropertyWriter|IEventDispatcher|IExternalizable|' r'IllegalOperationError|IME|IMEConversionMode|IMEEvent|int|' r'InteractiveObject|Interp...
leppa/home-assistant
homeassistant/components/alexa/config.py
Python
apache-2.0
2,151
0
"""Config helpers for Alexa.""" from homeassistant.core import callback from .state_report import async_enable_proactive_mode class AbstractConfig: """Hold the configuration for Alexa.""" _unsub_proactive_report = None def __init__(self, hass): """Initialize abstract config.""" self.has...
if unsub_func: unsub_func() self._unsub_proactive_report = None @callback def should_expose(self, entity_id): """If an entity should be exposed.""" # pylint: disable=no-self-use return False @callback def async_invalidate_access_token(self): ""...
async def async_get_access_token(self): """Get an access token.""" raise NotImplementedError async def async_accept_grant(self, code): """Accept a grant.""" raise NotImplementedError
sosey/ginga
ginga/qtw/plugins/Catalogs.py
Python
bsd-3-clause
19,290
0.003784
# # Catalogs.py -- Catalogs plugin for fits viewer # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # from __future__ import print_function from ginga.qtw.QtHelp import ...
combobox.addItem(name) index += 1 index = 0 combobox.setCurrentIndex(index) combobox.activated.connect(self.setup_params_image) if len(self.image_server_options) > 0: self.setup_params_image(index, redo=False) vbox = QtHelp.VBox() fr = QtHe...
ch=0, alignment=QtCore.Qt.AlignLeft) captions = (('Server', 'xlabel'), ('@Server', 'combobox'), ('Limit stars to area', 'checkbutton'), ('Search', 'button')) w, self.w2 = QtHelp.build_info(captions) self.w2.search.clicked.connect(self....
MaxHalford/Prince
tests/test_pca.py
Python
mit
3,331
0.002101
import unittest import matplotlib as mpl import numpy as np import pandas as pd from sklearn import datasets from sklearn import decomposition from sklearn.utils import estimator_checks import prince class TestPCA(u
nittest.TestCase): def setUp(self): X, _ = datasets.load_iris(return_X_y=True) columns = ['Sepal length', 'Sepal width', 'Petal length', 'Sepal length'] self.X = pd.DataFrame(X, columns=columns) def test_fit_pandas_dataframe(self): pca = prince.PCA(n_components=2, engine='fbpca...
nce.PCA(n_components=2) self.assertTrue(isinstance(pca.fit(self.X).transform(self.X), pd.DataFrame)) def test_fit_numpy_array(self): pca = prince.PCA(n_components=2, engine='fbpca') self.assertTrue(isinstance(pca.fit(self.X.values), prince.PCA)) def test_transform_numpy_array(self): ...
gion86/awlsim
awlsim/gui/hwmodconfig.py
Python
gpl-2.0
12,877
0.029976
# -*- coding: utf-8 -*- # # AWL simulator - GUI hardware module configuration widget # # Copyright 2015 Michael Buesch <m@bues.ch> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either versio...
getIcon("next")) self.addButton.setToolTip("A
dd the selected module to the " "project\nand mark it for download to the CPU.") vbox.addWidget(self.addButton) self.delButton = QPushButton(self) self.delButton.setIcon(getIcon("previous")) self.delButton.setToolTip("Remove the selected module from " "the project\nand mark it for removal from the CPU.") ...
dharmabumstead/ansible
lib/ansible/modules/system/firewalld.py
Python
gpl-3.0
35,378
0.001555
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Adam Miller (maxamillion@fedoraproject.org) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version':...
) :permanent: bool, action should be permanent :immediate: bool, action should take place immediately :fw_offline: bool, action takes place as if the firewall were offline :enabled_values: str[], acceptable values for enabling something (default: enabled) :disab...
table values for disabling something (default: disabled) """ self.fw = fw self.action_args = action_args self.zone = zone self.desired_state = desired_state self.permanent = permanent self.immediate = immediate self.fw_offline = fw_offline self.en...
wzhy90/git-repo
subcmds/sync.py
Python
apache-2.0
27,721
0.010065
# # Copyright (C) 2008 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
rom optparse import SUPPRESS_HELP import os import re import shutil import socket
import subprocess import sys import time from pyversion import is_python3 if is_python3(): import urllib.parse import xmlrpc.client else: import imp import urlparse import xmlrpclib urllib = imp.new_module('urllib') urllib.parse = urlparse xmlrpc = imp.new_module('xmlrpc') xmlrpc.client = xmlrpclib ...
reubano/tabutils
meza/io.py
Python
mit
52,280
0.000134
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ meza.io ~~~~~~~ Provides methods for reading/writing/processing tabular formatted files Examples: basic usage:: >>> from meza.io import read_csv >>> >>> path = p.join(DATA_DIR, 'test.csv') >>> csv_record...
ls as ft, process as pr, unicsv as csv, dbf, ENCODING, BOM, DATA_DIR) # pylint: disable=C0103 logger = gogo.Gogo(__name__, monolog=True, verbose=True).logger # pylint: disable=C0103 encode = lambda iterable: (s.encode(ENCODING) for s in iterable) chain = lambda iterable: it.chain.from_iterable(iterable or []) NEWLIN...
terable, lambda s: s not in NEWLINES) class IterStringIO(TextIOBase): """A lazy StringIO that reads a generator of strings. https://stackoverflow.com/a/32020108/408556 https://stackoverflow.com/a/20260030/408556 """ # pylint: disable=super-init-not-called def __init__(self, iterable=None, buf...
tavaresdong/courses
ucb_cs61A/lab/lab10/reader.py
Python
mit
3,571
0.00308
import string from buffer import Buffer from expr import * SYMBOL_STARTS = set(string.ascii_lowercase + string.ascii_uppercase + '_') SYMBOL_INNERS = SYMBOL_STARTS | set(string.digits) NUMERAL = set(string.digits + '-.') WHITESPACE = set(' \t\n\r') DELIMITERS = set('(),:') def tokenize(s):
"""Splits the string s into tokens and returns a list of them. >>> tokenize('lambda f: f(0, 4.2)') ['lambda', 'f', ':', 'f', '(', 0, ',', 4.2, ')'] """ src = Buffer(s) tokens = [] while True: token = next_token(src) if token is None: return tokens tokens...
ent() in allowed_characters: result += src.pop() return result def next_token(src): take(src, WHITESPACE) # skip whitespace c = src.current() if c is None: return None elif c in NUMERAL: literal = take(src, NUMERAL) try: return int(literal) excep...
alexholcombe/dot-jump
dataRaw/Fixed Cue/test_dot-jump25Oct2016_10-53.py
Python
gpl-3.0
25,090
0.019131
from __future__ import print_function __author__ = """Alex "O." Holcombe, Charles Ludowici, """ ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor import time, sys, platform, os from math import atan, atan2, pi, cos, sin, sqrt, ceil, radians, degrees import numpy as np import psychopy, ...
Rate = infoFirst['Screen refresh rate'] #monitor parameters widthPix = 1280 #1440 #monitor width in pixels heightPix =1024 #900 #monitor height in pixels monitorwidth = 40.5 #28.5 #monitor width in centimeters viewdist = 55.; #cm pixelperdegree = widthPix/ (atan(monito...
[-1,-1,-1] #black background monitorname = 'testMonitor' # 'mitsubishi' #in psychopy Monitors Center mon = monitors.Monitor(monitorname,width=monitorwidth, distance=viewdist)#fetch the most recent calib for this monitor mon.setSizePix( (widthPix,heightPix) ) myWin = openMyStimWindow(mon...
Distrotech/samba
wintest/test-s4-howto.py
Python
gpl-3.0
29,309
0.005357
#!/usr/bin/env python '''automated testing of the steps of the Samba4 HOWTO''' import sys, os import wintest, pexpect, time, subprocess def set_krb5_conf(t): t.putenv("KRB5_CONFIG", '${PREFIX}/private/krb5.conf') def build_s4(t): '''build samba4''' t.info('Building s4') t.chdir('${SOURCETREE}') ...
ename"]) t.cmd_co
ntains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -k no -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"]) t.cmd_contains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -k yes -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"]) child = t.open_telnet("${WIN_HOSTNAME}", "${DOMAI...
enormandeau/Scripts
fastq_split.py
Python
gpl-3.0
2,096
0.00334
#!/usr/bin/env python2 """Split a fastq file in n files of approximately the same number of sequences Usage: python fastq_remove.py input_file num_seq_per_file input_file = input Fastq file num_seq_per_file = number of sequences to put in each output files """ # Importing modules import sys # Defining classes...
ut_file_name, "w") for s in sequences: seq_num += 1 if seq_num > num_seq_per_file: output_file_number += 1 seq_num = 1 output_file.close()
output_file_name = input_file + "_split_" + str(output_file_number) output_file = open(output_file_name, "w") s.write_to_file(output_file)
hagabbar/pycbc_copy
pycbc/workflow/configuration.py
Python
gpl-3.0
38,216
0.004344
# Copyright (C) 2013,2017 Ian Harry, Duncan Brown # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 3 of the License, or (at your # option) any later version. # # This program is ...
e for git.ligo.org by running ecp-cookie-init LIGO.ORG https://git.ligo.org/users/auth/shibboleth/callback albert.einstein before attempting to download files from git.ligo.org. """ def resolve_url(url, directory=None, permissions=None): """ Resolves a URL to a local file, and returns the path to that fi...
me of the destination file if directory is None: directory = os.getcwd() filename = os.path.join(directory,os.path.basename(u.path)) if u.scheme == '' or u.scheme == 'file': # for regular files, make a direct copy if os.path.isfile(u.path): if os.path.isfile(filename): ...
googleinterns/data-dependency-graph-analysis
deprecated/process_config.py
Python
apache-2.0
4,187
0.005254
"""Graph Generation Config Reader This script reads the config from full_config.yaml file and processes it to be usable. It saves config to variables, and converts map strings to python dictionaries. """ import yaml from graph_generation.connection_generator import ConnectionGenerator from graph_generation.config_par...
values()]
return {keys[i]: values[i] for i in range(len(keys))} if __name__ == '__main__': # Read config file with open('configs/full_config.yaml', 'r') as f: config = yaml.load(f, Loader=yaml.FullLoader) dataset_params = DatasetParams( dataset_count=config["dataset"]["dataset_count"], ...
peterstace/project-euler
OLD_PY_CODE/project_euler_old_old/Resources/graph_theory.py
Python
unlicense
3,807
0.00394
"""This module provides graph theory functionality.""" from heapq import heapify, heappop, heappush def dijkstra(nodes, edges, startNode, directed): """Finds the length between each node in the graph and the startNode. Arguments: nodes - the set of nodes in the graph. edges - the set of edges ...
stance = dict([(node, float("inf")) for node in nodes]) distance[startNode] = 0 #mark every node as unvisited visited = dict([(node, False) for node in nodes]) #main part of algorithm unvisitedQ = [(0, startNode)] unvisitedQSet = set([startNode]) while len(unvi
sitedQ) != 0: currentNode = heapq.heappop(unvisitedQ)[1] unvisitedQSet.remove(currentNode) for (node, edgeWeight) in neighbours[currentNode]: if not visited[node]: if distance[currentNode] + edgeWeight < distance[node]: distance[node] = distance[cu...
varlib1/servermall
marathon/test_marathon.py
Python
bsd-3-clause
2,285
0.001751
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # stdlib import os # project from tests.checks.common import AgentCheckTest, Fixtures DEPLOYMENT_METRICS_CONFIG = { 'init_config': { 'default_timeout': 5 }, 'instances': [ { ...
Fixtures.read_json_file("queue.json", sdk_dir=ci_dir) else: raise Exception("unknown url:" + url) self.run_check(DEFAULT_CONFIG, mocks={"get_json": side_effect}) self.assertMetric('mar
athon.apps', value=1) self.assertMetric('marathon.deployments', value=1) for metric in Q_METRICS: self.assertMetric(metric, at_least=1) def test_empty_responses(self): def side_effect(url, timeout, auth, acs_url, verify): if "v2/apps" in url: return ...
oppianmatt/django-loki
src/loki/models.py
Python
gpl-3.0
9,165
0.003273
# Copyright 2008-20
10, Red Hat, Inc # Dan Radez <dradez@redhat.com> # # This software may be freely redistributed under the terms of the GNU # general public license. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambri...
odels from django.db.models.signals import post_save from django.db.models.signals import post_delete from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from loki.settings import * from loki.bind_administration import bind_administration from loki.signal_receiver...
yershalom/python-jenkins
tests/test_jenkins.py
Python
bsd-3-clause
75,211
0.000186
import json import socket import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest from mock import patch, Mock import six from six.moves.urllib.error import HTTPError from six.moves.urllib.request import build_opener import jenkins def get_mock_urlopen_return_value(a_dict...
aybe_add_crumb(request) self.assertEqual( jenkin
s_mock.call_args[0][0].get_full_url(), 'http://example.com/crumbIssuer/api/json') self.assertFalse(j.crumb) self.assertFalse('.crumb' in request.headers) self._check_requests(jenkins_mock.call_args_list) @patch('jenkins.urlopen') def test_maybe_add_crumb__with_data(self, jen...
repotvsupertuga/tvsupertuga.repository
script.module.openscrapers/lib/openscrapers/sources_openscrapers/scrapertest-yoda/to_be_fixed/__init__.py
Python
gpl-2.0
77
0
# M
akes this into a package, so it's
not loaded by the 'sources()' function.
ArcherSys/ArcherSys
Lib/distutils/command/install_headers.py
Python
mit
4,034
0.005949
<<<<<<< HEAD <<<<<<< HEAD """distutils.command.install_headers Implements the Distutils 'install_headers' command, to install C/C++ header files to the Python include directory.""" from distutils.core import Command # XXX force is never used class install_headers(Command): description = "install C/C++ header f...
dir'), ('force', 'force')) def run(self): headers = self.distribution.headers if not headers: return self.mkpath(self.install_dir) for header in headers: (out, _) = self.copy_file(header, self.install_dir) self...
rn self.outfiles >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= """distutils.command.install_headers Implements the Distutils 'install_headers' command, to install C/C++ header files to the Python include directory.""" from distutils.core import Command # XXX force is never used class install_headers(Comm...
Suwmlee/XX-Net
gae_proxy/server/lib/google/appengine/ext/db/polymodel.py
Python
bsd-2-clause
12,820
0.00507
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
_class
_hierarchy__ == [Foo, Bar, Baz] Unless the class is a root class or PolyModel itself, it is not inserted in to the kind-map like other models. However, all polymorphic classes, are inserted in to the class-map which maps the class-key to implementation. This class key is consulted using the polymorph...
ratoaq2/Flexget
flexget/plugins/input/listdir.py
Python
mit
1,908
0.001048
"""Plugin for filesystem tasks.""" from __future__ import unicode_literals, division, absolute_import import os import logging from path impo
rt Path from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.config_schema import one_or_more log = logging.getLogger('listdir') class Listdir(object): """ Uses local path content as an input.
Example:: listdir: /storage/movies/ """ schema = one_or_more({'type': 'string', 'format': 'path'}) def on_task_input(self, task, config): # If only a single path is passed turn it into a 1 element list if isinstance(config, basestring): config = [config] entr...
amdouglas/OpenPNM
test/unit/Utilities/TransformationsTest.py
Python
mit
100
0
class TransformationsTest:
class ArcBall
Test: def test_set_axes(self): pass
antonygc/liblightbase
liblightbase/lbsearch/search.py
Python
gpl-2.0
5,160
0.003682
from liblightbase import lbutils from liblightbase.lbutils.conv import dict2document class OrderBy(object): """ The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. To sort the records in a ascending order, you c...
rty asc getter """ return self._desc @desc.setter
def desc(self, value): """ @property asc setter """ msg = 'desc property must be list object.' assert isinstance(value, list), msg self._desc = value def _asjson(self, **kw): dict_orderby = {} for key in dir(self): if not key[0] == "_": ...
ballouche/navitia
source/jormungandr/jormungandr/interfaces/v1/Ptobjects.py
Python
agpl-3.0
5,265
0.003039
# coding=utf-8 # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility an...
nt("count", type=default_count_arg_type, default=10, description="The maximum number of\ ptobjects returned") self.parsers["get"].add_argument("search_type", type=int, default=0, d
escription="Type of search:\ firstletter or type error") self.parsers["get"].add_argument("admin_uri[]", type=unicode, action="append", description="If filled, will\ ...
giliam/turbo-songwriter
backend/songwriter/tests.py
Python
mit
75
0
# coding:utf-8 from dja
ngo.test import TestCase # Create your te
sts here.