text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def database_backup(self, data_directory, *args, **kwargs): """Uploads a PostgreSQL file cluster to S3 or Windows Azure Blob Service Mechanism: just wraps _upload_pg_cluster_dir with start/stop backup actions with exception handling. In particular there is a 'finally' block to ...
[ "def", "database_backup", "(", "self", ",", "data_directory", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "upload_good", "=", "False", "backup_stop_good", "=", "False", "while_offline", "=", "False", "start_backup_info", "=", "None", "if", "'while_off...
44.629213
20.797753
def includeme(config): """ Activate the ``pyramid_retry`` execution policy in your application. This will add the :func:`pyramid_retry.RetryableErrorPolicy` with ``attempts`` pulled from the ``retry.attempts`` setting. The ``last_retry_attempt`` and ``retryable_error`` view predicates are regi...
[ "def", "includeme", "(", "config", ")", ":", "settings", "=", "config", ".", "get_settings", "(", ")", "config", ".", "add_view_predicate", "(", "'last_retry_attempt'", ",", "LastAttemptPredicate", ")", "config", ".", "add_view_predicate", "(", "'retryable_error'", ...
32.735294
22.558824
def dataframe(self): """Build and cache a dataframe from query results""" if self._dataframe is None: try: import pandas as pd except ImportError: raise RuntimeError('To enable dataframe support, ' 'run \'pip ins...
[ "def", "dataframe", "(", "self", ")", ":", "if", "self", ".", "_dataframe", "is", "None", ":", "try", ":", "import", "pandas", "as", "pd", "except", "ImportError", ":", "raise", "RuntimeError", "(", "'To enable dataframe support, '", "'run \\'pip install datadotwo...
37.071429
23.214286
def events(self): """ All events in calendar within specified time range """ if self._events is None: self._events = self.parent.calendar.events( calendarId="primary", singleEvents=True, orderBy="startTime", timeMin=self.since, timeMax=self.until) retu...
[ "def", "events", "(", "self", ")", ":", "if", "self", ".", "_events", "is", "None", ":", "self", ".", "_events", "=", "self", ".", "parent", ".", "calendar", ".", "events", "(", "calendarId", "=", "\"primary\"", ",", "singleEvents", "=", "True", ",", ...
47
15.857143
def _print_MatMul(self, expr): """ Matrix multiplication printer. The sympy one turns everything into a dot product without type-checking. """ from sympy import MatrixExpr links = [] for i, j in zip(expr.args[1:], expr.args[:-1]): if isinstance(i, Matr...
[ "def", "_print_MatMul", "(", "self", ",", "expr", ")", ":", "from", "sympy", "import", "MatrixExpr", "links", "=", "[", "]", "for", "i", ",", "j", "in", "zip", "(", "expr", ".", "args", "[", "1", ":", "]", ",", "expr", ".", "args", "[", ":", "-...
39.352941
11.823529
def get_object_id_from_graph(access_token=None): '''Return the object ID for the Graph user who owns the access token. Args: access_token (str): A Microsoft Graph access token. (Not an Azure access token.) If not provided, attempt to get it from MSI_ENDPOINT. Returns: ...
[ "def", "get_object_id_from_graph", "(", "access_token", "=", "None", ")", ":", "if", "access_token", "is", "None", ":", "access_token", "=", "get_graph_token_from_msi", "(", ")", "endpoint", "=", "'https://'", "+", "GRAPH_RESOURCE_HOST", "+", "'/v1.0/me/'", "headers...
39.882353
27.764706
def locked(self): """ Determines if the queue is locked. """ if len(self.failed) == 0: return False for fail in self.failed: for job in self.active_jobs: if fail.alias in job.depends_on: return True
[ "def", "locked", "(", "self", ")", ":", "if", "len", "(", "self", ".", "failed", ")", "==", "0", ":", "return", "False", "for", "fail", "in", "self", ".", "failed", ":", "for", "job", "in", "self", ".", "active_jobs", ":", "if", "fail", ".", "ali...
34.375
8.875
async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: """Make an HTTP request.""" if method == "GET" and not body: real_body = None else: real_body = body requ...
[ "async", "def", "_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", "=", "b''", ")", "->", "Tuple", "[", "int", ",", "Mapping", "[", ...
52.615385
20.846154
def req(self, url, method='get', params=None, data=None, auth=False): """ 请求API :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: dict ...
[ "def", "req", "(", "self", ",", "url", ",", "method", "=", "'get'", ",", "params", "=", "None", ",", "data", "=", "None", ",", "auth", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "'fetch api<%s:%s>'", "%", "(", "method", ",", ...
32.058824
21.411765
def _prepare(cls, context: Dict) -> Dict: """This is where you should alter the context to fit the action. Default behaviour will leave the context as it is. """ if not context and cls.raise_empty_context: raise PolyaxonActionException('{} received invalid payload context.'....
[ "def", "_prepare", "(", "cls", ",", "context", ":", "Dict", ")", "->", "Dict", ":", "if", "not", "context", "and", "cls", ".", "raise_empty_context", ":", "raise", "PolyaxonActionException", "(", "'{} received invalid payload context.'", ".", "format", "(", "cls...
39.222222
20.666667
def tsToDf(tso): """ Create Pandas DataFrame from TimeSeries object. Use: Must first extractTs to get a time series. Then pick one item from time series and pass it through :param dict tso: Time series entry :return dict dfs: Pandas dataframes """ dfs = {} try: dfs = ts_to_df(ts...
[ "def", "tsToDf", "(", "tso", ")", ":", "dfs", "=", "{", "}", "try", ":", "dfs", "=", "ts_to_df", "(", "tso", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Error: Unable to create data frame\"", ")", "logger_start", ".", "warn", "(", "\"ts_...
31.266667
19.666667
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
[ "def", "MethodCalled", "(", "self", ",", "mock_method", ")", ":", "# Check to see if this method exists, and if so, remove it from the set", "# and return it.", "for", "method", "in", "self", ".", "_methods", ":", "if", "method", "==", "mock_method", ":", "# Remove the ca...
33.757576
25.030303
def get_rules(family='ipv4'): ''' Return a data structure of the current, in-memory rules CLI Example: .. code-block:: bash salt '*' nftables.get_rules salt '*' nftables.get_rules family=ipv6 ''' nft_family = _NFTABLES_FAMILIES[family] rules = [] cmd = '{0} --numeric...
[ "def", "get_rules", "(", "family", "=", "'ipv4'", ")", ":", "nft_family", "=", "_NFTABLES_FAMILIES", "[", "family", "]", "rules", "=", "[", "]", "cmd", "=", "'{0} --numeric --numeric --numeric '", "'list tables {1}'", ".", "format", "(", "_nftables_cmd", "(", ")...
28.645161
20.580645
def load(target:str, namespace:str=None, default=nodefault, executable:bool=False, separators:Sequence[str]=('.', ':'), protect:bool=True): """This helper function loads an object identified by a dotted-notation string. For example:: # Load class Foo from example.objects load('example.objects:Foo') # L...
[ "def", "load", "(", "target", ":", "str", ",", "namespace", ":", "str", "=", "None", ",", "default", "=", "nodefault", ",", "executable", ":", "bool", "=", "False", ",", "separators", ":", "Sequence", "[", "str", "]", "=", "(", "'.'", ",", "':'", "...
30.604167
28.020833
def base_boxes(self): """ Get the list of vagrant base boxes """ return sorted(list(set([name for name, provider in self._box_list()])))
[ "def", "base_boxes", "(", "self", ")", ":", "return", "sorted", "(", "list", "(", "set", "(", "[", "name", "for", "name", ",", "provider", "in", "self", ".", "_box_list", "(", ")", "]", ")", ")", ")" ]
32.8
12
def usb( ctx, enable, disable, list, enable_all, touch_eject, no_touch_eject, autoeject_timeout, chalresp_timeout, lock_code, force): """ Enable or disable applications over USB. """ def ensure_not_all_disabled(ctx, usb_enabled): for app in APPLICATION: if app & usb_...
[ "def", "usb", "(", "ctx", ",", "enable", ",", "disable", ",", "list", ",", "enable_all", ",", "touch_eject", ",", "no_touch_eject", ",", "autoeject_timeout", ",", "chalresp_timeout", ",", "lock_code", ",", "force", ")", ":", "def", "ensure_not_all_disabled", "...
31.786408
18.893204
def ReadAttachments(self, document_link, options=None): """Reads all attachments in a document. :param str document_link: The link to the document. :param dict options: The request options for the request. :return: Query Iterable of Attachments. ...
[ "def", "ReadAttachments", "(", "self", ",", "document_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "return", "self", ".", "QueryAttachments", "(", "document_link", ",", "None", ",", "options", ...
27.166667
17.277778
def list_corpora(self): """Show corpora available for the CLTK to download.""" try: # corpora = LANGUAGE_CORPORA[self.language] corpora = self.all_corpora corpus_names = [corpus['name'] for corpus in corpora] return corpus_names except (NameError, ...
[ "def", "list_corpora", "(", "self", ")", ":", "try", ":", "# corpora = LANGUAGE_CORPORA[self.language]", "corpora", "=", "self", ".", "all_corpora", "corpus_names", "=", "[", "corpus", "[", "'name'", "]", "for", "corpus", "in", "corpora", "]", "return", "corpus_...
44.727273
14.909091
def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True): """ Downsample the number of vertices in a mesh. :param float fraction: the desired target of reduction. :param int N: the desired number of final points (**fraction** is recalculated based on it). :param ...
[ "def", "decimate", "(", "self", ",", "fraction", "=", "0.5", ",", "N", "=", "None", ",", "boundaries", "=", "False", ",", "verbose", "=", "True", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "if", "N", ":", "# N = desired number ...
39.96875
19.46875
def get_sdf(identifier, namespace='cid', domain='compound',operation=None, searchtype=None, **kwargs): """Request wrapper that automatically parses SDF response and supresses NotFoundError.""" try: return get(identifier, namespace, domain, operation, 'SDF', searchtype, **kwargs).decode() except NotF...
[ "def", "get_sdf", "(", "identifier", ",", "namespace", "=", "'cid'", ",", "domain", "=", "'compound'", ",", "operation", "=", "None", ",", "searchtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "get", "(", "identifier", ","...
52.714286
29.142857
def get_path_name(self): """Gets path and name of song :return: Name of path, name of file (or folder) """ path = fix_raw_path(os.path.dirname(os.path.abspath(self.path))) name = os.path.basename(self.path) return path, name
[ "def", "get_path_name", "(", "self", ")", ":", "path", "=", "fix_raw_path", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "self", ".", "path", ")", ")", ")", "name", "=", "os", ".", "path", ".", "basename", ...
33.25
15
def buildCommand(self,fileName,count,args): """ This is an internal method, building the command for a particular file. """ # Escape all placeholders in the file path: fileNameWithPath = self.escapePlaceholders(fileName) # The command is split into 'parts', which are separated ...
[ "def", "buildCommand", "(", "self", ",", "fileName", ",", "count", ",", "args", ")", ":", "# Escape all placeholders in the file path:", "fileNameWithPath", "=", "self", ".", "escapePlaceholders", "(", "fileName", ")", "# The command is split into 'parts', which are separat...
48.2
20.066667
def chmod(path, mode, recursive=True): """ alternative to os. """ if recursive: cmd = 'chmod -R %s %s' % (mode, path) else: cmd = 'chmod %s %s' % (mode, path) return sh(cmd)
[ "def", "chmod", "(", "path", ",", "mode", ",", "recursive", "=", "True", ")", ":", "if", "recursive", ":", "cmd", "=", "'chmod -R %s %s'", "%", "(", "mode", ",", "path", ")", "else", ":", "cmd", "=", "'chmod %s %s'", "%", "(", "mode", ",", "path", ...
20.2
16.5
def aggregate_stat(origin_stat, new_stat): """ aggregate new_stat to origin_stat. Args: origin_stat (dict): origin stat dict, will be updated with new_stat dict. new_stat (dict): new stat dict. """ for key in new_stat: if key not in origin_stat: origin_stat[key] = n...
[ "def", "aggregate_stat", "(", "origin_stat", ",", "new_stat", ")", ":", "for", "key", "in", "new_stat", ":", "if", "key", "not", "in", "origin_stat", ":", "origin_stat", "[", "key", "]", "=", "new_stat", "[", "key", "]", "elif", "key", "==", "\"start_at\...
31.625
16.3125
def stats(): ''' Returns statistics about the locate database CLI Example: .. code-block:: bash salt '*' locate.stats ''' ret = {} cmd = 'locate -S' out = __salt__['cmd.run'](cmd).splitlines() for line in out: comps = line.strip().split() if line.startswith...
[ "def", "stats", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'locate -S'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "for", "line", "in", "out", ":", "comps", "=", "line", ".", "strip", "(",...
22.5
20.8
def all(self, cache=False): """ can use cache to return objects """ if cache: return [get_object(self.modelb, obj_id, cache=True, use_local=True) for obj_id in self.keys(True)] else: return self
[ "def", "all", "(", "self", ",", "cache", "=", "False", ")", ":", "if", "cache", ":", "return", "[", "get_object", "(", "self", ".", "modelb", ",", "obj_id", ",", "cache", "=", "True", ",", "use_local", "=", "True", ")", "for", "obj_id", "in", "self...
31.375
18.875
def fill_altgoids(go2obj): """Given a go2obj containing key GO IDs, fill with all alternate GO IDs.""" alt2obj = {altgo:goobj for goobj in go2obj.values() for altgo in goobj.alt_ids} for goid, goobj in alt2obj.items(): go2obj[goid] = goobj
[ "def", "fill_altgoids", "(", "go2obj", ")", ":", "alt2obj", "=", "{", "altgo", ":", "goobj", "for", "goobj", "in", "go2obj", ".", "values", "(", ")", "for", "altgo", "in", "goobj", ".", "alt_ids", "}", "for", "goid", ",", "goobj", "in", "alt2obj", "....
51
14
def get_version(version=None): """Returns a PEP 386-compliant version number from VERSION. :param version: A tuple that represent a version. :type version: tuple :returns: a PEP 386-compliant version number. :rtype: str """ if version is None: version_list = inasafe_version.split(...
[ "def", "get_version", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version_list", "=", "inasafe_version", ".", "split", "(", "'.'", ")", "version", "=", "tuple", "(", "version_list", "+", "[", "inasafe_release_status", "]", "...
32
18.625
def increment_times_modified(self): """ Increments the number of times this resource has been modified by all processes. """ rc = self.conn.client.incr(self.times_modified_key) self.conn.client.pexpire(self.times_modified_key, phonon.s_to_...
[ "def", "increment_times_modified", "(", "self", ")", ":", "rc", "=", "self", ".", "conn", ".", "client", ".", "incr", "(", "self", ".", "times_modified_key", ")", "self", ".", "conn", ".", "client", ".", "pexpire", "(", "self", ".", "times_modified_key", ...
40.125
14.125
def read(fname, merge_duplicate_shots=False, encoding='windows-1252'): """Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it""" return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse()
[ "def", "read", "(", "fname", ",", "merge_duplicate_shots", "=", "False", ",", "encoding", "=", "'windows-1252'", ")", ":", "return", "PocketTopoTxtParser", "(", "fname", ",", "merge_duplicate_shots", ",", "encoding", ")", ".", "parse", "(", ")" ]
81.333333
24
def firstVariant(): """first variant of Variants Read-only """ def fget(self): if self.variants: return self.variants[0] else: variant = Variant() return variant return locals()
[ "def", "firstVariant", "(", ")", ":", "def", "fget", "(", "self", ")", ":", "if", "self", ".", "variants", ":", "return", "self", ".", "variants", "[", "0", "]", "else", ":", "variant", "=", "Variant", "(", ")", "return", "variant", "return", "locals...
22.076923
15.384615
def migrate(connection, dsn): """ Collects all migrations and applies missed. Args: connection (sqlalchemy connection): """ all_migrations = _get_all_migrations() logger.debug('Collected migrations: {}'.format(all_migrations)) for version, modname in all_migrations: if _is_mis...
[ "def", "migrate", "(", "connection", ",", "dsn", ")", ":", "all_migrations", "=", "_get_all_migrations", "(", ")", "logger", ".", "debug", "(", "'Collected migrations: {}'", ".", "format", "(", "all_migrations", ")", ")", "for", "version", ",", "modname", "in"...
38.423077
21.653846
def get(self, sid): """ Constructs a DeploymentContext :param sid: The sid :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext """ return Deployme...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "DeploymentContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "environment_sid", "=", "self", ".", "_solution", "[", "'enviro...
32.8
21.733333
def is_default(self): """ ``True`` if the item's value is its default value or if no value and no default value are set. If the item is backed by an environment variable, this will be ``True`` only if the environment variable is set and is different to the default value of the i...
[ "def", "is_default", "(", "self", ")", ":", "envvar_value", "=", "self", ".", "_get_envvar_value", "(", ")", "if", "envvar_value", "is", "not", "not_set", ":", "return", "envvar_value", "==", "self", ".", "default", "else", ":", "return", "self", ".", "_va...
42.076923
20.846154
def render_view(view_name, **args): '''Process view and return root Node''' try: root_xml = get_view_root(view_name) return render(root_xml, **args) except CoreError as error: error.add_view_info(ViewInfo(view_name, None)) raise except: info = exc_info() e...
[ "def", "render_view", "(", "view_name", ",", "*", "*", "args", ")", ":", "try", ":", "root_xml", "=", "get_view_root", "(", "view_name", ")", "return", "render", "(", "root_xml", ",", "*", "*", "args", ")", "except", "CoreError", "as", "error", ":", "e...
35.307692
16.076923
def _logger_api(self): """Add API logging handler.""" from .tcex_logger import TcExLogHandler, TcExLogFormatter api = TcExLogHandler(self.session) api.set_name('api') api.setLevel(logging.DEBUG) api.setFormatter(TcExLogFormatter()) self.log.addHandler(api)
[ "def", "_logger_api", "(", "self", ")", ":", "from", ".", "tcex_logger", "import", "TcExLogHandler", ",", "TcExLogFormatter", "api", "=", "TcExLogHandler", "(", "self", ".", "session", ")", "api", ".", "set_name", "(", "'api'", ")", "api", ".", "setLevel", ...
33.888889
12.777778
def associate_notification_template(self, job_template, notification_template, status): """Associate a notification template from this job template. =====API DOCS===== Associate a notification template from this job template. :param job_template:...
[ "def", "associate_notification_template", "(", "self", ",", "job_template", ",", "notification_template", ",", "status", ")", ":", "return", "self", ".", "_assoc", "(", "'notification_templates_%s'", "%", "status", ",", "job_template", ",", "notification_template", ")...
45.45
24.7
def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2): ''' TT completion via Alternating Least Squares algorithm. Parameters: :dict: cooP dictionary with two records - 'indices': numpy.array of P x d shape, ...
[ "def", "ttSparseALS", "(", "cooP", ",", "shape", ",", "x0", "=", "None", ",", "ttRank", "=", "1", ",", "tol", "=", "1e-5", ",", "maxnsweeps", "=", "20", ",", "verbose", "=", "True", ",", "alpha", "=", "1e-2", ")", ":", "indices", "=", "cooP", "["...
37.873134
19.08209
def list_commands(self, page_size=None): """ Lists the commands visible to this client. Commands are returned in lexicographical order. :rtype: :class:`.Command` iterator """ params = {} if page_size is not None: params['limit'] = page_size ...
[ "def", "list_commands", "(", "self", ",", "page_size", "=", "None", ")", ":", "params", "=", "{", "}", "if", "page_size", "is", "not", "None", ":", "params", "[", "'limit'", "]", "=", "page_size", "return", "pagination", ".", "Iterator", "(", "client", ...
27.666667
15.47619
def _Open(self, path_spec, mode='rb'): """Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str])): file access mode. The default is 'rb' read-only binary. Raises: AccessError: if the access to open the file wa...
[ "def", "_Open", "(", "self", ",", "path_spec", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ".", "HasParent", "(", ")", ":", "raise", "errors", ".", "PathSpecError", "(", "'Unsupported path specification without parent.'", ")", "file_object", ...
32.566667
20.3
def set_uri(self, uri, size, checksum, readable=True, writable=False, storage_class=None): """Set a location of a file.""" self.uri = uri self.size = size self.checksum = checksum self.writable = writable self.readable = readable self.storage_class...
[ "def", "set_uri", "(", "self", ",", "uri", ",", "size", ",", "checksum", ",", "readable", "=", "True", ",", "writable", "=", "False", ",", "storage_class", "=", "None", ")", ":", "self", ".", "uri", "=", "uri", "self", ".", "size", "=", "size", "se...
36.230769
12.923077
def toggle_value(request, name): """ For manual shortcut links to perform toggle actions """ obj = service.system.namespace.get(name, None) if not obj or service.read_only: raise Http404 new_status = obj.status = not obj.status if service.redirect_from_setters: return HttpRes...
[ "def", "toggle_value", "(", "request", ",", "name", ")", ":", "obj", "=", "service", ".", "system", ".", "namespace", ".", "get", "(", "name", ",", "None", ")", "if", "not", "obj", "or", "service", ".", "read_only", ":", "raise", "Http404", "new_status...
35.916667
12.25
def siret_validator(): """Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.""" def _validate_siret(form, field, siret=""): """SIRET validator. A WTForm validator wants a form and a field as parameters. We also want to give directly a s...
[ "def", "siret_validator", "(", ")", ":", "def", "_validate_siret", "(", "form", ",", "field", ",", "siret", "=", "\"\"", ")", ":", "\"\"\"SIRET validator.\n\n A WTForm validator wants a form and a field as parameters. We\n also want to give directly a siret, for a scr...
35
18.666667
def create_archiver(typename): """Returns Archivers in common configurations. :API: public The typename must correspond to one of the following: 'tar' Returns a tar archiver that applies no compression and emits .tar files. 'tgz' Returns a tar archiver that applies gzip compression and emits .tar.gz fil...
[ "def", "create_archiver", "(", "typename", ")", ":", "archiver", "=", "_ARCHIVER_BY_TYPE", ".", "get", "(", "typename", ")", "if", "not", "archiver", ":", "raise", "ValueError", "(", "'No archiver registered for {!r}'", ".", "format", "(", "typename", ")", ")", ...
50.5
27.95
def get_abbr_impl(): """Return abbreviated implementation name.""" impl = platform.python_implementation() if impl == 'PyPy': return 'pp' elif impl == 'Jython': return 'jy' elif impl == 'IronPython': return 'ip' elif impl == 'CPython': return 'cp' raise Looku...
[ "def", "get_abbr_impl", "(", ")", ":", "impl", "=", "platform", ".", "python_implementation", "(", ")", "if", "impl", "==", "'PyPy'", ":", "return", "'pp'", "elif", "impl", "==", "'Jython'", ":", "return", "'jy'", "elif", "impl", "==", "'IronPython'", ":",...
27.384615
17.307692
def _print_refs(self, refs, total, prefix=' ', level=1, minsize=0, minpct=0.1): """ Print individual referents recursively. """ lrefs = list(refs) lrefs.sort(key=lambda x: x.size) lrefs.reverse() for ref in lrefs: if ref.size > m...
[ "def", "_print_refs", "(", "self", ",", "refs", ",", "total", ",", "prefix", "=", "' '", ",", "level", "=", "1", ",", "minsize", "=", "0", ",", "minpct", "=", "0.1", ")", ":", "lrefs", "=", "list", "(", "refs", ")", "lrefs", ".", "sort", "(", ...
39.333333
12.555556
def graph(self, ASres=None, padding=0, vspread=0.75, title="Multi-Traceroute Probe (MTR)", timestamp="", rtt=1, **kargs): """x.graph(ASres=conf.AS_resolver, other args): ASres = None : Use AS default resolver => 'conf.AS_resolver' ASres = AS_resolver() : default whois AS resolver (riswh...
[ "def", "graph", "(", "self", ",", "ASres", "=", "None", ",", "padding", "=", "0", ",", "vspread", "=", "0.75", ",", "title", "=", "\"Multi-Traceroute Probe (MTR)\"", ",", "timestamp", "=", "\"\"", ",", "rtt", "=", "1", ",", "*", "*", "kargs", ")", ":...
60.869565
24.173913
def read_pure_water_scattering_from_file(self, file_name): """Read the pure water scattering from a csv formatted file :param file_name: filename and path of the csv file """ lg.info('Reading water scattering from file') try: self.b_water = self._read_iop_from_file(f...
[ "def", "read_pure_water_scattering_from_file", "(", "self", ",", "file_name", ")", ":", "lg", ".", "info", "(", "'Reading water scattering from file'", ")", "try", ":", "self", ".", "b_water", "=", "self", ".", "_read_iop_from_file", "(", "file_name", ")", "except...
40.1
18.9
def bootstrap_jar_classfiles(self): """Returns a set of classfiles from the JVM bootstrap jars.""" bootstrap_jar_classfiles = set() for jar_file in self._find_all_bootstrap_jars(): for cls in self._jar_classfiles(jar_file): bootstrap_jar_classfiles.add(cls) return bootstrap_jar_classfiles
[ "def", "bootstrap_jar_classfiles", "(", "self", ")", ":", "bootstrap_jar_classfiles", "=", "set", "(", ")", "for", "jar_file", "in", "self", ".", "_find_all_bootstrap_jars", "(", ")", ":", "for", "cls", "in", "self", ".", "_jar_classfiles", "(", "jar_file", ")...
44.714286
5
def parse(self, argv=None): """ Parse argv of terminal :param argv: default is sys.argv """ if not argv: argv = sys.argv elif isinstance(argv, str): argv = argv.split() self._argv = argv[1:] if not self._argv: self.va...
[ "def", "parse", "(", "self", ",", "argv", "=", "None", ")", ":", "if", "not", "argv", ":", "argv", "=", "sys", ".", "argv", "elif", "isinstance", "(", "argv", ",", "str", ")", ":", "argv", "=", "argv", ".", "split", "(", ")", "self", ".", "_arg...
29.941176
16.019608
def _copy_old_features(new_eopatch, old_eopatch, copy_features): """ Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located ...
[ "def", "_copy_old_features", "(", "new_eopatch", ",", "old_eopatch", ",", "copy_features", ")", ":", "if", "copy_features", ":", "existing_features", "=", "set", "(", "new_eopatch", ".", "get_feature_list", "(", ")", ")", "for", "copy_feature_type", ",", "copy_fea...
52.5
32.178571
def delete(self, *, if_unused=True): """ Delete the exchange. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the exchange will only be deleted if it has no queues bound to it. """ self.sender.send_ExchangeDelete(self.name, i...
[ "def", "delete", "(", "self", ",", "*", ",", "if_unused", "=", "True", ")", ":", "self", ".", "sender", ".", "send_ExchangeDelete", "(", "self", ".", "name", ",", "if_unused", ")", "yield", "from", "self", ".", "synchroniser", ".", "wait", "(", "spec",...
34.25
17.25
def visitInlineShapeDefinition(self, ctx: ShExDocParser.InlineShapeDefinitionContext): """ shapeDefinition: qualifier* '{' oneOfShape? '}' """ if ctx.qualifier(): for q in ctx.qualifier(): self.visit(q) if ctx.oneOfShape(): oneof_parser = ShexOneOfShapePar...
[ "def", "visitInlineShapeDefinition", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "InlineShapeDefinitionContext", ")", ":", "if", "ctx", ".", "qualifier", "(", ")", ":", "for", "q", "in", "ctx", ".", "qualifier", "(", ")", ":", "self", ".", "visit",...
48.666667
14.777778
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) ...
[ "def", "trustworthiness", "(", "X", ",", "X_embedded", ",", "n_neighbors", "=", "5", ",", "precomputed", "=", "False", ")", ":", "if", "precomputed", ":", "dist_X", "=", "X", "else", ":", "dist_X", "=", "pairwise_distances", "(", "X", ",", "squared", "="...
35.75
23.133333
def start_market(self): """ start the market thread and register backtest broker thread QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承 """ # 启动 trade_engine 线程 self.market.start() # 注册 backtest_broker ,并且启动和它关联线程QAThread 存...
[ "def", "start_market", "(", "self", ")", ":", "# 启动 trade_engine 线程", "self", ".", "market", ".", "start", "(", ")", "# 注册 backtest_broker ,并且启动和它关联线程QAThread 存放在 kernels 词典中, { 'broker_name': QAThread }", "#self.market.register(self.broker_name, self.broker)", "self", ".", "mark...
41.818182
22
def _init(self, parser): """Initialize/Build the ``argparse.ArgumentParser`` and subparsers. This internal version of ``init`` is used to ensure that all subcommands have a properly initialized parser. Args ---- parser : argparse.ArgumentParser The parser fo...
[ "def", "_init", "(", "self", ",", "parser", ")", ":", "assert", "isinstance", "(", "parser", ",", "argparse", ".", "ArgumentParser", ")", "self", ".", "_init_parser", "(", "parser", ")", "self", ".", "_attach_arguments", "(", ")", "self", ".", "_attach_sub...
29.166667
17.944444
def get_product_url(self, force_http=False): """ Creates base url of product location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of product location :rtype: str """ base_url = sel...
[ "def", "get_product_url", "(", "self", ",", "force_http", "=", "False", ")", ":", "base_url", "=", "self", ".", "base_http_url", "if", "force_http", "else", "self", ".", "base_url", "return", "'{}products/{}/{}'", ".", "format", "(", "base_url", ",", "self", ...
41.363636
19.727273
def _init_content_type_params(self): """ Return the Content-Type request header parameters Convert all of the semi-colon separated parameters into a dict of key/vals. If for some stupid reason duplicate & conflicting params are present then the last one wins. If a parti...
[ "def", "_init_content_type_params", "(", "self", ")", ":", "ret", "=", "{", "}", "if", "self", ".", "content_type", ":", "params", "=", "self", ".", "content_type", ".", "split", "(", "';'", ")", "[", "1", ":", "]", "for", "param", "in", "params", ":...
29.689655
20.586207
def unlock(self): """Closes the session to the database.""" if not hasattr(self, 'session'): raise RuntimeError('Error detected! The session that you want to close does not exist any more!') logger.debug("Closed database session of '%s'" % self._database) self.session.close() del self.session
[ "def", "unlock", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'session'", ")", ":", "raise", "RuntimeError", "(", "'Error detected! The session that you want to close does not exist any more!'", ")", "logger", ".", "debug", "(", "\"Closed database...
44.714286
22
def filename(self): """ Returns readable filename for a transcript """ client_id, __ = os.path.splitext(self.video.client_video_id) file_name = u'{name}-{language}.{format}'.format( name=client_id, language=self.language_code, format=self.file_...
[ "def", "filename", "(", "self", ")", ":", "client_id", ",", "__", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "video", ".", "client_video_id", ")", "file_name", "=", "u'{name}-{language}.{format}'", ".", "format", "(", "name", "=", "client_i...
31.5
12.833333
async def factbook(self, root): """Region's World Factbook Entry. Returns ------- an :class:`ApiQuery` of str """ # This lib might have been a mistake, but the line below # definitely isn't. return html.unescape(html.unescape(root.find('FACTBOOK').text))
[ "async", "def", "factbook", "(", "self", ",", "root", ")", ":", "# This lib might have been a mistake, but the line below", "# definitely isn't.", "return", "html", ".", "unescape", "(", "html", ".", "unescape", "(", "root", ".", "find", "(", "'FACTBOOK'", ")", "....
31
17.2
def process(self, metric): """ Send a metric to Riemann. """ event = self._metric_to_riemann_event(metric) try: self.client.send_event(event) except Exception as e: self.log.error( "RiemannHandler: Error sending event to Riemann: %s...
[ "def", "process", "(", "self", ",", "metric", ")", ":", "event", "=", "self", ".", "_metric_to_riemann_event", "(", "metric", ")", "try", ":", "self", ".", "client", ".", "send_event", "(", "event", ")", "except", "Exception", "as", "e", ":", "self", "...
31.6
11.8
def close(self): """ Disconnect from the controller. """ logger.info("Closing connection to %s:%s", self._host, self._port) self._ioloop_future.cancel() try: yield from self._ioloop_future except asyncio.CancelledError: pass
[ "def", "close", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Closing connection to %s:%s\"", ",", "self", ".", "_host", ",", "self", ".", "_port", ")", "self", ".", "_ioloop_future", ".", "cancel", "(", ")", "try", ":", "yield", "from", "self", ...
29.5
11.9
def create_char(self, location, bitmap): """Create a new character. The HD44780 supports up to 8 custom characters (location 0-7). :param location: The place in memory where the character is stored. Values need to be integers between 0 and 7. :type location: int :pa...
[ "def", "create_char", "(", "self", ",", "location", ",", "bitmap", ")", ":", "assert", "0", "<=", "location", "<=", "7", ",", "'Only locations 0-7 are valid.'", "assert", "len", "(", "bitmap", ")", "==", "8", ",", "'Bitmap should have exactly 8 rows.'", "# Store...
31.090909
19.840909
def render_queries(queries, sort): """ Returns a StringIO containing the formatted SQL queries. _sort_ is a field to sort by. """ output = StringIO() if sort == 'order': print >>output, " time query" for query in queries: print >>output, " %8s %s" % (query["time"...
[ "def", "render_queries", "(", "queries", ",", "sort", ")", ":", "output", "=", "StringIO", "(", ")", "if", "sort", "==", "'order'", ":", "print", ">>", "output", ",", "\" time query\"", "for", "query", "in", "queries", ":", "print", ">>", "output", "...
31.428571
14.685714
def _minigui_report_search_status(self, leaves): """Prints the current MCTS search status to stderr. Reports the current search path, root node's child_Q, root node's child_N, the most visited path in a format that can be parsed by one of the STDERR_HANDLERS in minigui.ts. Args...
[ "def", "_minigui_report_search_status", "(", "self", ",", "leaves", ")", ":", "root", "=", "self", ".", "_player", ".", "get_root", "(", ")", "msg", "=", "{", "\"id\"", ":", "hex", "(", "id", "(", "root", ")", ")", ",", "\"n\"", ":", "int", "(", "r...
33.163636
18.709091
def raise_on_invalid_zip(func: Callable) -> Callable: """Raise an exception when there's no data (via a bad ZIP code).""" async def decorator(*args: list, **kwargs: dict) -> dict: """Decorate.""" data = await func(*args, **kwargs) if not data['Location']['periods']: raise Inv...
[ "def", "raise_on_invalid_zip", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "async", "def", "decorator", "(", "*", "args", ":", "list", ",", "*", "*", "kwargs", ":", "dict", ")", "->", "dict", ":", "\"\"\"Decorate.\"\"\"", "data", "=", "awai...
39.8
14.6
def toggle_eventtype(self): """Check or uncheck all event types in event type scroll.""" check = self.check_all_eventtype.isChecked() for btn in self.idx_eventtype_list: btn.setChecked(check)
[ "def", "toggle_eventtype", "(", "self", ")", ":", "check", "=", "self", ".", "check_all_eventtype", ".", "isChecked", "(", ")", "for", "btn", "in", "self", ".", "idx_eventtype_list", ":", "btn", ".", "setChecked", "(", "check", ")" ]
38.666667
11.166667
def intersection(L1, L2): """Intersects two line segments Args: L1 ([float, float]): x and y coordinates L2 ([float, float]): x and y coordinates Returns: bool: if they intersect (float, float): x and y of intersection, if they do """ D = L1[0] * L2[1] - L1[1] * L2[0...
[ "def", "intersection", "(", "L1", ",", "L2", ")", ":", "D", "=", "L1", "[", "0", "]", "*", "L2", "[", "1", "]", "-", "L1", "[", "1", "]", "*", "L2", "[", "0", "]", "Dx", "=", "L1", "[", "2", "]", "*", "L2", "[", "1", "]", "-", "L1", ...
25.526316
16.157895
def numToDigits(num, places): """ Helper, for converting numbers to textual digits. """ s = str(num) if len(s) < places: return ("0" * (places - len(s))) + s elif len(s) > places: return s[len(s)-places: ] else: return s
[ "def", "numToDigits", "(", "num", ",", "places", ")", ":", "s", "=", "str", "(", "num", ")", "if", "len", "(", "s", ")", "<", "places", ":", "return", "(", "\"0\"", "*", "(", "places", "-", "len", "(", "s", ")", ")", ")", "+", "s", "elif", ...
23.818182
13.272727
def main(argv=None): """Routine to page text or determine window size via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size']) except getopt.error as msg: raise Usage(msg) # Print usage and return, regardless of presence...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", "[", "1", ":", "]", ",", "'dhs'", ",", "[", "'nod...
25.894737
22.131579
def map(cls, visitor, value, value_type): """The common visitor API used by all three visitor implementations. args: ``visitor=``\ *Visitor* Visitor options instance: contains the callbacks to use to implement the visiting, as well as traversal & filtering ...
[ "def", "map", "(", "cls", ",", "visitor", ",", "value", ",", "value_type", ")", ":", "unpacked", "=", "visitor", ".", "unpack", "(", "value", ",", "value_type", ",", "visitor", ")", "if", "unpacked", "==", "cls", ".", "StopVisiting", "or", "isinstance", ...
30.653061
18.469388
def check_codes(self, expected_codes, received_code, info): """ Checks if any of expected matches received. :param expected_codes: tuple of expected codes :type expected_codes: :py:class:`tuple` :param received_code: received code for matching :type received_code: :py:c...
[ "def", "check_codes", "(", "self", ",", "expected_codes", ",", "received_code", ",", "info", ")", ":", "if", "not", "any", "(", "map", "(", "received_code", ".", "matches", ",", "expected_codes", ")", ")", ":", "raise", "errors", ".", "StatusCodeError", "(...
37.444444
20.555556
def present( name, user=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Verifies that the specified host is known by the specified user On m...
[ "def", "present", "(", "name", ",", "user", "=", "None", ",", "fingerprint", "=", "None", ",", "key", "=", "None", ",", "port", "=", "None", ",", "enc", "=", "None", ",", "config", "=", "None", ",", "hash_known_hosts", "=", "True", ",", "timeout", ...
37.666667
24.183673
def filter(self, term_doc_matrix): ''' Parameters ---------- term_doc_matrix : TermDocMatrix Returns ------- TermDocMatrix pmi-filterd term doc matrix ''' df = term_doc_matrix.get_term_freq_df() if len(df) == 0: return term_doc_matrix low_pmi_bigrams = get_low_pmi_bigrams(self._threshold_coef...
[ "def", "filter", "(", "self", ",", "term_doc_matrix", ")", ":", "df", "=", "term_doc_matrix", ".", "get_term_freq_df", "(", ")", "if", "len", "(", "df", ")", "==", "0", ":", "return", "term_doc_matrix", "low_pmi_bigrams", "=", "get_low_pmi_bigrams", "(", "se...
29.619048
22.095238
def com_google_fonts_check_ttx_roundtrip(font): """Checking with fontTools.ttx""" from fontTools import ttx import sys ttFont = ttx.TTFont(font) failed = False class TTXLogger: msgs = [] def __init__(self): self.original_stderr = sys.stderr self.original_stdout = sys.stdout sys.s...
[ "def", "com_google_fonts_check_ttx_roundtrip", "(", "font", ")", ":", "from", "fontTools", "import", "ttx", "import", "sys", "ttFont", "=", "ttx", ".", "TTFont", "(", "font", ")", "failed", "=", "False", "class", "TTXLogger", ":", "msgs", "=", "[", "]", "d...
32.1
19.371429
def disco_loop(opc, version, queue, real_out, dup_lines=False, show_bytes=False): """Disassembles a queue of code objects. If we discover another code object which will be found in co_consts, we add the new code to the list. Note that the order of code discovery is in the order of first e...
[ "def", "disco_loop", "(", "opc", ",", "version", ",", "queue", ",", "real_out", ",", "dup_lines", "=", "False", ",", "show_bytes", "=", "False", ")", ":", "while", "len", "(", "queue", ")", ">", "0", ":", "co", "=", "queue", ".", "popleft", "(", ")...
39.16
19.32
def decaying(start, stop, decay): """Yield an infinite series of linearly decaying values.""" curr = float(start) while True: yield max(curr, stop) curr -= (decay)
[ "def", "decaying", "(", "start", ",", "stop", ",", "decay", ")", ":", "curr", "=", "float", "(", "start", ")", "while", "True", ":", "yield", "max", "(", "curr", ",", "stop", ")", "curr", "-=", "(", "decay", ")" ]
26.571429
16.714286
def _construct_result(left, result, index, name, dtype=None): """ If the raw op result has a non-None name (e.g. it is an Index object) and the name argument is None, then passing name to the constructor will not be enough; we still need to override the name attribute. """ out = left._constructo...
[ "def", "_construct_result", "(", "left", ",", "result", ",", "index", ",", "name", ",", "dtype", "=", "None", ")", ":", "out", "=", "left", ".", "_constructor", "(", "result", ",", "index", "=", "index", ",", "dtype", "=", "dtype", ")", "out", "=", ...
41.4
19
def plotdata(self, key, part='re', scale='log', steps=50): """Return a tuple of arrays x, y that can be fed to plt.plot, where x is the scale in GeV and y is the parameter of interest. Parameters: - key: dicionary key of the parameter to be plotted (e.g. a WCxf coefficient na...
[ "def", "plotdata", "(", "self", ",", "key", ",", "part", "=", "'re'", ",", "scale", "=", "'log'", ",", "steps", "=", "50", ")", ":", "if", "scale", "==", "'log'", ":", "x", "=", "np", ".", "logspace", "(", "log", "(", "self", ".", "scale_min", ...
39.428571
14.571429
def color_pipeline(raw, setup, bpp=12): """Order from: http://www.visionresearch.com/phantomzone/viewtopic.php?f=20&t=572#p3884 """ # 1. Offset the raw image by the amount in flare print("fFlare: ", setup.fFlare) # 2. White balance the raw picture using the white balance component of cmatrix ...
[ "def", "color_pipeline", "(", "raw", ",", "setup", ",", "bpp", "=", "12", ")", ":", "# 1. Offset the raw image by the amount in flare", "print", "(", "\"fFlare: \"", ",", "setup", ".", "fFlare", ")", "# 2. White balance the raw picture using the white balance component of c...
33.989474
23.368421
def _getarray(loci, tree): """ parse the loci file list and return presence/absence matrix ordered by the tips on the tree """ ## order tips tree.ladderize() ## get tip names snames = tree.get_leaf_names() ## make an empty matrix lxs = np.zeros((len(snames), len(loci)), dtype...
[ "def", "_getarray", "(", "loci", ",", "tree", ")", ":", "## order tips", "tree", ".", "ladderize", "(", ")", "## get tip names", "snames", "=", "tree", ".", "get_leaf_names", "(", ")", "## make an empty matrix", "lxs", "=", "np", ".", "zeros", "(", "(", "l...
23.47619
19.333333
def createResource(self): """ When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex} for my application. """ pp = ixmantissa.IPublicPage(self.application, None) if pp is not None: warn( "Use the sharing system to provide public page...
[ "def", "createResource", "(", "self", ")", ":", "pp", "=", "ixmantissa", ".", "IPublicPage", "(", "self", ".", "application", ",", "None", ")", "if", "pp", "is", "not", "None", ":", "warn", "(", "\"Use the sharing system to provide public pages, not IPublicPage\""...
37.230769
14.769231
def predict(self, X): """ Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. """ if X.ndim==1: X = X[None,:] ps = self.model.param_array.copy() means...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", "None", ",", ":", "]", "ps", "=", "self", ".", "model", ".", "param_array", ".", "copy", "(", ")", "means", "=", "[", "]", "stds"...
37.761905
17.095238
def create_search_index(): """ takes people names from blockchain and writes deduped names in a 'cache' """ # create people name cache counter = 0 people_names = [] twitter_handles = [] usernames = [] log.debug("-" * 5) log.debug("Creating search index") for user in namespace...
[ "def", "create_search_index", "(", ")", ":", "# create people name cache", "counter", "=", "0", "people_names", "=", "[", "]", "twitter_handles", "=", "[", "]", "usernames", "=", "[", "]", "log", ".", "debug", "(", "\"-\"", "*", "5", ")", "log", ".", "de...
26.237624
19.950495
def extract_args(cls, *args): """ Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud. """ model = None crudbuilder = None for arg in args: if issubclass(arg, models.Model): model ...
[ "def", "extract_args", "(", "cls", ",", "*", "args", ")", ":", "model", "=", "None", "crudbuilder", "=", "None", "for", "arg", "in", "args", ":", "if", "issubclass", "(", "arg", ",", "models", ".", "Model", ")", ":", "model", "=", "arg", "else", ":...
26.666667
15.733333
def print_warning(cls): """Print a missing progress bar warning if it was not printed. """ if not cls.warning: cls.warning = True print('Can\'t create progress bar:', str(TQDM_IMPORT_ERROR), file=sys.stderr)
[ "def", "print_warning", "(", "cls", ")", ":", "if", "not", "cls", ".", "warning", ":", "cls", ".", "warning", "=", "True", "print", "(", "'Can\\'t create progress bar:'", ",", "str", "(", "TQDM_IMPORT_ERROR", ")", ",", "file", "=", "sys", ".", "stderr", ...
38.142857
11.142857
def init(): ''' Return the list of svn remotes and their configuration information ''' bp_ = os.path.join(__opts__['cachedir'], 'svnfs') new_remote = False repos = [] per_remote_defaults = {} for param in PER_REMOTE_OVERRIDES: per_remote_defaults[param] = \ six.text_...
[ "def", "init", "(", ")", ":", "bp_", "=", "os", ".", "path", ".", "join", "(", "__opts__", "[", "'cachedir'", "]", ",", "'svnfs'", ")", "new_remote", "=", "False", "repos", "=", "[", "]", "per_remote_defaults", "=", "{", "}", "for", "param", "in", ...
36.512195
20.463415
def getProvIden(self, provstack): ''' Returns the iden corresponding to a provenance stack and stores if it hasn't seen it before ''' iden = _providen(provstack) misc, frames = provstack # Convert each frame back from (k, v) tuples to a dict dictframes = [(typ, {k...
[ "def", "getProvIden", "(", "self", ",", "provstack", ")", ":", "iden", "=", "_providen", "(", "provstack", ")", "misc", ",", "frames", "=", "provstack", "# Convert each frame back from (k, v) tuples to a dict", "dictframes", "=", "[", "(", "typ", ",", "{", "k", ...
40
23.142857
def compact(self): """Convert this instance to a compact version: the value will be the same at all times, but repeated measurements are discarded. """ previous_value = object() redundant = [] for time, value in self: if value == previous_value: ...
[ "def", "compact", "(", "self", ")", ":", "previous_value", "=", "object", "(", ")", "redundant", "=", "[", "]", "for", "time", ",", "value", "in", "self", ":", "if", "value", "==", "previous_value", ":", "redundant", ".", "append", "(", "time", ")", ...
32.769231
11.923077
def get_session_id(self): """ get a unique id (shortish string) to allow simple aggregation of log records from multiple sources. This id is used for the life of the running program to allow extraction from all logs. WARING - this can give duplicate sessions when 2 apps hit it ...
[ "def", "get_session_id", "(", "self", ")", ":", "max_session", "=", "'0'", "try", ":", "with", "open", "(", "self", ".", "log_folder", "+", "os", ".", "sep", "+", "'_sessions.txt'", ",", "'r'", ")", "as", "f", ":", "for", "_", "in", "f", ":", "txt"...
43
20.090909
def set_service_status(service, status): '''Update the status of a particular service in the database. ''' srv = db.ServiceStates() srv.type = service srv.status = status dbs = db.get_session() dbs.merge(srv) dbs.commit() dbs.close()
[ "def", "set_service_status", "(", "service", ",", "status", ")", ":", "srv", "=", "db", ".", "ServiceStates", "(", ")", "srv", ".", "type", "=", "service", "srv", ".", "status", "=", "status", "dbs", "=", "db", ".", "get_session", "(", ")", "dbs", "....
23.636364
20.909091
def child_set(self, child, **kwargs): """Set a child properties on the given child to key/value pairs.""" for name, value in kwargs.items(): name = name.replace('_', '-') self.child_set_property(child, name, value)
[ "def", "child_set", "(", "self", ",", "child", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "name", "=", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "self", ".", "child_set_...
41.666667
10.166667
def output_reduce_list(path_list, force=False): """Generates structure file with protons from a list of structure files.""" output_paths = [] for path in path_list: output_path = output_reduce(path, force=force) if output_path: output_paths.append(output_path) return output_p...
[ "def", "output_reduce_list", "(", "path_list", ",", "force", "=", "False", ")", ":", "output_paths", "=", "[", "]", "for", "path", "in", "path_list", ":", "output_path", "=", "output_reduce", "(", "path", ",", "force", "=", "force", ")", "if", "output_path...
39.625
11.5
def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. ...
[ "def", "render_done", "(", "self", ",", "form", ",", "*", "*", "kwargs", ")", ":", "final_form_list", "=", "[", "]", "# walk through the form list and try to validate the data again.", "for", "form_key", "in", "self", ".", "get_form_list", "(", ")", ":", "form_obj...
47.26087
17.869565
def json(self, url, method='get', params=None, data=None): """ 请求并返回json :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: di...
[ "def", "json", "(", "self", ",", "url", ",", "method", "=", "'get'", ",", "params", "=", "None", ",", "data", "=", "None", ")", ":", "r", "=", "self", ".", "req", "(", "url", ",", "method", ",", "params", ",", "data", ")", "return", "r", ".", ...
20.863636
18.772727
def formatTime(self, record, datefmt=None): """Format the log timestamp.""" _seconds_fraction = record.created - int(record.created) _datetime_utc = time.mktime(time.gmtime(record.created)) _datetime_utc += _seconds_fraction _created = self.converter(_datetime_utc) if da...
[ "def", "formatTime", "(", "self", ",", "record", ",", "datefmt", "=", "None", ")", ":", "_seconds_fraction", "=", "record", ".", "created", "-", "int", "(", "record", ".", "created", ")", "_datetime_utc", "=", "time", ".", "mktime", "(", "time", ".", "...
41.769231
17.538462
def isValidSemver(version): """Semantic version number - determines whether the version is qualified. The format is MAJOR.Minor.PATCH, more with https://semver.org/""" if version and isinstance(version, string_types): try: semver.parse(version) except (TypeError,ValueError): ...
[ "def", "isValidSemver", "(", "version", ")", ":", "if", "version", "and", "isinstance", "(", "version", ",", "string_types", ")", ":", "try", ":", "semver", ".", "parse", "(", "version", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "retu...
38.2
14.7
def validate_IPykernel(venv_dir): """Validates that this env contains an IPython kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir) """ python_exe_name = find_exe(venv_dir, "python") if python_exe_name is None: python_exe_name = find_exe(venv_dir, "py...
[ "def", "validate_IPykernel", "(", "venv_dir", ")", ":", "python_exe_name", "=", "find_exe", "(", "venv_dir", ",", "\"python\"", ")", "if", "python_exe_name", "is", "None", ":", "python_exe_name", "=", "find_exe", "(", "venv_dir", ",", "\"python2\"", ")", "if", ...
38.387097
18.806452
def daterange(start, stop, step=1, inclusive=False): """In the spirit of :func:`range` and :func:`xrange`, the `daterange` generator that yields a sequence of :class:`~datetime.date` objects, starting at *start*, incrementing by *step*, until *stop* is reached. When *inclusive* is True, the final d...
[ "def", "daterange", "(", "start", ",", "stop", ",", "step", "=", "1", ",", "inclusive", "=", "False", ")", ":", "if", "not", "isinstance", "(", "start", ",", "date", ")", ":", "raise", "TypeError", "(", "\"start expected datetime.date instance\"", ")", "if...
37.964706
18.647059