text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def list_cluster(datacenter=None, cluster=None, service_instance=None): ''' Returns a dict representation of an ESX cluster. datacenter Name of datacenter containing the cluster. Ignored if already contained by proxy details. Default value is None. cluster Name of clust...
[ "def", "list_cluster", "(", "datacenter", "=", "None", ",", "cluster", "=", "None", ",", "service_instance", "=", "None", ")", ":", "proxy_type", "=", "get_proxy_type", "(", ")", "if", "proxy_type", "==", "'esxdatacenter'", ":", "dc_ref", "=", "_get_proxy_targ...
33.268293
0.000712
def _load_ngram(name): """Dynamically import the python module with the ngram defined as a dictionary. Since bigger ngrams are large files its wasteful to always statically import them if they're not used. """ module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name)) return...
[ "def", "_load_ngram", "(", "name", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "'lantern.analysis.english_ngrams.{}'", ".", "format", "(", "name", ")", ")", "return", "getattr", "(", "module", ",", "name", ")" ]
56.166667
0.011696
def nearest(self, coordinates, num_results=1, objects=False): """Returns the ``k``-nearest objects to the given coordinates. :param coordinates: sequence or array This may be an object that satisfies the numpy array protocol, providing the index's dimension * 2 coordinate ...
[ "def", "nearest", "(", "self", ",", "coordinates", ",", "num_results", "=", "1", ",", "objects", "=", "False", ")", ":", "if", "objects", ":", "return", "self", ".", "_nearest_obj", "(", "coordinates", ",", "num_results", ",", "objects", ")", "p_mins", "...
45.755556
0.000951
def _mongodump_exec(mongodump, address, port, user, passwd, db, out_dir, auth_db, dry_run): """ Run mongodump on a database :param address: server host name or IP address :param port: server port :param user: user name :param passwd: password :param db: database name ...
[ "def", "_mongodump_exec", "(", "mongodump", ",", "address", ",", "port", ",", "user", ",", "passwd", ",", "db", ",", "out_dir", ",", "auth_db", ",", "dry_run", ")", ":", "# Log the call", "log", ".", "msg", "(", "\"mongodump [{mongodump}] db={db} auth_db={auth_d...
36.483871
0.001723
def baseclass(self): """The baseclass of self.""" for cls in _BASE_CLASSES: if isinstance(self, cls): return cls raise ValueError("Cannot determine the base class of %s" % self.__class__.__name__)
[ "def", "baseclass", "(", "self", ")", ":", "for", "cls", "in", "_BASE_CLASSES", ":", "if", "isinstance", "(", "self", ",", "cls", ")", ":", "return", "cls", "raise", "ValueError", "(", "\"Cannot determine the base class of %s\"", "%", "self", ".", "__class__",...
34.714286
0.012048
def extend_right_to(self, window, max_size): """Adjust the size to make our window end where the right window begins, but don't get larger than max_size""" self.size = min(self.size + (window.ofs - self.ofs_end()), max_size)
[ "def", "extend_right_to", "(", "self", ",", "window", ",", "max_size", ")", ":", "self", ".", "size", "=", "min", "(", "self", ".", "size", "+", "(", "window", ".", "ofs", "-", "self", ".", "ofs_end", "(", ")", ")", ",", "max_size", ")" ]
61.25
0.012097
def fd_solve(self): """ w = fd_solve() Sparse flexural response calculation. Can be performed by direct factorization with UMFpack (defuault) or by an iterative minimum residual technique These are both the fastest of the standard Scipy builtin techniques in their respective classes R...
[ "def", "fd_solve", "(", "self", ")", ":", "if", "self", ".", "Debug", ":", "try", ":", "# Will fail if scalar", "print", "(", "\"self.Te\"", ",", "self", ".", "Te", ".", "shape", ")", "except", ":", "pass", "print", "(", "\"self.qs\"", ",", "self", "."...
41.142857
0.018089
def get_auditpol_dump(): ''' Gets the contents of an auditpol /backup. Used by the LGPO module to get fieldnames and GUIDs for Advanced Audit policies. Returns: list: A list of lines form the backup file Usage: .. code-block:: python import salt.utils.win_lgpo_auditpol ...
[ "def", "get_auditpol_dump", "(", ")", ":", "# Just get a temporary file name", "# NamedTemporaryFile will delete the file it creates by default on Windows", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.csv'", ")", "as", "tmp_file", ":", "csv_file", "=...
27.923077
0.001332
def read_string_from_file(path, encoding="utf8"): """ Read entire contents of file into a string. """ with codecs.open(path, "rb", encoding=encoding) as f: value = f.read() return value
[ "def", "read_string_from_file", "(", "path", ",", "encoding", "=", "\"utf8\"", ")", ":", "with", "codecs", ".", "open", "(", "path", ",", "\"rb\"", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "value", "=", "f", ".", "read", "(", ")", "retu...
27.571429
0.020101
def dropbox_basename(url): """ Strip off the dl=0 suffix from dropbox links >>> dropbox_basename('https://www.dropbox.com/s/yviic64qv84x73j/aclImdb_v1.tar.gz?dl=1') 'aclImdb_v1.tar.gz' """ filename = os.path.basename(url) match = re.findall(r'\?dl=[0-9]$', filename) if match: re...
[ "def", "dropbox_basename", "(", "url", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "match", "=", "re", ".", "findall", "(", "r'\\?dl=[0-9]$'", ",", "filename", ")", "if", "match", ":", "return", "filename", "[", ":",...
32.727273
0.008108
def get_group_tree_root(self, page_size=1000): r"""Return the root group for this accounts' group tree This will return the root group for this tree but with all links between nodes (i.e. children starting from root) populated. Examples:: # print the group hierarchy to std...
[ "def", "get_group_tree_root", "(", "self", ",", "page_size", "=", "1000", ")", ":", "# first pass, build mapping", "group_map", "=", "{", "}", "# map id -> group", "page_size", "=", "validate_type", "(", "page_size", ",", "*", "six", ".", "integer_types", ")", "...
39.84
0.00147
def upload_all_books(book_id_start, book_id_end, rdf_library=None): """ Uses the fetch, make, push subcommands to mirror Project Gutenberg to a github3 api """ # TODO refactor appname into variable logger.info( "starting a gitberg mass upload: {0} -> {1}".format( book_id_sta...
[ "def", "upload_all_books", "(", "book_id_start", ",", "book_id_end", ",", "rdf_library", "=", "None", ")", ":", "# TODO refactor appname into variable", "logger", ".", "info", "(", "\"starting a gitberg mass upload: {0} -> {1}\"", ".", "format", "(", "book_id_start", ",",...
33.777778
0.001066
def bitmap2RRlist(bitmap): """ Decode the 'Type Bit Maps' field of the NSEC Resource Record into an integer list. """ # RFC 4034, 4.1.2. The Type Bit Maps Field RRlist = [] while bitmap: if len(bitmap) < 2: warning("bitmap too short (%i)" % len(bitmap)) re...
[ "def", "bitmap2RRlist", "(", "bitmap", ")", ":", "# RFC 4034, 4.1.2. The Type Bit Maps Field", "RRlist", "=", "[", "]", "while", "bitmap", ":", "if", "len", "(", "bitmap", ")", "<", "2", ":", "warning", "(", "\"bitmap too short (%i)\"", "%", "len", "(", "bitma...
30.902439
0.011477
def _mark_context_complete(marker, context, has_errors): """Transactionally 'complete' the context.""" current = None if marker: current = marker.key.get() if not current: return False if current and current.complete: return False current.complete = True current....
[ "def", "_mark_context_complete", "(", "marker", ",", "context", ",", "has_errors", ")", ":", "current", "=", "None", "if", "marker", ":", "current", "=", "marker", ".", "key", ".", "get", "(", ")", "if", "not", "current", ":", "return", "False", "if", ...
19.636364
0.002208
def add_optional_arg_param(self, param_name, layer_index, blob_index): """Add an arg param. If there is no such param in .caffemodel fie, silently ignore it.""" blobs = self.layers[layer_index].blobs if blob_index < len(blobs): self.add_arg_param(param_name, layer_index, blob_index)
[ "def", "add_optional_arg_param", "(", "self", ",", "param_name", ",", "layer_index", ",", "blob_index", ")", ":", "blobs", "=", "self", ".", "layers", "[", "layer_index", "]", ".", "blobs", "if", "blob_index", "<", "len", "(", "blobs", ")", ":", "self", ...
63
0.009404
def _require_authenticate(func): '''A decorator to add digest authorization checks to HTTP Request Handlers''' def wrapped(self): if not hasattr(self, 'authenticated'): self.authenticated = None if self.authenticated: return func(self) auth = self.headers.get(u'...
[ "def", "_require_authenticate", "(", "func", ")", ":", "def", "wrapped", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'authenticated'", ")", ":", "self", ".", "authenticated", "=", "None", "if", "self", ".", "authenticated", ":", "re...
36.355932
0.001362
def exons(self): """ return a list of exons [(start, stop)] for this object if appropriate """ # drop the trailing comma if not self.is_gene_pred: return [] if hasattr(self, "exonStarts"): try: starts = (long(s) for s in self.exonStarts[:-1].sp...
[ "def", "exons", "(", "self", ")", ":", "# drop the trailing comma", "if", "not", "self", ".", "is_gene_pred", ":", "return", "[", "]", "if", "hasattr", "(", "self", ",", "\"exonStarts\"", ")", ":", "try", ":", "starts", "=", "(", "long", "(", "s", ")",...
42.666667
0.010917
def deleteAllNetworkViews(self, networkId, verbose=None): """ Deletes all Network Views available in the Network specified by the `networkId` parameter. Cytoscape can have multiple views per network model, but this feature is not exposed in the Cytoscape GUI. GUI access is limited to the first available...
[ "def", "deleteAllNetworkViews", "(", "self", ",", "networkId", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'networks/'", "+", "str", "(", "networkId", ")", "+", "'/views'", ",", "method", ...
49.666667
0.008237
def _check_sig_dims(sig, read_len, n_sig, samps_per_frame): """ Integrity check of a signal's shape after reading. """ if isinstance(sig, np.ndarray): if sig.shape != (read_len, n_sig): raise ValueError('Samples were not loaded correctly') else: if len(sig) != n_sig: ...
[ "def", "_check_sig_dims", "(", "sig", ",", "read_len", ",", "n_sig", ",", "samps_per_frame", ")", ":", "if", "isinstance", "(", "sig", ",", "np", ".", "ndarray", ")", ":", "if", "sig", ".", "shape", "!=", "(", "read_len", ",", "n_sig", ")", ":", "rai...
38.142857
0.001828
def parse_tstamp(ev, field_name): """Parse a timestamp string in format "YYYY-MM-DD HH:MM" :returns: datetime """ try: return datetime.strptime(ev[field_name], '%Y-%m-%d %H:%M') except Exception as e: log.error("Unable to parse the '%s' field in the event named '%s': %s" \ ...
[ "def", "parse_tstamp", "(", "ev", ",", "field_name", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "ev", "[", "field_name", "]", ",", "'%Y-%m-%d %H:%M'", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "\"Unable ...
32.545455
0.01087
def community_topic_subscription_show(self, topic_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#show-topic-subscription" api_path = "/api/v2/community/topics/{topic_id}/subscriptions/{id}.json" api_path = api_path.format(topic_id=topic_id, id=id) ...
[ "def", "community_topic_subscription_show", "(", "self", ",", "topic_id", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/community/topics/{topic_id}/subscriptions/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "topic_id", "="...
71
0.011142
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False): """Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommen...
[ "def", "select_autoescape", "(", "enabled_extensions", "=", "(", "'html'", ",", "'htm'", ",", "'xml'", ")", ",", "disabled_extensions", "=", "(", ")", ",", "default_for_string", "=", "True", ",", "default", "=", "False", ")", ":", "enabled_patterns", "=", "t...
40.788462
0.000921
def add(obj): ''' Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added ''' Form = badge_form(obj.__class__) form = api.validate(Form) kind = form.kind.data badge = obj...
[ "def", "add", "(", "obj", ")", ":", "Form", "=", "badge_form", "(", "obj", ".", "__class__", ")", "form", "=", "api", ".", "validate", "(", "Form", ")", "kind", "=", "form", ".", "kind", ".", "data", "badge", "=", "obj", ".", "get_badge", "(", "k...
23.823529
0.002375
def lambda_handler(event, context=None, settings_name="zappa_settings"): # NoQA """ An AWS Lambda function which parses specific API Gateway input into a WSGI request. The request get fed it to Django, processes the Django response, and returns that back to the API Gateway. """ time_start = da...
[ "def", "lambda_handler", "(", "event", ",", "context", "=", "None", ",", "settings_name", "=", "\"zappa_settings\"", ")", ":", "# NoQA", "time_start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "# If in DEBUG mode, log all raw incoming events.", "if", ...
38.953488
0.001456
def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None): """ Find item with port closest to specified position. List of items to be ignored can be specified with `exclude` parameter. Tuple is returned - found item - closest, connecta...
[ "def", "get_port_at_point", "(", "self", ",", "vpos", ",", "distance", "=", "10", ",", "exclude", "=", "None", ",", "exclude_port_fun", "=", "None", ")", ":", "# Method had to be inherited, as the base method has a bug:", "# It misses the statement max_dist = d", "v2i", ...
30.157895
0.00169
def bowtie2_alignment_plot (self): """ Make the HighCharts HTML to plot the alignment rates """ half_warning = '' for s_name in self.bowtie2_data: if 'paired_aligned_mate_one_halved' in self.bowtie2_data[s_name] or 'paired_aligned_mate_multi_halved' in self.bowtie2_data[s_name] or '...
[ "def", "bowtie2_alignment_plot", "(", "self", ")", ":", "half_warning", "=", "''", "for", "s_name", "in", "self", ".", "bowtie2_data", ":", "if", "'paired_aligned_mate_one_halved'", "in", "self", ".", "bowtie2_data", "[", "s_name", "]", "or", "'paired_aligned_mate...
59.844828
0.015306
def which(program, add_win_suffixes=True): """Mimic 'which' command behavior. Adapted from https://stackoverflow.com/a/377028 """ def is_exe(fpath): """Determine if program exists and is executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.pat...
[ "def", "which", "(", "program", ",", "add_win_suffixes", "=", "True", ")", ":", "def", "is_exe", "(", "fpath", ")", ":", "\"\"\"Determine if program exists and is executable.\"\"\"", "return", "os", ".", "path", ".", "isfile", "(", "fpath", ")", "and", "os", "...
32.142857
0.001079
def find_binary(self, binary): """ Scan and return the first path to a binary that we can find """ if os.path.exists(binary): return binary # Extract out the filename if we were given a full path binary_name = os.path.basename(binary) # Gather $PATH ...
[ "def", "find_binary", "(", "self", ",", "binary", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "binary", ")", ":", "return", "binary", "# Extract out the filename if we were given a full path", "binary_name", "=", "os", ".", "path", ".", "basename", ...
26.794118
0.002119
def user_absent(name, profile=None, **connection_args): ''' Ensure that the keystone user is absent. name The name of the user that should not exist ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'User "{0}" is already absent'.format(name...
[ "def", "user_absent", "(", "name", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'User \"{0}\" is ...
34.407407
0.001047
def get_next_action(self, request, application, label, roles): """ Django view method. """ actions = self.get_actions(request, application, roles) if label is None and \ 'is_applicant' in roles and 'is_admin' not in roles: # applicant, admin, leader can reopen an appl...
[ "def", "get_next_action", "(", "self", ",", "request", ",", "application", ",", "label", ",", "roles", ")", ":", "actions", "=", "self", ".", "get_actions", "(", "request", ",", "application", ",", "roles", ")", "if", "label", "is", "None", "and", "'is_a...
43.421053
0.002372
def pre_save(cls, sender, instance, *args, **kwargs): """Pull constant_contact_id out of data. """ instance.constant_contact_id = str(instance.data['id'])
[ "def", "pre_save", "(", "cls", ",", "sender", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "instance", ".", "constant_contact_id", "=", "str", "(", "instance", ".", "data", "[", "'id'", "]", ")" ]
43.75
0.011236
def parse_prototype(prototype): '''Returns a :attr:`FunctionSpec` instance from the input. ''' val = ' '.join(prototype.splitlines()) f = match(func_pat, val) # match the whole function if f is None: raise Exception('Cannot parse function prototype "{}"'.format(val)) ftp, pointer...
[ "def", "parse_prototype", "(", "prototype", ")", ":", "val", "=", "' '", ".", "join", "(", "prototype", ".", "splitlines", "(", ")", ")", "f", "=", "match", "(", "func_pat", ",", "val", ")", "# match the whole function\r", "if", "f", "is", "None", ":", ...
43.25
0.002262
def visitNodeConstraintNonLiteral(self, ctx: ShExDocParser.NodeConstraintNonLiteralContext): """ nodeConstraint: nonLiteralKind stringFacet* # nodeConstraintNonLiteral """ self.nodeconstraint.nodeKind = 'iri' if ctx.nonLiteralKind().KW_IRI() \ else 'bnode' if ctx.nonLiteralKind().KW_BNODE()...
[ "def", "visitNodeConstraintNonLiteral", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "NodeConstraintNonLiteralContext", ")", ":", "self", ".", "nodeconstraint", ".", "nodeKind", "=", "'iri'", "if", "ctx", ".", "nonLiteralKind", "(", ")", ".", "KW_IRI", "(...
64.142857
0.008791
def from_path(cls, path, suffix=""): """ Convenient constructor that takes in the path name of VASP run to perform Bader analysis. Args: path (str): Name of directory where VASP output files are stored. suffix (str): specific suffix to look for (e...
[ "def", "from_path", "(", "cls", ",", "path", ",", "suffix", "=", "\"\"", ")", ":", "def", "_get_filepath", "(", "filename", ")", ":", "name_pattern", "=", "filename", "+", "suffix", "+", "'*'", "if", "filename", "!=", "'POTCAR'", "else", "filename", "+",...
43.320755
0.000852
def PythonPercentFormat(format_str): """Use Python % format strings as template format specifiers.""" if format_str.startswith('printf '): fmt = format_str[len('printf '):] return lambda value: fmt % value else: return None
[ "def", "PythonPercentFormat", "(", "format_str", ")", ":", "if", "format_str", ".", "startswith", "(", "'printf '", ")", ":", "fmt", "=", "format_str", "[", "len", "(", "'printf '", ")", ":", "]", "return", "lambda", "value", ":", "fmt", "%", "value", "e...
29.375
0.016529
def remove_empty_segments(times, labels): """Removes empty segments if needed.""" assert len(times) - 1 == len(labels) inters = times_to_intervals(times) new_inters = [] new_labels = [] for inter, label in zip(inters, labels): if inter[0] < inter[1]: new_inters.append(inter) ...
[ "def", "remove_empty_segments", "(", "times", ",", "labels", ")", ":", "assert", "len", "(", "times", ")", "-", "1", "==", "len", "(", "labels", ")", "inters", "=", "times_to_intervals", "(", "times", ")", "new_inters", "=", "[", "]", "new_labels", "=", ...
37.454545
0.00237
def transfer(ctx, to, amount, asset, memo, account): """ Transfer assets """ pprint(ctx.peerplays.transfer(to, amount, asset, memo=memo, account=account))
[ "def", "transfer", "(", "ctx", ",", "to", ",", "amount", ",", "asset", ",", "memo", ",", "account", ")", ":", "pprint", "(", "ctx", ".", "peerplays", ".", "transfer", "(", "to", ",", "amount", ",", "asset", ",", "memo", "=", "memo", ",", "account",...
40.75
0.012048
def mark_for_update(self): ''' Note that a change has been made so all Statuses need update ''' self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE) push_key.delay(self)
[ "def", "mark_for_update", "(", "self", ")", ":", "self", ".", "pub_statuses", ".", "exclude", "(", "status", "=", "UNPUBLISHED", ")", ".", "update", "(", "status", "=", "NEEDS_UPDATE", ")", "push_key", ".", "delay", "(", "self", ")" ]
38.166667
0.012821
def createCellsList (self): ''' Create population cells based on list of individual cells''' from .. import sim cells = [] self.tags['numCells'] = len(self.tags['cellsList']) for i in self._distributeCells(len(self.tags['cellsList']))[sim.rank]: #if 'cellMode...
[ "def", "createCellsList", "(", "self", ")", ":", "from", ".", ".", "import", "sim", "cells", "=", "[", "]", "self", ".", "tags", "[", "'numCells'", "]", "=", "len", "(", "self", ".", "tags", "[", "'cellsList'", "]", ")", "for", "i", "in", "self", ...
74.074074
0.009872
def _run_check(self): """Execute a check command. Returns: True if the exit code of the command is 0 otherwise False. """ cmd = shlex.split(self.config['check_cmd']) self.log.info("running %s", ' '.join(cmd)) proc = subprocess.Popen(cmd, stdout=subprocess.PI...
[ "def", "_run_check", "(", "self", ")", ":", "cmd", "=", "shlex", ".", "split", "(", "self", ".", "config", "[", "'check_cmd'", "]", ")", "self", ".", "log", ".", "info", "(", "\"running %s\"", ",", "' '", ".", "join", "(", "cmd", ")", ")", "proc", ...
36.138889
0.001497
def _check_file(parameters): """Return list of errors.""" (filename, args) = parameters if filename == '-': contents = sys.stdin.read() else: with contextlib.closing( docutils.io.FileInput(source_path=filename) ) as input_file: contents = input_file.read(...
[ "def", "_check_file", "(", "parameters", ")", ":", "(", "filename", ",", "args", ")", "=", "parameters", "if", "filename", "==", "'-'", ":", "contents", "=", "sys", ".", "stdin", ".", "read", "(", ")", "else", ":", "with", "contextlib", ".", "closing",...
30.9375
0.000979
def get_fields(self): """ Calculate fields that can be accessed by authenticated user. """ ret = OrderedDict() # no rights to see anything if not self.user: return ret # all fields that can be accessed through serializer fields = super(ModelPermissionsSerial...
[ "def", "get_fields", "(", "self", ")", ":", "ret", "=", "OrderedDict", "(", ")", "# no rights to see anything", "if", "not", "self", ".", "user", ":", "return", "ret", "# all fields that can be accessed through serializer", "fields", "=", "super", "(", "ModelPermiss...
39.114286
0.001426
def wait(self, **kwargs): """Wait until any pending asynchronous requests are finished for this collection.""" if self.request: self.request.wait(**kwargs) self.request = None return self.inflate()
[ "def", "wait", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "request", ":", "self", ".", "request", ".", "wait", "(", "*", "*", "kwargs", ")", "self", ".", "request", "=", "None", "return", "self", ".", "inflate", "(", ")" ]
40
0.012245
def connect(self): """Initialize the database connection.""" self._client = self._create_client() self._db = getattr(self._client, self._db_name) self._generic_dao = GenericDAO(self._client, self._db_name)
[ "def", "connect", "(", "self", ")", ":", "self", ".", "_client", "=", "self", ".", "_create_client", "(", ")", "self", ".", "_db", "=", "getattr", "(", "self", ".", "_client", ",", "self", ".", "_db_name", ")", "self", ".", "_generic_dao", "=", "Gene...
46.6
0.008439
def nvp2pl(normal, point): """ Make a plane from a normal vector and a point. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvp2pl_c.html :param normal: A normal vector defining a plane. :type normal: 3-Element Array of floats :param point: A point defining a plane. :type point: ...
[ "def", "nvp2pl", "(", "normal", ",", "point", ")", ":", "normal", "=", "stypes", ".", "toDoubleVector", "(", "normal", ")", "point", "=", "stypes", ".", "toDoubleVector", "(", "point", ")", "plane", "=", "stypes", ".", "Plane", "(", ")", "libspice", "....
32.666667
0.001653
def ephemerals_info(self, hosts): """Returns ClientInfo per path. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of (path, ClientInfo). """ info_by_path, info_by_id = {}, {} for server_endpoint, dump in self.dump_by_server(hos...
[ "def", "ephemerals_info", "(", "self", ",", "hosts", ")", ":", "info_by_path", ",", "info_by_id", "=", "{", "}", ",", "{", "}", "for", "server_endpoint", ",", "dump", "in", "self", ".", "dump_by_server", "(", "hosts", ")", ".", "items", "(", ")", ":", ...
34.852941
0.001642
def _format_line(self): 'Joins the widgets and justifies the line' widgets = ''.join(self._format_widgets()) if self.left_justify: return widgets.ljust(self.term_width) else: return widgets.rjust(self.term_width)
[ "def", "_format_line", "(", "self", ")", ":", "widgets", "=", "''", ".", "join", "(", "self", ".", "_format_widgets", "(", ")", ")", "if", "self", ".", "left_justify", ":", "return", "widgets", ".", "ljust", "(", "self", ".", "term_width", ")", "else",...
34.285714
0.01626
def load_data(self, cls_vec): """pre-processed the data frame.new filtering methods will be implement here. """ # read data in if isinstance(self.data, pd.DataFrame) : exprs = self.data.copy() # handle index is gene_names if exprs.index.dtype == 'O': ...
[ "def", "load_data", "(", "self", ",", "cls_vec", ")", ":", "# read data in", "if", "isinstance", "(", "self", ".", "data", ",", "pd", ".", "DataFrame", ")", ":", "exprs", "=", "self", ".", "data", ".", "copy", "(", ")", "# handle index is gene_names", "i...
46.342857
0.012077
def on_btn_orientation(self, event): """ Create and fill wxPython grid for entering orientation data. """ wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() #dw, dh = wx.DisplaySize() size = wx.DisplaySize() size = (size[0...
[ "def", "on_btn_orientation", "(", "self", ",", "event", ")", ":", "wait", "=", "wx", ".", "BusyInfo", "(", "'Compiling required data, please wait...'", ")", "wx", ".", "SafeYield", "(", ")", "#dw, dh = wx.DisplaySize()", "size", "=", "wx", ".", "DisplaySize", "(...
41.619048
0.011186
def stop(self): """Send a TX_DELETE message to cancel this task. This will delete the entry for the transmission of the CAN-message with the specified can_id CAN identifier. The message length for the command TX_DELETE is {[bcm_msg_head]} (only the header). """ log.debug...
[ "def", "stop", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Stopping periodic task\"", ")", "stopframe", "=", "build_bcm_tx_delete_header", "(", "self", ".", "can_id_with_flags", ",", "self", ".", "flags", ")", "send_bcm", "(", "self", ".", "bcm_socket"...
42.272727
0.008421
def tag_map(self): ''' Build a map from tagtype to list of tags ''' tm = dd(list) for tag in self.__tags: tm[tag.tagtype].append(tag) return tm
[ "def", "tag_map", "(", "self", ")", ":", "tm", "=", "dd", "(", "list", ")", "for", "tag", "in", "self", ".", "__tags", ":", "tm", "[", "tag", ".", "tagtype", "]", ".", "append", "(", "tag", ")", "return", "tm" ]
30.333333
0.010695
def get_dvportgroups(parent_ref, portgroup_names=None, get_all_portgroups=False): ''' Returns distributed virtual porgroups (dvportgroups). The parent object can be either a datacenter or a dvs. parent_ref The parent object reference. Can be either a datacenter or a dvs. ...
[ "def", "get_dvportgroups", "(", "parent_ref", ",", "portgroup_names", "=", "None", ",", "get_all_portgroups", "=", "False", ")", ":", "if", "not", "(", "isinstance", "(", "parent_ref", ",", "(", "vim", ".", "Datacenter", ",", "vim", ".", "DistributedVirtualSwi...
41.792453
0.000441
def range_decompress(cl): ''' #only support sorted-ints or sorted-ascii cl = [1, (5, 8), (13, 14), 18, (30, 34)] range_decompress(cl) cl = [1, (5, 8), (13, 14), 18, (30, 34), 40] range_decompress(cl) cl = [('a', 'd'), ('j', 'n'), 'u', ('y', 'z')] range_decompr...
[ "def", "range_decompress", "(", "cl", ")", ":", "def", "cond_func", "(", "ele", ")", ":", "length", "=", "ele", ".", "__len__", "(", ")", "cond", "=", "(", "length", "==", "1", ")", "if", "(", "cond", ")", ":", "return", "(", "ord", "(", "ele", ...
25.369565
0.011551
def _separators(strings, linewidth): """Return separators that keep joined strings within the line width.""" if len(strings) <= 1: return () indent_len = 4 separators = [] cur_line_len = indent_len + len(strings[0]) + 1 if cur_line_len + 2 <= linewidth and '\n' not in strings[0]: ...
[ "def", "_separators", "(", "strings", ",", "linewidth", ")", ":", "if", "len", "(", "strings", ")", "<=", "1", ":", "return", "(", ")", "indent_len", "=", "4", "separators", "=", "[", "]", "cur_line_len", "=", "indent_len", "+", "len", "(", "strings", ...
33.703704
0.000534
def transform_six_add_metaclass(node): """Check if the given class node is decorated with *six.add_metaclass* If so, inject its argument as the metaclass of the underlying class. """ if not node.decorators: return for decorator in node.decorators.nodes: if not isinstance(decorator,...
[ "def", "transform_six_add_metaclass", "(", "node", ")", ":", "if", "not", "node", ".", "decorators", ":", "return", "for", "decorator", "in", "node", ".", "decorators", ".", "nodes", ":", "if", "not", "isinstance", "(", "decorator", ",", "nodes", ".", "Cal...
31
0.001565
def telnet_login( self, pri_prompt_terminator=r"]\s*$", alt_prompt_terminator=r">\s*$", username_pattern=r"(?:user:|username|login|user name)", pwd_pattern=r"assword", delay_factor=1, max_loops=20, ): """Telnet login for Huawei Devices""" dela...
[ "def", "telnet_login", "(", "self", ",", "pri_prompt_terminator", "=", "r\"]\\s*$\"", ",", "alt_prompt_terminator", "=", "r\">\\s*$\"", ",", "username_pattern", "=", "r\"(?:user:|username|login|user name)\"", ",", "pwd_pattern", "=", "r\"assword\"", ",", "delay_factor", "...
36.629032
0.001715
def _siftup_max(heap, pos): 'Maxheap variant of _siftup' endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the larger child until hitting a leaf. childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of larger child. ...
[ "def", "_siftup_max", "(", "heap", ",", "pos", ")", ":", "endpos", "=", "len", "(", "heap", ")", "startpos", "=", "pos", "newitem", "=", "heap", "[", "pos", "]", "# Bubble up the larger child until hitting a leaf.", "childpos", "=", "2", "*", "pos", "+", "...
37.55
0.001299
def update_source(self, id, **kwargs): # noqa: E501 """Update metadata (description or tags) for a specific source. # noqa: E501 The \"hidden\" property is stored as a tag. To set the value, add \"hidden\": &lt;value&gt; to the list of tags. # noqa: E501 This method makes a synchronous HTTP ...
[ "def", "update_source", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "update_source_...
53.045455
0.001684
def confirmation_view(template, doc="Display a confirmation view."): """ Confirmation view generator for the "comment was posted/flagged/deleted/approved" views. """ def confirmed(request): comment = None if 'c' in request.GET: try: comment = comments.get_...
[ "def", "confirmation_view", "(", "template", ",", "doc", "=", "\"Display a confirmation view.\"", ")", ":", "def", "confirmed", "(", "request", ")", ":", "comment", "=", "None", "if", "'c'", "in", "request", ".", "GET", ":", "try", ":", "comment", "=", "co...
29
0.001391
def getmacbyip6(ip6, chainCC=0): """Returns the MAC address corresponding to an IPv6 address neighborCache.get() method is used on instantiated neighbor cache. Resolution mechanism is described in associated doc string. (chainCC parameter value ends up being passed to sending function used to per...
[ "def", "getmacbyip6", "(", "ip6", ",", "chainCC", "=", "0", ")", ":", "if", "isinstance", "(", "ip6", ",", "Net6", ")", ":", "ip6", "=", "str", "(", "ip6", ")", "if", "in6_ismaddr", "(", "ip6", ")", ":", "# Multicast", "mac", "=", "in6_getnsmac", "...
25.925
0.000929
def delete_folder(self, uri, purge=False): """Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without sending it to Trash """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: ...
[ "def", "delete_folder", "(", "self", ",", "uri", ",", "purge", "=", "False", ")", ":", "try", ":", "resource", "=", "self", ".", "get_resource_by_uri", "(", "uri", ")", "except", "ResourceNotFoundError", ":", "# Nothing to remove", "return", "None", "if", "n...
27.305556
0.001965
def _drop_definition(self): """Remove header definition associated with this section.""" rId = self._sectPr.remove_headerReference(self._hdrftr_index) self._document_part.drop_header_part(rId)
[ "def", "_drop_definition", "(", "self", ")", ":", "rId", "=", "self", ".", "_sectPr", ".", "remove_headerReference", "(", "self", ".", "_hdrftr_index", ")", "self", ".", "_document_part", ".", "drop_header_part", "(", "rId", ")" ]
53.25
0.009259
def weights(self, matrix_id=0): """ Return the frame for the respective weight matrix. :param: matrix_id: an integer, ranging from 0 to number of layers, that specifies the weight matrix to return. :returns: an H2OFrame which represents the weight matrix identified by matrix_id ...
[ "def", "weights", "(", "self", ",", "matrix_id", "=", "0", ")", ":", "return", "{", "model", ".", "model_id", ":", "model", ".", "weights", "(", "matrix_id", ")", "for", "model", "in", "self", ".", "models", "}" ]
49.875
0.012315
def cleanup_a_alpha_and_derivatives(self): r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for every component''' del(self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, self.kappa3, self.Tc)
[ "def", "cleanup_a_alpha_and_derivatives", "(", "self", ")", ":", "del", "(", "self", ".", "a", ",", "self", ".", "kappa", ",", "self", ".", "kappa0", ",", "self", ".", "kappa1", ",", "self", ".", "kappa2", ",", "self", ".", "kappa3", ",", "self", "."...
62.8
0.012579
def get_receipt_by_index(self, block_number: BlockNumber, receipt_index: int) -> Receipt: """ Returns the Receipt of the transaction at specified index for the block header obtained by the specified block number """ try: ...
[ "def", "get_receipt_by_index", "(", "self", ",", "block_number", ":", "BlockNumber", ",", "receipt_index", ":", "int", ")", "->", "Receipt", ":", "try", ":", "block_header", "=", "self", ".", "get_canonical_block_header_by_number", "(", "block_number", ")", "excep...
45.95
0.008529
def lm_deltat(freqs, damping_times, modes): """Return the minimum delta_t of all the modes given, with delta_t given by the inverse of the frequency at which the amplitude of the ringdown falls to 1/1000 of the peak amplitude. """ dt = {} for lmn in modes: l, m, nmodes = int(lmn[0]), in...
[ "def", "lm_deltat", "(", "freqs", ",", "damping_times", ",", "modes", ")", ":", "dt", "=", "{", "}", "for", "lmn", "in", "modes", ":", "l", ",", "m", ",", "nmodes", "=", "int", "(", "lmn", "[", "0", "]", ")", ",", "int", "(", "lmn", "[", "1",...
34.611111
0.021875
def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash ...
[ "def", "tablespace_alter", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "new_name", "=", "None", ",", "new_owner", "=", "None", ",", ...
37.659091
0.001765
def load_data_batch(self, data_batch): """Load data and labels into arrays.""" _load_data(data_batch, self.data_arrays) _load_label(data_batch, self.label_arrays)
[ "def", "load_data_batch", "(", "self", ",", "data_batch", ")", ":", "_load_data", "(", "data_batch", ",", "self", ".", "data_arrays", ")", "_load_label", "(", "data_batch", ",", "self", ".", "label_arrays", ")" ]
45.75
0.010753
def joinpaths(self, *paths): """Mimic os.path.join using the specified path_separator. Args: *paths: (str) Zero or more paths to join. Returns: (str) The paths joined by the path separator, starting with the last absolute path in paths. """ ...
[ "def", "joinpaths", "(", "self", ",", "*", "paths", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "6", ")", ":", "paths", "=", "[", "os", ".", "fspath", "(", "path", ")", "for", "path", "in", "paths", "]", "if", "len", "(", ...
39.551724
0.001702
def page(self, value): """ Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object """ instance = copy(self) ins...
[ "def", "page", "(", "self", ",", "value", ")", ":", "instance", "=", "copy", "(", "self", ")", "instance", ".", "_filters", ".", "append", "(", "{", "'page'", ":", "value", "}", ")", "return", "instance" ]
26
0.009901
def _send_and_receive(self, target, lun, netfn, cmdid, payload): """Send and receive data using aardvark interface. target: lun: netfn: cmdid: payload: IPMI message payload as bytestring Returns the received data as bytestring """ self._inc_seque...
[ "def", "_send_and_receive", "(", "self", ",", "target", ",", "lun", ",", "netfn", ",", "cmdid", ",", "payload", ")", ":", "self", ".", "_inc_sequence_number", "(", ")", "# assemble IPMB header", "header", "=", "IpmbHeaderReq", "(", ")", "header", ".", "netfn...
27
0.001881
def get_uplink_dvportgroup(dvs_ref): ''' Returns the uplink distributed virtual portgroup of a distributed virtual switch (dvs) dvs_ref The dvs reference ''' dvs_name = get_managed_object_name(dvs_ref) log.trace('Retrieving uplink portgroup of dvs \'%s\'', dvs_name) traversal_sp...
[ "def", "get_uplink_dvportgroup", "(", "dvs_ref", ")", ":", "dvs_name", "=", "get_managed_object_name", "(", "dvs_ref", ")", "log", ".", "trace", "(", "'Retrieving uplink portgroup of dvs \\'%s\\''", ",", "dvs_name", ")", "traversal_spec", "=", "vmodl", ".", "query", ...
42.444444
0.000853
def file_hash(self, filename, block_size=2**20): '''Calculate MD5 hash code for a local file''' m = hashlib.md5() with open(filename, 'rb') as f: while True: data = f.read(block_size) if not data: break m.update(data) return m.hexdigest()
[ "def", "file_hash", "(", "self", ",", "filename", ",", "block_size", "=", "2", "**", "20", ")", ":", "m", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "data", "=", ...
28.5
0.010204
def _extract_packages(self): """ Extract a package in a new directory. """ self.path_unpacked = [] if not hasattr(self, "retrieved_packages_unpacked"): self.retrieved_packages_unpacked = [self.package_name] for path in self.retrieved_packages_unpacked: ...
[ "def", "_extract_packages", "(", "self", ")", ":", "self", ".", "path_unpacked", "=", "[", "]", "if", "not", "hasattr", "(", "self", ",", "\"retrieved_packages_unpacked\"", ")", ":", "self", ".", "retrieved_packages_unpacked", "=", "[", "self", ".", "package_n...
40.72
0.001919
def get_resource_operations(cls): '''Return the swagger-formatted method descriptions''' operations = [] for http, callback in cls.implemented_methods.items(): # Parse docstring summary, notes = utils.parse_docstring(callback) # Parse return annotations ...
[ "def", "get_resource_operations", "(", "cls", ")", ":", "operations", "=", "[", "]", "for", "http", ",", "callback", "in", "cls", ".", "implemented_methods", ".", "items", "(", ")", ":", "# Parse docstring", "summary", ",", "notes", "=", "utils", ".", "par...
43.157895
0.002387
def to_url(self, site='amazon', country='us'): """Generate a link to an online book site. Args: site (str): Site to create link to country (str): Country specific version of ``site`` Returns: ``str``: URL on ``site`` for book Raises: Sit...
[ "def", "to_url", "(", "self", ",", "site", "=", "'amazon'", ",", "country", "=", "'us'", ")", ":", "try", ":", "try", ":", "url", ",", "tlds", "=", "URL_MAP", "[", "site", "]", "except", "ValueError", ":", "tlds", "=", "None", "url", "=", "URL_MAP"...
27.59375
0.002188
def sort_dict(key_counts, by_key=False): '''Accept a dict of key:values (numerics) returning list of key-value tuples ordered by desc values. If by_key=True, sorts by dict key.''' sort_key = lambda x: (-1 * x[1], x[0]) if by_key: sort_key = lambda x: x[0] return sorted(key_counts.items(), k...
[ "def", "sort_dict", "(", "key_counts", ",", "by_key", "=", "False", ")", ":", "sort_key", "=", "lambda", "x", ":", "(", "-", "1", "*", "x", "[", "1", "]", ",", "x", "[", "0", "]", ")", "if", "by_key", ":", "sort_key", "=", "lambda", "x", ":", ...
40.625
0.012048
def from_data(self, time, value, series_id=None, key=None, tz=None): """Create a DataPoint object from data, rather than a JSON object or string. This should be used by user code to construct DataPoints from Python-based data like Datetime objects and floats. The series_id and key argu...
[ "def", "from_data", "(", "self", ",", "time", ",", "value", ",", "series_id", "=", "None", ",", "key", "=", "None", ",", "tz", "=", "None", ")", ":", "t", "=", "check_time_param", "(", "time", ")", "if", "type", "(", "value", ")", "in", "[", "flo...
40.805556
0.00133
def left_overlaps(self, other, min_overlap_size=1): """ Does this VariantSequence overlap another on the left side? """ if self.alt != other.alt: # allele must match! return False if len(other.prefix) > len(self.prefix): # only consider strin...
[ "def", "left_overlaps", "(", "self", ",", "other", ",", "min_overlap_size", "=", "1", ")", ":", "if", "self", ".", "alt", "!=", "other", ".", "alt", ":", "# allele must match!", "return", "False", "if", "len", "(", "other", ".", "prefix", ")", ">", "le...
37.540541
0.002105
def parse_seeds_xml(root): """ Parse <seeds> element in the UBCPI XBlock's content XML. Args: root (lxml.etree.Element): The root of the <seeds> node in the tree. Returns: a list of deserialized representation of seeds. E.g. [{ 'answer': 1, # option index starting ...
[ "def", "parse_seeds_xml", "(", "root", ")", ":", "seeds", "=", "[", "]", "for", "seed_el", "in", "root", ".", "findall", "(", "'seed'", ")", ":", "seed_dict", "=", "dict", "(", ")", "seed_dict", "[", "'rationale'", "]", "=", "_safe_get_text", "(", "see...
26.030303
0.002245
def neg_loglik(self, beta): """ Creates the negative log-likelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- The negative logliklihood of the model """ ...
[ "def", "neg_loglik", "(", "self", ",", "beta", ")", ":", "lmda", ",", "Y", ",", "___", ",", "theta", "=", "self", ".", "_model", "(", "beta", ")", "return", "-", "np", ".", "sum", "(", "logpdf", "(", "Y", ",", "self", ".", "latent_variables", "."...
34.235294
0.018395
def hacking_has_correct_license(physical_line, filename, lines, line_number): """Check for Apache 2.0 license. H103 header does not match Apache 2.0 License notice """ # don't work about init files for now # TODO(sdague): enforce license in init file if it's not empty of content # skip files t...
[ "def", "hacking_has_correct_license", "(", "physical_line", ",", "filename", ",", "lines", ",", "line_number", ")", ":", "# don't work about init files for now", "# TODO(sdague): enforce license in init file if it's not empty of content", "# skip files that are < 10 lines, which isn't en...
49.052632
0.001053
def getXML(self, CorpNum, NTSConfirmNum, UserID=None): """ 전자세금계산서 상세정보 확인 - XML args CorpNum : 팝빌회원 사업자번호 NTSConfirmNum : 국세청 승인번호 UserID : 팝빌회원 아이디 return 전자세금계산서 정보객체 raise PopbillException ...
[ "def", "getXML", "(", "self", ",", "CorpNum", ",", "NTSConfirmNum", ",", "UserID", "=", "None", ")", ":", "if", "NTSConfirmNum", "==", "None", "or", "len", "(", "NTSConfirmNum", ")", "!=", "24", ":", "raise", "PopbillException", "(", "-", "99999999", ","...
37.2
0.008741
def select(cls, verb): """ Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains ...
[ "def", "select", "(", "cls", ",", "verb", ")", ":", "columns", "=", "verb", ".", "data", ".", "columns", "contains", "=", "verb", ".", "contains", "matches", "=", "verb", ".", "matches", "groups", "=", "_get_groups", "(", "verb", ")", "names", "=", "...
29.838235
0.000954
def _consume_flags(self): """Read flags until we encounter the first token that isn't a flag.""" flags = [] while self._at_flag(): flag = self._unconsumed_args.pop() if not self._check_for_help_request(flag): flags.append(flag) return flags
[ "def", "_consume_flags", "(", "self", ")", ":", "flags", "=", "[", "]", "while", "self", ".", "_at_flag", "(", ")", ":", "flag", "=", "self", ".", "_unconsumed_args", ".", "pop", "(", ")", "if", "not", "self", ".", "_check_for_help_request", "(", "flag...
33.625
0.01087
def dump_set(self, obj, class_name=set_class_name): """ ``set`` dumper. """ return {"$" + class_name: [self._json_convert(item) for item in obj]}
[ "def", "dump_set", "(", "self", ",", "obj", ",", "class_name", "=", "set_class_name", ")", ":", "return", "{", "\"$\"", "+", "class_name", ":", "[", "self", ".", "_json_convert", "(", "item", ")", "for", "item", "in", "obj", "]", "}" ]
34.6
0.011299
def _get_option_to_record(self, scope, option=None): """Looks up an option scope (and optionally option therein) in the options parsed by Pants. Returns a dict of of all options in the scope, if option is None. Returns the specific option if option is not None. Raises ValueError if scope or option coul...
[ "def", "_get_option_to_record", "(", "self", ",", "scope", ",", "option", "=", "None", ")", ":", "scope_to_look_up", "=", "scope", "if", "scope", "!=", "'GLOBAL'", "else", "''", "try", ":", "value", "=", "self", ".", "_all_options", ".", "for_scope", "(", ...
41.45
0.009434
def _get_nws_feed(self): """get nws alert feed, and cache it""" url = '''http://alerts.weather.gov/cap/%s.php?x=0''' % (str(self._state).lower()) # pylint: disable=E1103 xml = requests.get(url).content return xml
[ "def", "_get_nws_feed", "(", "self", ")", ":", "url", "=", "'''http://alerts.weather.gov/cap/%s.php?x=0'''", "%", "(", "str", "(", "self", ".", "_state", ")", ".", "lower", "(", ")", ")", "# pylint: disable=E1103", "xml", "=", "requests", ".", "get", "(", "u...
41.166667
0.011905
def to_dict(self, field=None, **kwargs): """ Convert the ParameterSet to a structured (nested) dictionary to allow traversing the structure from the bottom up :parameter str field: (optional) build the dictionary with keys at a given level/field. Can be any of the keys in ...
[ "def", "to_dict", "(", "self", ",", "field", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "return", "self", ".", "filter", "(", "*", "*", "kwargs", ")", ".", "to_dict", "(", "field", "=", "field", ")", "if", "field", "is",...
48.042553
0.001302
def smooth(x, y, degree=3): """Smooth y-values and return new x, y pair.""" if degree == 1: return x, y elif not isodd(degree): raise ValueError("Degree must be an odd number") else: window_width = int(degree / 2) data_size = len(y) - degree + 1 smoothed_y = np....
[ "def", "smooth", "(", "x", ",", "y", ",", "degree", "=", "3", ")", ":", "if", "degree", "==", "1", ":", "return", "x", ",", "y", "elif", "not", "isodd", "(", "degree", ")", ":", "raise", "ValueError", "(", "\"Degree must be an odd number\"", ")", "el...
27.421053
0.001855
def add_to_dict_val_set(dict_obj, key, val): """Adds the given val to the set mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': set([1, 2])} >>> add_to_dict_val_set(dict_obj, 'a', 2) >>> print(dict_obj['a']) {1...
[ "def", "add_to_dict_val_set", "(", "dict_obj", ",", "key", ",", "val", ")", ":", "try", ":", "dict_obj", "[", "key", "]", ".", "add", "(", "val", ")", "except", "KeyError", ":", "dict_obj", "[", "key", "]", "=", "set", "(", "[", "val", "]", ")" ]
27.777778
0.001934
def yield_for_all_futures(result): """ Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, then if the value inside the Future is another Future we yield until it's done as well, and so on. """ while True: # This is needed ...
[ "def", "yield_for_all_futures", "(", "result", ")", ":", "while", "True", ":", "# This is needed for Tornado >= 4.5 where convert_yielded will no", "# longer raise BadYieldError on None", "if", "result", "is", "None", ":", "break", "try", ":", "future", "=", "gen", ".", ...
31.318182
0.001408
def write_float(self, number): """ Writes a float to the underlying output file as a 4-byte value. """ buf = pack(self.byte_order + "f", number) self.write(buf)
[ "def", "write_float", "(", "self", ",", "number", ")", ":", "buf", "=", "pack", "(", "self", ".", "byte_order", "+", "\"f\"", ",", "number", ")", "self", ".", "write", "(", "buf", ")" ]
45.25
0.01087
def _get_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired. """ request = view_obj.request view_method = getattr(view_obj, request.ac...
[ "def", "_get_event_kwargs", "(", "view_obj", ")", ":", "request", "=", "view_obj", ".", "request", "view_method", "=", "getattr", "(", "view_obj", ",", "request", ".", "action", ")", "do_trigger", "=", "not", "(", "getattr", "(", "view_method", ",", "'_silen...
31.653846
0.001179
def add_parent(self,node): """ Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent. """ if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ): raise CondorDAGNodeError, "Parent must be a Con...
[ "def", "add_parent", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "(", "CondorDAGNode", ",", "CondorDAGManNode", ")", ")", ":", "raise", "CondorDAGNodeError", ",", "\"Parent must be a CondorDAGNode or a CondorDAGManNode\"", "self"...
42.111111
0.023256
def execute(command, shell=None, working_dir=".", echo=False, echo_indent=0): """Execute a command on the command-line. :param str,list command: The command to run :param bool shell: Whether or not to use the shell. This is optional; if ``command`` is a basestring, shell will be set to True, otherw...
[ "def", "execute", "(", "command", ",", "shell", "=", "None", ",", "working_dir", "=", "\".\"", ",", "echo", "=", "False", ",", "echo_indent", "=", "0", ")", ":", "if", "shell", "is", "None", ":", "shell", "=", "True", "if", "isinstance", "(", "comman...
36.871795
0.001355
def _reset_param(self, param): """ Resets a single parameter :param param: A configuration parameter :type param: str """ if param not in self._instance.CONFIG_PARAMS: raise ValueError("Cannot reset unknown parameter '{}'".format(param)) setattr(self, param, ...
[ "def", "_reset_param", "(", "self", ",", "param", ")", ":", "if", "param", "not", "in", "self", ".", "_instance", ".", "CONFIG_PARAMS", ":", "raise", "ValueError", "(", "\"Cannot reset unknown parameter '{}'\"", ".", "format", "(", "param", ")", ")", "setattr"...
38.666667
0.008427
def add_query_occurrence(self, report): """Adds a report to the report aggregation""" initial_millis = int(report['parsed']['stats']['millis']) mask = report['queryMask'] existing_report = self._get_existing_report(mask, report) if existing_report is not None: self...
[ "def", "add_query_occurrence", "(", "self", ",", "report", ")", ":", "initial_millis", "=", "int", "(", "report", "[", "'parsed'", "]", "[", "'stats'", "]", "[", "'millis'", "]", ")", "mask", "=", "report", "[", "'queryMask'", "]", "existing_report", "=", ...
43
0.001896
def RebuildHttpConnections(http): """Rebuilds all http connections in the httplib2.Http instance. httplib2 overloads the map in http.connections to contain two different types of values: { scheme string: connection class } and { scheme + authority string : actual http connection } Here we remo...
[ "def", "RebuildHttpConnections", "(", "http", ")", ":", "if", "getattr", "(", "http", ",", "'connections'", ",", "None", ")", ":", "for", "conn_key", "in", "list", "(", "http", ".", "connections", ".", "keys", "(", ")", ")", ":", "if", "':'", "in", "...
39.352941
0.00146
def get_paths_cfg( sys_file='pythran.cfg', platform_file='pythran-{}.cfg'.format(sys.platform), user_file='.pythranrc' ): """ >>> os.environ['HOME'] = '/tmp/test' >>> get_paths_cfg()['user'] '/tmp/test/.pythranrc' >>> os.environ['HOME'] = '/tmp/test' >>> os.environ['XDG_CONFIG_HOME']...
[ "def", "get_paths_cfg", "(", "sys_file", "=", "'pythran.cfg'", ",", "platform_file", "=", "'pythran-{}.cfg'", ".", "format", "(", "sys", ".", "platform", ")", ",", "user_file", "=", "'.pythranrc'", ")", ":", "sys_config_dir", "=", "os", ".", "path", ".", "di...
37.1
0.001751