text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def reset(cls): """Reset the registry to the standard multihash functions.""" # Maps function names (hyphens or underscores) to registered functions. cls._func_from_name = {} # Maps hashlib names to registered functions. cls._func_from_hash = {} # Hashlib compatibility ...
[ "def", "reset", "(", "cls", ")", ":", "# Maps function names (hyphens or underscores) to registered functions.", "cls", ".", "_func_from_name", "=", "{", "}", "# Maps hashlib names to registered functions.", "cls", ".", "_func_from_hash", "=", "{", "}", "# Hashlib compatibili...
37.2
19.133333
def calcELAxi(R,vR,vT,pot,vc=1.,ro=1.): """ NAME: calcELAxi PURPOSE: calculate the energy and angular momentum INPUT: R - Galactocentric radius (/ro) vR - radial part of the velocity (/vc) vT - azimuthal part of the velocity (/vc) vc - circular velocity r...
[ "def", "calcELAxi", "(", "R", ",", "vR", ",", "vT", ",", "pot", ",", "vc", "=", "1.", ",", "ro", "=", "1.", ")", ":", "return", "(", "potentialAxi", "(", "R", ",", "pot", ")", "+", "vR", "**", "2.", "/", "2.", "+", "vT", "**", "2.", "/", ...
27.5
14.555556
def parse_c_serialized(f): """ Reads in a binary file created by a C++ serializer (prob. MFC?) and returns tuples of (header name, data following the header). These are used by Thermo for *.CF and *.DXF files and by Agilent for new-style *.REG files. """ # TODO: rewrite to use re library ...
[ "def", "parse_c_serialized", "(", "f", ")", ":", "# TODO: rewrite to use re library", "f", ".", "seek", "(", "0", ")", "try", ":", "p_rec_type", "=", "None", "while", "True", ":", "rec_off", "=", "f", ".", "tell", "(", ")", "while", "True", ":", "if", ...
36.970588
12.911765
def job_to_dict(job): """Converts a job to an OrderedDict.""" data = OrderedDict() data['id'] = job.id data['name'] = job.name data['func'] = job.func_ref data['args'] = job.args data['kwargs'] = job.kwargs data.update(trigger_to_dict(job.trigger)) if not job.pending: data...
[ "def", "job_to_dict", "(", "job", ")", ":", "data", "=", "OrderedDict", "(", ")", "data", "[", "'id'", "]", "=", "job", ".", "id", "data", "[", "'name'", "]", "=", "job", ".", "name", "data", "[", "'func'", "]", "=", "job", ".", "func_ref", "data...
28.111111
21.055556
def get_all_tgt(self): """ Returns a list of AS_REP tickets in native format (dict). To determine which ticket are AP_REP we check for the server principal to be the kerberos service """ tgts = [] for cred in self.credentials: if cred.server.to_string().lower().find('krbtgt') != -1: tgts.append(cred...
[ "def", "get_all_tgt", "(", "self", ")", ":", "tgts", "=", "[", "]", "for", "cred", "in", "self", ".", "credentials", ":", "if", "cred", ".", "server", ".", "to_string", "(", ")", ".", "lower", "(", ")", ".", "find", "(", "'krbtgt'", ")", "!=", "-...
30.454545
21
def process_entry(self, entry): 'Construct a Post from a feedparser entry and save/update it in db' from feedjack.models import Post, Tag ## Construct a Post object from feedparser entry (FeedParserDict) post = Post(feed=self.feed) post.link = entry.get('link', self.feed.link) post.title = entry.get('titl...
[ "def", "process_entry", "(", "self", ",", "entry", ")", ":", "from", "feedjack", ".", "models", "import", "Post", ",", "Tag", "## Construct a Post object from feedparser entry (FeedParserDict)", "post", "=", "Post", "(", "feed", "=", "self", ".", "feed", ")", "p...
38.666667
21.777778
def remove_callback(instance, prop, callback): """ Remove a callback function from a property in an instance Parameters ---------- instance The instance to detach the callback from prop : str Name of callback property in `instance` callback : func The callback functi...
[ "def", "remove_callback", "(", "instance", ",", "prop", ",", "callback", ")", ":", "p", "=", "getattr", "(", "type", "(", "instance", ")", ",", "prop", ")", "if", "not", "isinstance", "(", "p", ",", "CallbackProperty", ")", ":", "raise", "TypeError", "...
30.058824
14.058824
def _expect(self, expected, times=50): """Find the `expected` line within `times` trials. Args: expected str: the expected string times int: number of trials """ print '[%s] Expecting [%s]' % (self.port, expected) retry_times = 10 while ...
[ "def", "_expect", "(", "self", ",", "expected", ",", "times", "=", "50", ")", ":", "print", "'[%s] Expecting [%s]'", "%", "(", "self", ".", "port", ",", "expected", ")", "retry_times", "=", "10", "while", "times", ">", "0", "and", "retry_times", ">", "...
29.36
19.16
def description(self): """ A list of the metrics this query will ask for. """ if 'metrics' in self.raw: metrics = self.raw['metrics'] head = metrics[0:-1] or metrics[0:1] text = ", ".join(head) if len(metrics) > 1: tail = m...
[ "def", "description", "(", "self", ")", ":", "if", "'metrics'", "in", "self", ".", "raw", ":", "metrics", "=", "self", ".", "raw", "[", "'metrics'", "]", "head", "=", "metrics", "[", "0", ":", "-", "1", "]", "or", "metrics", "[", "0", ":", "1", ...
26.25
13.5
def dereference_package_descriptor(descriptor, base_path): """Dereference data package descriptor (IN-PLACE FOR NOW). """ for resource in descriptor.get('resources', []): dereference_resource_descriptor(resource, base_path, descriptor) return descriptor
[ "def", "dereference_package_descriptor", "(", "descriptor", ",", "base_path", ")", ":", "for", "resource", "in", "descriptor", ".", "get", "(", "'resources'", ",", "[", "]", ")", ":", "dereference_resource_descriptor", "(", "resource", ",", "base_path", ",", "de...
45.333333
13.5
def pulls(self, from_date=None): """Fetch the pull requests from the repository. The method retrieves, from a GitHub repository, the pull requests updated since the given date. :param from_date: obtain pull requests updated since this date :returns: a generator of pull request...
[ "def", "pulls", "(", "self", ",", "from_date", "=", "None", ")", ":", "issues_groups", "=", "self", ".", "issues", "(", "from_date", "=", "from_date", ")", "for", "raw_issues", "in", "issues_groups", ":", "issues", "=", "json", ".", "loads", "(", "raw_is...
31.192308
20.961538
def _produce_return(self, cursor): """ Return the one result. """ results = cursor.fetchmany(2) if len(results) != 1: return None # Return the one row, or the one column. row = results[0] if self._row_formatter is not None: row = self._row...
[ "def", "_produce_return", "(", "self", ",", "cursor", ")", ":", "results", "=", "cursor", ".", "fetchmany", "(", "2", ")", "if", "len", "(", "results", ")", "!=", "1", ":", "return", "None", "# Return the one row, or the one column.", "row", "=", "results", ...
26.8
13.666667
def _compile_column_metadata(row, keys, number): """ Compile column metadata from one excel row ("9 part data") :param list row: Row of cells :param list keys: Variable header keys :return dict: Column metadata """ # Store the variable keys by index in a dictionary _column = {} _inte...
[ "def", "_compile_column_metadata", "(", "row", ",", "keys", ",", "number", ")", ":", "# Store the variable keys by index in a dictionary", "_column", "=", "{", "}", "_interpretation", "=", "{", "}", "_calibration", "=", "{", "}", "_physical", "=", "{", "}", "# U...
37.797468
19.392405
def download(gfile, wks_name=None, col_names=False, row_names=False, credentials=None, start_cell = 'A1'): """ Download Google Spreadsheet and convert it to Pandas DataFrame :param gfile: path to Google Spreadsheet or gspread ID :param wks_name: worksheet name :param col...
[ "def", "download", "(", "gfile", ",", "wks_name", "=", "None", ",", "col_names", "=", "False", ",", "row_names", "=", "False", ",", "credentials", "=", "None", ",", "start_cell", "=", "'A1'", ")", ":", "# access credentials", "credentials", "=", "get_credent...
34.473684
21.673684
def memoize(method): """A new method which acts like the given method but memoizes arguments See https://en.wikipedia.org/wiki/Memoization for the general idea >>> @memoize ... def test(arg): ... print('called') ... return arg + 1 >>> test(1) called 2 >>> test(2) cal...
[ "def", "memoize", "(", "method", ")", ":", "method", ".", "cache", "=", "{", "}", "def", "invalidate", "(", "*", "arguments", ",", "*", "*", "keyword_arguments", ")", ":", "key", "=", "_represent_arguments", "(", "*", "arguments", ",", "*", "*", "keywo...
29.5
20.62963
def get_trunk_interfaces(auth, url, devid=None, devip=None): """Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass ...
[ "def", "get_trunk_interfaces", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'",...
37.684211
25.350877
def insert_loudest_triggers_option_group(parser, coinc_options=True): """ Add options to the optparser object for selecting templates in bins. Parameters ----------- parser : object OptionParser instance. """ opt_group = insert_bank_bins_option_group(parser) opt_group.title = "Optio...
[ "def", "insert_loudest_triggers_option_group", "(", "parser", ",", "coinc_options", "=", "True", ")", ":", "opt_group", "=", "insert_bank_bins_option_group", "(", "parser", ")", "opt_group", ".", "title", "=", "\"Options for finding loudest triggers.\"", "if", "coinc_opti...
52.375
22.34375
def setup_logging(config_path=None, log_level=logging.INFO, formatter='standard'): """Setup logging configuration """ config = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': ...
[ "def", "setup_logging", "(", "config_path", "=", "None", ",", "log_level", "=", "logging", ".", "INFO", ",", "formatter", "=", "'standard'", ")", ":", "config", "=", "{", "'version'", ":", "1", ",", "'disable_existing_loggers'", ":", "False", ",", "'formatte...
27.791667
16.729167
def export_csv(self, spec, asset_refs, curves_dict): """ :param asset_ref: name of the asset :param curves_dict: a dictionary tag -> loss curves """ writer = writers.CsvWriter(fmt=writers.FIVEDIGITS) ebr = hasattr(self, 'builder') for key in sorted(curves_dict): ...
[ "def", "export_csv", "(", "self", ",", "spec", ",", "asset_refs", ",", "curves_dict", ")", ":", "writer", "=", "writers", ".", "CsvWriter", "(", "fmt", "=", "writers", ".", "FIVEDIGITS", ")", "ebr", "=", "hasattr", "(", "self", ",", "'builder'", ")", "...
51.62963
15.407407
def _ProcessMessages(self, notification, queue_manager): """Does the real work with a single flow.""" flow_obj = None session_id = notification.session_id try: # Take a lease on the flow: flow_name = session_id.FlowName() if flow_name in self.well_known_flows: # Well known flo...
[ "def", "_ProcessMessages", "(", "self", ",", "notification", ",", "queue_manager", ")", ":", "flow_obj", "=", "None", "session_id", "=", "notification", ".", "session_id", "try", ":", "# Take a lease on the flow:", "flow_name", "=", "session_id", ".", "FlowName", ...
42.567901
23.45679
async def create_signing_key(self, seed: str = None, metadata: dict = None) -> KeyInfo: """ Create a new signing key pair. Raise WalletState if wallet is closed, ExtantRecord if verification key already exists. :param seed: optional seed allowing deterministic key creation :par...
[ "async", "def", "create_signing_key", "(", "self", ",", "seed", ":", "str", "=", "None", ",", "metadata", ":", "dict", "=", "None", ")", "->", "KeyInfo", ":", "LOGGER", ".", "debug", "(", "'Wallet.create_signing_key >>> seed: [SEED], metadata: %s'", ",", "metada...
47.709677
33.709677
def disconnect(self): """ Disconnect from the Kafka broker. This is used to implement disconnection on timeout as a workaround for Kafka connections occasionally getting stuck on the server side under load. Requests are not cancelled, so they will be retried. """ ...
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "proto", ":", "log", ".", "debug", "(", "'%r Disconnecting from %r'", ",", "self", ",", "self", ".", "proto", ".", "transport", ".", "getPeer", "(", ")", ")", "self", ".", "proto", ".", "...
42.090909
21.363636
def get_max_instability(self, min_voltage=None, max_voltage=None): """ The maximum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum d...
[ "def", "get_max_instability", "(", "self", ",", "min_voltage", "=", "None", ",", "max_voltage", "=", "None", ")", ":", "data", "=", "[", "]", "for", "pair", "in", "self", ".", "_select_in_voltage_range", "(", "min_voltage", ",", "max_voltage", ")", ":", "i...
42.157895
21.421053
def _static(self, target, value): """PHP's "static" """ return 'static ' + self.__p(ast.Assign(targets=[target],value=value))
[ "def", "_static", "(", "self", ",", "target", ",", "value", ")", ":", "return", "'static '", "+", "self", ".", "__p", "(", "ast", ".", "Assign", "(", "targets", "=", "[", "target", "]", ",", "value", "=", "value", ")", ")" ]
29.2
16.8
def _write_file(iface, data, folder, pattern): ''' Writes a file to disk ''' filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise...
[ "def", "_write_file", "(", "iface", ",", "data", ",", "folder", ",", "pattern", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "pattern", ".", "format", "(", "iface", ")", ")", "if", "not", "os", ".", "path", ".", ...
35.461538
15.923077
def get_contents(self, element): """ Retrieve the contents of an element :param element: The XML Element object :type element: etree._Element :return: A list of responses :rtype : list of Response """ return [Response(self.trigger, child, self.file_path)...
[ "def", "get_contents", "(", "self", ",", "element", ")", ":", "return", "[", "Response", "(", "self", ".", "trigger", ",", "child", ",", "self", ".", "file_path", ")", "for", "child", "in", "element", "if", "child", ".", "tag", "in", "[", "'response'",...
35.363636
11.727273
def drop_trailing_zeros(num): """ Drops the trailing zeros in a float that is printed. """ txt = '%f' %(num) txt = txt.rstrip('0') if txt.endswith('.'): txt = txt[:-1] return txt
[ "def", "drop_trailing_zeros", "(", "num", ")", ":", "txt", "=", "'%f'", "%", "(", "num", ")", "txt", "=", "txt", ".", "rstrip", "(", "'0'", ")", "if", "txt", ".", "endswith", "(", "'.'", ")", ":", "txt", "=", "txt", "[", ":", "-", "1", "]", "...
22.888889
13.333333
def _parse_cluster_manage_command(cls, args, action): """ Parse command line arguments for cluster manage commands. """ argparser = ArgumentParser(prog="cluster_manage_command") group = argparser.add_mutually_exclusive_group(required=True) group.add_argument("--id", dest="cluster_...
[ "def", "_parse_cluster_manage_command", "(", "cls", ",", "args", ",", "action", ")", ":", "argparser", "=", "ArgumentParser", "(", "prog", "=", "\"cluster_manage_command\"", ")", "group", "=", "argparser", ".", "add_mutually_exclusive_group", "(", "required", "=", ...
39.125
24.208333
def get_extended_summaryf(self, *args, **kwargs): """Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args...
[ "def", "get_extended_summaryf", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "func", "(", "f", ")", ":", "doc", "=", "f", ".", "__doc__", "self", ".", "get_extended_summary", "(", "doc", "or", "''", ",", "*", "args", ","...
36.681818
23.636364
def __finish_initializing(self): """ Handle any initialization after arguments & config has been parsed. """ if self.args.debug or self.args.trace: # Set the console (StreamHandler) to allow debug statements. if self.args.debug: self.console.setLevel(logging.DEB...
[ "def", "__finish_initializing", "(", "self", ")", ":", "if", "self", ".", "args", ".", "debug", "or", "self", ".", "args", ".", "trace", ":", "# Set the console (StreamHandler) to allow debug statements.", "if", "self", ".", "args", ".", "debug", ":", "self", ...
41.027027
26.945946
def run_samtools_faidx(job, ref_id): """ Use SAMtools to create reference index file :param JobFunctionWrappingJob job: passed automatically by Toil :param str ref_id: FileStoreID for the reference genome :return: FileStoreID for reference index :rtype: str """ job.fileStore.logToMaster...
[ "def", "run_samtools_faidx", "(", "job", ",", "ref_id", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Created reference index'", ")", "work_dir", "=", "job", ".", "fileStore", ".", "getLocalTempDir", "(", ")", "job", ".", "fileStore", ".", "r...
46
19.25
def send_message(self, to=None, msg=None): """ method to send a message to a user Parameters: to -> recipient msg -> message to send """ url = self.root_url + "send_message" values = {} if to is not None: values["to"] = to ...
[ "def", "send_message", "(", "self", ",", "to", "=", "None", ",", "msg", "=", "None", ")", ":", "url", "=", "self", ".", "root_url", "+", "\"send_message\"", "values", "=", "{", "}", "if", "to", "is", "not", "None", ":", "values", "[", "\"to\"", "]"...
29
10.214286
def get_all_role_config_groups(self): """ Get a list of role configuration groups in the service. @return: A list of ApiRoleConfigGroup objects. @since: API v3 """ return role_config_groups.get_all_role_config_groups( self._get_resource_root(), self.name, self._get_cluster_name())
[ "def", "get_all_role_config_groups", "(", "self", ")", ":", "return", "role_config_groups", ".", "get_all_role_config_groups", "(", "self", ".", "_get_resource_root", "(", ")", ",", "self", ".", "name", ",", "self", ".", "_get_cluster_name", "(", ")", ")" ]
34
15.777778
def enumerate_keyword_args(tokens): """ Iterates over *tokens* and returns a dictionary with function names as the keys and lists of keyword arguments as the values. """ keyword_args = {} inside_function = False for index, tok in enumerate(tokens): token_type = tok[0] token_s...
[ "def", "enumerate_keyword_args", "(", "tokens", ")", ":", "keyword_args", "=", "{", "}", "inside_function", "=", "False", "for", "index", ",", "tok", "in", "enumerate", "(", "tokens", ")", ":", "token_type", "=", "tok", "[", "0", "]", "token_string", "=", ...
39
11.095238
def link(self, *args): """ Start assembling a Map/Reduce operation. A shortcut for :meth:`~riak.mapreduce.RiakMapReduce.link`. :rtype: :class:`~riak.mapreduce.RiakMapReduce` """ mr = RiakMapReduce(self.client) mr.add(self.bucket.name, self.key) return mr....
[ "def", "link", "(", "self", ",", "*", "args", ")", ":", "mr", "=", "RiakMapReduce", "(", "self", ".", "client", ")", "mr", ".", "add", "(", "self", ".", "bucket", ".", "name", ",", "self", ".", "key", ")", "return", "mr", ".", "link", "(", "*",...
32.2
12
def put_all(self, map): """ Copies all of the mappings from the specified map to this map. No atomicity guarantees are given. In the case of a failure, some of the key-value tuples may get written, while others are not. :param map: (dict), map which includes mappings to be stored in thi...
[ "def", "put_all", "(", "self", ",", "map", ")", ":", "entries", "=", "{", "}", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "map", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "check_not_none", "(", "val...
49.307692
25.615385
def cancel_milestone_payment(session, milestone_id): """ Release a milestone payment """ params_data = { 'action': 'cancel', } # PUT /api/projects/0.1/milestones/{milestone_id}/?action=release endpoint = 'milestones/{}'.format(milestone_id) response = make_put_request(session, en...
[ "def", "cancel_milestone_payment", "(", "session", ",", "milestone_id", ")", ":", "params_data", "=", "{", "'action'", ":", "'cancel'", ",", "}", "# PUT /api/projects/0.1/milestones/{milestone_id}/?action=release", "endpoint", "=", "'milestones/{}'", ".", "format", "(", ...
35.111111
13.111111
def issue_reactions(self, issue_number): """Get reactions of an issue""" payload = { 'per_page': PER_PAGE, 'direction': 'asc', 'sort': 'updated' } path = urijoin("issues", str(issue_number), "reactions") return self.fetch_items(path, payload)
[ "def", "issue_reactions", "(", "self", ",", "issue_number", ")", ":", "payload", "=", "{", "'per_page'", ":", "PER_PAGE", ",", "'direction'", ":", "'asc'", ",", "'sort'", ":", "'updated'", "}", "path", "=", "urijoin", "(", "\"issues\"", ",", "str", "(", ...
28.181818
17.181818
def fill(self, term_dict, terms): # type: (Dict[int, Set[Type[Rule]]], Any) -> None """ Fill first row of the structure witch nonterminal directly rewritable to terminal. :param term_dict: Dictionary of rules directly rewritable to terminal. Key is hash of terminal, value is set ...
[ "def", "fill", "(", "self", ",", "term_dict", ",", "terms", ")", ":", "# type: (Dict[int, Set[Type[Rule]]], Any) -> None", "for", "i", "in", "range", "(", "len", "(", "terms", ")", ")", ":", "t", "=", "terms", "[", "i", "]", "self", ".", "_field", "[", ...
48.181818
18.545455
def ValidateIapJwtFromComputeEngine(iap_jwt, cloud_project_number, backend_service_id): """Validates an IAP JWT for your (Compute|Container) Engine service. Args: iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header. cloud_project_number: The project *number* for...
[ "def", "ValidateIapJwtFromComputeEngine", "(", "iap_jwt", ",", "cloud_project_number", ",", "backend_service_id", ")", ":", "expected_audience", "=", "\"/projects/{}/global/backendServices/{}\"", ".", "format", "(", "cloud_project_number", ",", "backend_service_id", ")", "ret...
42.681818
22.636364
def add_portal(self, origin, destination, symmetrical=False, **kwargs): """Connect the origin to the destination with a :class:`Portal`. Keyword arguments are the :class:`Portal`'s attributes. Exception: if keyword ``symmetrical`` == ``True``, a mirror-:class:`Portal` will be placed in ...
[ "def", "add_portal", "(", "self", ",", "origin", ",", "destination", ",", "symmetrical", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "origin", ",", "Node", ")", ":", "origin", "=", "origin", ".", "name", "if", "isinstance"...
44.842105
17.842105
def scan_module(egg_dir, base, name, stubs): """Check whether module possibly uses unsafe-for-zipfile stuff""" filename = os.path.join(base,name) if filename[:-1] in stubs: return True # Extension module pkg = base[len(egg_dir)+1:].replace(os.sep,'.') module = pkg+(pkg and '.' or '')+os...
[ "def", "scan_module", "(", "egg_dir", ",", "base", ",", "name", ",", "stubs", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "base", ",", "name", ")", "if", "filename", "[", ":", "-", "1", "]", "in", "stubs", ":", "return", "True...
41.441176
16.764706
def _build_path(self): ''' Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server. ''' if not self.path: self.path = '/' ...
[ "def", "_build_path", "(", "self", ")", ":", "if", "not", "self", ".", "path", ":", "self", ".", "path", "=", "'/'", "if", "self", ".", "uri_parameters", ":", "self", ".", "path", "=", "self", ".", "path", "+", "';'", "+", "requote_uri", "(", "self...
31.28125
23.59375
def parse_polygonal_poi(coords, response): """ Parse areal POI way polygons from OSM node coords. Parameters ---------- coords : dict dict of node IDs and their lat, lon coordinates Returns ------- dict of POIs containing each's nodes, polygon geometry, and osmid """ i...
[ "def", "parse_polygonal_poi", "(", "coords", ",", "response", ")", ":", "if", "'type'", "in", "response", "and", "response", "[", "'type'", "]", "==", "'way'", ":", "nodes", "=", "response", "[", "'nodes'", "]", "try", ":", "polygon", "=", "Polygon", "("...
27.25
21.5
def blit(self, surface, pos=(0, 0)): """ Blits a surface on the screen at pos :param surface: Surface to blit :param pos: Top left corner to start blitting :type surface: Surface :type pos: tuple """ for x in range(surface.width): for y in ran...
[ "def", "blit", "(", "self", ",", "surface", ",", "pos", "=", "(", "0", ",", "0", ")", ")", ":", "for", "x", "in", "range", "(", "surface", ".", "width", ")", ":", "for", "y", "in", "range", "(", "surface", ".", "height", ")", ":", "point", "=...
35.571429
10.142857
def x509_name(name): """Parses a subject into a :py:class:`x509.Name <cg:cryptography.x509.Name>`. If ``name`` is a string, :py:func:`parse_name` is used to parse it. >>> x509_name('/C=AT/CN=example.com') <Name(C=AT,CN=example.com)> >>> x509_name([('C', 'AT'), ('CN', 'example.com')]) <Name(C=A...
[ "def", "x509_name", "(", "name", ")", ":", "if", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ":", "name", "=", "parse_name", "(", "name", ")", "return", "x509", ".", "Name", "(", "[", "x509", ".", "NameAttribute", "(", "NAME_OID_MA...
37
20.285714
def collect_impl(self): """ overrides DistJarChange and DistClassChange from the underlying DistChange with DistJarReport and DistClassReport instances """ for c in DistChange.collect_impl(self): if isinstance(c, DistJarChange): if c.is_change(): ...
[ "def", "collect_impl", "(", "self", ")", ":", "for", "c", "in", "DistChange", ".", "collect_impl", "(", "self", ")", ":", "if", "isinstance", "(", "c", ",", "DistJarChange", ")", ":", "if", "c", ".", "is_change", "(", ")", ":", "ln", "=", "DistJarRep...
42.944444
16.388889
def reduce_min(attrs, inputs, proto_obj): """Reduce the array along a given axis by minimum value""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'min', new_attrs, inputs
[ "def", "reduce_min", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'axes'", ":", "'axis'", "}", ")", "return", "'min'", ",", "new_attrs", ",", "inputs" ]
54
11
def FromJson(json): """ Convert a json object to a ContractParameter object Args: item (dict): The item to convert to a ContractParameter object Returns: ContractParameter """ type = ContractParameterType.FromString(json['type']) value ...
[ "def", "FromJson", "(", "json", ")", ":", "type", "=", "ContractParameterType", ".", "FromString", "(", "json", "[", "'type'", "]", ")", "value", "=", "json", "[", "'value'", "]", "param", "=", "ContractParameter", "(", "type", "=", "type", ",", "value",...
30.534884
22.395349
def _add_sub_elements_from_dict(parent, sub_dict): """ Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"e...
[ "def", "_add_sub_elements_from_dict", "(", "parent", ",", "sub_dict", ")", ":", "for", "key", ",", "value", "in", "sub_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "repeated_element", "in", "value", ...
33.484848
16.636364
def add_to_enum(self, clsdict): """ Compile XML mappings in addition to base add behavior. """ super(XmlMappedEnumMember, self).add_to_enum(clsdict) self.register_xml_mapping(clsdict)
[ "def", "add_to_enum", "(", "self", ",", "clsdict", ")", ":", "super", "(", "XmlMappedEnumMember", ",", "self", ")", ".", "add_to_enum", "(", "clsdict", ")", "self", ".", "register_xml_mapping", "(", "clsdict", ")" ]
36.333333
9
def align_unwrapped(sino): """Align an unwrapped phase array to zero-phase All operations are performed in-place. """ samples = [] if len(sino.shape) == 2: # 2D # take 1D samples at beginning and end of array samples.append(sino[:, 0]) samples.append(sino[:, 1]) ...
[ "def", "align_unwrapped", "(", "sino", ")", ":", "samples", "=", "[", "]", "if", "len", "(", "sino", ".", "shape", ")", "==", "2", ":", "# 2D", "# take 1D samples at beginning and end of array", "samples", ".", "append", "(", "sino", "[", ":", ",", "0", ...
28.9
14
def parse_template(input_filename, output_filename=''): """ Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file """ ...
[ "def", "parse_template", "(", "input_filename", ",", "output_filename", "=", "''", ")", ":", "data", "=", "load_input", "(", ")", "with", "open", "(", "input_filename", ",", "'rb'", ")", "as", "file", ":", "template", "=", "file", ".", "read", "(", ")", ...
40.159091
21.909091
def _check_satisfy(self, rand_box, gt_boxes): """ check if overlap with any gt box is larger than threshold """ l, t, r, b = rand_box num_gt = gt_boxes.shape[0] ls = np.ones(num_gt) * l ts = np.ones(num_gt) * t rs = np.ones(num_gt) * r bs = np.ones...
[ "def", "_check_satisfy", "(", "self", ",", "rand_box", ",", "gt_boxes", ")", ":", "l", ",", "t", ",", "r", ",", "b", "=", "rand_box", "num_gt", "=", "gt_boxes", ".", "shape", "[", "0", "]", "ls", "=", "np", ".", "ones", "(", "num_gt", ")", "*", ...
39.695652
12.086957
def prepare(self): """ All codes that create parameters should be put into 'setup' function. """ self.output_dim = 10 self.encoder = Chain(self.input_dim).stack(Dense(self.internal_layer_size, 'tanh')) self.decoder = Chain(self.internal_layer_size).stack(Dense(self.input_...
[ "def", "prepare", "(", "self", ")", ":", "self", ".", "output_dim", "=", "10", "self", ".", "encoder", "=", "Chain", "(", "self", ".", "input_dim", ")", ".", "stack", "(", "Dense", "(", "self", ".", "internal_layer_size", ",", "'tanh'", ")", ")", "se...
48.266667
27.333333
def _get_lib_modules(self, full): """Returns a list of the modules in the same folder as the one being wrapped for compilation as a linked library. :arg full: when True, all the code files in the source file's directory are considered as dependencies; otherwise only those explicitly n...
[ "def", "_get_lib_modules", "(", "self", ",", "full", ")", ":", "#The only complication with the whole process is that we need to get the list of", "#dependencies for the current module. For full lib, we compile *all* the files in", "#the directory, otherwise only those that are explicitly requir...
48.230769
24.115385
def GetValidHostsForCert(cert): """Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs. """ if 'subjectAltName' in cert: return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns'...
[ "def", "GetValidHostsForCert", "(", "cert", ")", ":", "if", "'subjectAltName'", "in", "cert", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "cert", "[", "'subjectAltName'", "]", "if", "x", "[", "0", "]", ".", "lower", "(", ")", "==", "'...
31.538462
16.769231
def validate_schema(sconf): """ Return True if config schema is correct. Parameters ---------- sconf : dict session configuration Returns ------- bool """ # verify session_name if 'session_name' not in sconf: raise exc.ConfigError('config requires "session_...
[ "def", "validate_schema", "(", "sconf", ")", ":", "# verify session_name", "if", "'session_name'", "not", "in", "sconf", ":", "raise", "exc", ".", "ConfigError", "(", "'config requires \"session_name\"'", ")", "if", "'windows'", "not", "in", "sconf", ":", "raise",...
23.612903
22.580645
def as_raw(self): """ Return a representation of this object that can be used with mongoengine Document.objects(__raw__=x) Example: >>> stream_id = StreamId(name='test', meta_data=((u'house', u'1'), (u'resident', u'1'))) >>> stream_id.as_raw() {'stream_id.meta_data': [(u...
[ "def", "as_raw", "(", "self", ")", ":", "return", "dict", "(", "(", "'stream_id.'", "+", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "as_dict", "(", ")", ".", "items", "(", ")", ")" ]
43.25
30.916667
def _get_video_id(self, url=None): """ Extract video id. It will try to avoid making an HTTP request if it can find the ID in the URL, but otherwise it will try to scrape it from the HTML document. Returns None in case it's unable to extract the ID at all. """ if ...
[ "def", "_get_video_id", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", ":", "html_data", "=", "self", ".", "http", ".", "request", "(", "\"get\"", ",", "url", ")", ".", "text", "else", ":", "html_data", "=", "self", ".", "get_urldata", ...
42.696629
20.58427
def get_event_details(self, group_url, event_id): ''' a method to retrieve details for an event :param group_url: string with meetup urlname for host group :param event_id: integer with meetup id for event :return: dictionary with list of event details inside [json] key ...
[ "def", "get_event_details", "(", "self", ",", "group_url", ",", "event_id", ")", ":", "# https://www.meetup.com/meetup_api/docs/:urlname/events/:id/#get\r", "title", "=", "'%s.get_event_details'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs\r", "input...
34.846154
26.589744
def authenticated(f): """Access only with a valid session.""" @functools.wraps(f) def wrapper(request, *args, **kwargs): if d1_common.const.SUBJECT_AUTHENTICATED not in request.all_subjects_set: raise d1_common.types.exceptions.NotAuthorized( 0, 'Access a...
[ "def", "authenticated", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "d1_common", ".", "const", ".", "SUBJECT_AUTHENTICATED", "not", "i...
38.5
24.4375
def get_settings(self): """ Gets the interconnect settings for a logical interconnect group. Returns: dict: Interconnect Settings. """ uri = "{}/settings".format(self.data["uri"]) return self._helper.do_get(uri)
[ "def", "get_settings", "(", "self", ")", ":", "uri", "=", "\"{}/settings\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ")", "return", "self", ".", "_helper", ".", "do_get", "(", "uri", ")" ]
29.333333
14
def create(name, **params): ''' Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create lama salt '*' serverden...
[ "def", "create", "(", "name", ",", "*", "*", "params", ")", ":", "log", ".", "debug", "(", "'Server Density params: %s'", ",", "params", ")", "params", "=", "_clean_salt_variables", "(", "params", ")", "params", "[", "'name'", "]", "=", "name", "api_respon...
33.771429
25.028571
def MessageSetItemEncoder(field_number): """Encoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ start_bytes = b"".join([ TagBytes(...
[ "def", "MessageSetItemEncoder", "(", "field_number", ")", ":", "start_bytes", "=", "b\"\"", ".", "join", "(", "[", "TagBytes", "(", "1", ",", "wire_format", ".", "WIRETYPE_START_GROUP", ")", ",", "TagBytes", "(", "2", ",", "wire_format", ".", "WIRETYPE_VARINT"...
29.192308
14.384615
def generate_html_documentation(self): """generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can cho...
[ "def", "generate_html_documentation", "(", "self", ")", ":", "methods", "=", "{", "}", "for", "method_name", "in", "self", ".", "system_listMethods", "(", ")", ":", "if", "method_name", "in", "self", ".", "funcs", ":", "method", "=", "self", ".", "funcs", ...
43.44
18.02
def read(self, data, offset=0): """ Read data structure and return (nested) named tuple(s). """ if isinstance(data, Buffer): return data.read(self) try: args = list(self._struct.unpack_from(data, offset)) except TypeError as error: # Working around st...
[ "def", "read", "(", "self", ",", "data", ",", "offset", "=", "0", ")", ":", "if", "isinstance", "(", "data", ",", "Buffer", ")", ":", "return", "data", ".", "read", "(", "self", ")", "try", ":", "args", "=", "list", "(", "self", ".", "_struct", ...
40
15.615385
def do_file_update_metadata(client, args): """Update file metadata""" client.update_file_metadata(args.uri, filename=args.filename, description=args.description, mtime=args.mtime, privacy=args.privacy) return True
[ "def", "do_file_update_metadata", "(", "client", ",", "args", ")", ":", "client", ".", "update_file_metadata", "(", "args", ".", "uri", ",", "filename", "=", "args", ".", "filename", ",", "description", "=", "args", ".", "description", ",", "mtime", "=", "...
47.333333
17.333333
def needs_quotes(s): """Checks whether a string is a dot language ID. It will check whether the string is solely composed by the characters allowed in an ID or not. If the string is one of the reserved keywords it will need quotes too but the user will need to add them manually. """ # If...
[ "def", "needs_quotes", "(", "s", ")", ":", "# If the name is a reserved keyword it will need quotes but pydot", "# can't tell when it's being used as a keyword or when it's simply", "# a name. Hence the user needs to supply the quotes when an element", "# would use a reserved keyword as name. This...
44.307692
21.807692
def cheb_range_simplifier(low, high, text=False): ''' >>> low, high = 0.0023046250851646434, 4.7088985707840125 >>> cheb_range_simplifier(low, high, text=True) 'chebval(0.42493574399544564724*(x + -2.3556015979345885647), coeffs)' ''' constant = 0.5*(-low-high) factor = 2.0/(high-low) if...
[ "def", "cheb_range_simplifier", "(", "low", ",", "high", ",", "text", "=", "False", ")", ":", "constant", "=", "0.5", "*", "(", "-", "low", "-", "high", ")", "factor", "=", "2.0", "/", "(", "high", "-", "low", ")", "if", "text", ":", "return", "'...
37.818182
21.454545
def resample_single_nifti(input_nifti): """ Resample a gantry tilted image in place """ # read the input image input_image = nibabel.load(input_nifti) output_image = resample_nifti_images([input_image]) output_image.to_filename(input_nifti)
[ "def", "resample_single_nifti", "(", "input_nifti", ")", ":", "# read the input image", "input_image", "=", "nibabel", ".", "load", "(", "input_nifti", ")", "output_image", "=", "resample_nifti_images", "(", "[", "input_image", "]", ")", "output_image", ".", "to_fil...
32.625
4.625
def download_data(request_list, redownload=False, max_threads=None): """ Download all requested data or read data from disk, if already downloaded and available and redownload is not required. :param request_list: list of DownloadRequests :type request_list: list of DownloadRequests :param redownlo...
[ "def", "download_data", "(", "request_list", ",", "redownload", "=", "False", ",", "max_threads", "=", "None", ")", ":", "_check_if_must_download", "(", "request_list", ",", "redownload", ")", "LOGGER", ".", "debug", "(", "\"Using max_threads=%s for %s requests\"", ...
55.318182
29.045455
def m2m_changed(sender, instance, action, reverse, model, pk_set, using, **kwargs): """https://docs.djangoproject.com/es/1.10/ref/signals/#m2m-changed""" try: with transaction.atomic(): if not should_audit(instance): return False if action not in ("post_add", "po...
[ "def", "m2m_changed", "(", "sender", ",", "instance", ",", "action", ",", "reverse", ",", "model", ",", "pk_set", ",", "using", ",", "*", "*", "kwargs", ")", ":", "try", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "if", "not", "should_a...
42.262295
21.065574
def tan(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the tan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the tan function. ''' return cls._unary_op(x, tf.tan, tf.float32)
[ "def", "tan", "(", "cls", ",", "x", ":", "'TensorFluent'", ")", "->", "'TensorFluent'", ":", "return", "cls", ".", "_unary_op", "(", "x", ",", "tf", ".", "tan", ",", "tf", ".", "float32", ")" ]
28.1
21.7
def research_organism(soup): "Find the research-organism from the set of kwd-group tags" if not raw_parser.research_organism_keywords(soup): return [] return list(map(node_text, raw_parser.research_organism_keywords(soup)))
[ "def", "research_organism", "(", "soup", ")", ":", "if", "not", "raw_parser", ".", "research_organism_keywords", "(", "soup", ")", ":", "return", "[", "]", "return", "list", "(", "map", "(", "node_text", ",", "raw_parser", ".", "research_organism_keywords", "(...
47.8
21.8
def _heightmap_cdata(array: np.ndarray) -> ffi.CData: """Return a new TCOD_heightmap_t instance using an array. Formatting is verified during this function. """ if array.flags["F_CONTIGUOUS"]: array = array.transpose() if not array.flags["C_CONTIGUOUS"]: raise ValueError("array must...
[ "def", "_heightmap_cdata", "(", "array", ":", "np", ".", "ndarray", ")", "->", "ffi", ".", "CData", ":", "if", "array", ".", "flags", "[", "\"F_CONTIGUOUS\"", "]", ":", "array", "=", "array", ".", "transpose", "(", ")", "if", "not", "array", ".", "fl...
42.714286
13.428571
def select_port(default_port=20128): """Find and return a non used port""" import socket while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # sock.setsockopt(so...
[ "def", "select_port", "(", "default_port", "=", "20128", ")", ":", "import", "socket", "while", "True", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ",", "socket", ".", "IPPROTO_...
34.055556
16.722222
async def get_session_data(self): """Get Tautulli sessions.""" cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(...
[ "async", "def", "get_session_data", "(", "self", ")", ":", "cmd", "=", "'get_activity'", "url", "=", "self", ".", "base_url", "+", "cmd", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", "self", ".", "_loop", ")...
41.1875
19.8125
def check_photometry_categorize(x, y, levels, tags=None): '''Put every point in its category. levels must be sorted.''' x = numpy.asarray(x) y = numpy.asarray(y) ys = y.copy() ys.sort() # Mean of the upper half m = ys[len(ys) // 2:].mean() y /= m m = 1.0 s = ys[len(ys) // 2:...
[ "def", "check_photometry_categorize", "(", "x", ",", "y", ",", "levels", ",", "tags", "=", "None", ")", ":", "x", "=", "numpy", ".", "asarray", "(", "x", ")", "y", "=", "numpy", ".", "asarray", "(", "y", ")", "ys", "=", "y", ".", "copy", "(", "...
22.129032
19.806452
def get_last_origin(tp): """Get the last base of (multiply) subscripted type. Supports generic types, Union, Callable, and Tuple. Returns None for unsupported types. Examples:: get_last_origin(int) == None get_last_origin(ClassVar[int]) == None get_last_origin(Generic[T]) == Generic...
[ "def", "get_last_origin", "(", "tp", ")", ":", "if", "NEW_TYPING", ":", "raise", "ValueError", "(", "'This function is only supported in Python 3.6,'", "' use get_origin instead'", ")", "sentinel", "=", "object", "(", ")", "origin", "=", "getattr", "(", "tp", ",", ...
36.318182
16.636364
def GetHostNumCpuCores(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostNumCpuCores(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
[ "def", "GetHostNumCpuCores", "(", "self", ")", ":", "counter", "=", "c_uint", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_GetHostNumCpuCores", "(", "self", ".", "handle", ".", "value", ",", "byref", "(", "counter", ")", ")", "if", "ret", "!=", "...
45.5
22.166667
def getBinaries(self): ''' Return a dictionary of binaries to compile: {"dirname":"exename"}, this is used when automatically generating CMakeLists Note that currently modules may define only a single executable binary or library to be built by the automatic build system, by...
[ "def", "getBinaries", "(", "self", ")", ":", "# the module.json syntax is a subset of the package.json syntax: a", "# single string that defines the source directory to use to build an", "# executable with the same name as the component. This may be extended", "# to include the rest of the npm syn...
56.384615
31.461538
def filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False): """Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" u...
[ "def", "filter_exclude_dicts", "(", "filter_dict", "=", "None", ",", "exclude_dict", "=", "None", ",", "name", "=", "'acctno'", ",", "values", "=", "[", "]", ",", "swap", "=", "False", ")", ":", "filter_dict", "=", "filter_dict", "or", "{", "}", "exclude...
40.392857
24.035714
def is_balanced(self): """ Returns True if the (sub)tree is balanced The tree is balanced if the heights of both subtrees differ at most by 1 """ left_height = self.left.height() if self.left else 0 right_height = self.right.height() if self.right else 0 if abs(left_he...
[ "def", "is_balanced", "(", "self", ")", ":", "left_height", "=", "self", ".", "left", ".", "height", "(", ")", "if", "self", ".", "left", "else", "0", "right_height", "=", "self", ".", "right", ".", "height", "(", ")", "if", "self", ".", "right", "...
32.230769
23.153846
def _build_url(self, host, handler): """ Build a url for our request based on the host, handler and use_http property """ scheme = 'https' if self.use_https else 'http' return '%s://%s/%s' % (scheme, host, handler)
[ "def", "_build_url", "(", "self", ",", "host", ",", "handler", ")", ":", "scheme", "=", "'https'", "if", "self", ".", "use_https", "else", "'http'", "return", "'%s://%s/%s'", "%", "(", "scheme", ",", "host", ",", "handler", ")" ]
36.571429
12.857143
def plot_account(self, row, per_capita=False, sector=None, file_name=False, file_dpi=600, population=None, **kwargs): """ Plots D_pba, D_cba, D_imp and D_exp for the specified row (account) Plot either the total country accounts or for a specific sector, ...
[ "def", "plot_account", "(", "self", ",", "row", ",", "per_capita", "=", "False", ",", "sector", "=", "None", ",", "file_name", "=", "False", ",", "file_dpi", "=", "600", ",", "population", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# necessary if...
37.812903
18.354839
def serialize_text(out, text): """This method is used to append content of the `text` argument to the `out` argument. Depending on how many lines in the text, a padding can be added to all lines except the first one. Concatenation result is appended to the `out` argument. """ padding =...
[ "def", "serialize_text", "(", "out", ",", "text", ")", ":", "padding", "=", "len", "(", "out", ")", "# we need to add padding to all lines", "# except the first one", "add_padding", "=", "padding_adder", "(", "padding", ")", "text", "=", "add_padding", "(", "text"...
29.352941
15.882353
def OpenFileEntry(cls, path_spec_object, resolver_context=None): """Opens a file entry object defined by path specification. Args: path_spec_object (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built in context which is n...
[ "def", "OpenFileEntry", "(", "cls", ",", "path_spec_object", ",", "resolver_context", "=", "None", ")", ":", "file_system", "=", "cls", ".", "OpenFileSystem", "(", "path_spec_object", ",", "resolver_context", "=", "resolver_context", ")", "if", "resolver_context", ...
34.76
23.24
def _fill_in_cainfo(self): """Fill in the path of the PEM file containing the CA certificate. The priority is: 1. user provided path, 2. path to the cacert.pem bundle provided by certifi (if installed), 3. let pycurl use the system path where libcurl's cacert bundle is assumed to be sto...
[ "def", "_fill_in_cainfo", "(", "self", ")", ":", "if", "self", ".", "cainfo", ":", "cainfo", "=", "self", ".", "cainfo", "else", ":", "try", ":", "cainfo", "=", "certifi", ".", "where", "(", ")", "except", "AttributeError", ":", "cainfo", "=", "None", ...
37.294118
16.882353
def continue_to_install(self): """Continue to install ? """ if (self.count_uni > 0 or self.count_upg > 0 or "--download-only" in self.flag or "--rebuild" in self.flag): if self.master_packages and self.msg.answer() in ["y", "Y"]: installs, upgraded = s...
[ "def", "continue_to_install", "(", "self", ")", ":", "if", "(", "self", ".", "count_uni", ">", "0", "or", "self", ".", "count_upg", ">", "0", "or", "\"--download-only\"", "in", "self", ".", "flag", "or", "\"--rebuild\"", "in", "self", ".", "flag", ")", ...
46.5
11.583333
def tuple(self): """ Tuple conversion to (value, dimensions), e.g.: (123, {dimension_1: "foo", dimension_2: "bar"}) """ return (self.value, {dv.id: dv.value for dv in self.dimensionvalues})
[ "def", "tuple", "(", "self", ")", ":", "return", "(", "self", ".", "value", ",", "{", "dv", ".", "id", ":", "dv", ".", "value", "for", "dv", "in", "self", ".", "dimensionvalues", "}", ")" ]
43.6
15.4
def get_all_rules(self, id_env): """Save an environment rule :param id_env: Environment id :return: Estrutura: :: { 'rules': [{'id': < id >, 'environment': < Environment Object >, 'content': < content >, 'name': < name >, 'c...
[ "def", "get_all_rules", "(", "self", ",", "id_env", ")", ":", "url", "=", "'rule/all/'", "+", "str", "(", "id_env", ")", "code", ",", "xml", "=", "self", ".", "submit", "(", "None", ",", "'GET'", ",", "url", ")", "return", "self", ".", "response", ...
32.458333
19.958333
def del_arg(self, name: str) -> None: """Delete all arguments with the given then.""" for arg in reversed(self.arguments): if arg.name.strip(WS) == name.strip(WS): del arg[:]
[ "def", "del_arg", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "for", "arg", "in", "reversed", "(", "self", ".", "arguments", ")", ":", "if", "arg", ".", "name", ".", "strip", "(", "WS", ")", "==", "name", ".", "strip", "(", "W...
42.8
6.6
def component(self, extra_params=None): """ The Component currently assigned to the Ticket """ if self.get('component_id', None): components = self.space.components(id=self['component_id'], extra_params=extra_params) if components: return component...
[ "def", "component", "(", "self", ",", "extra_params", "=", "None", ")", ":", "if", "self", ".", "get", "(", "'component_id'", ",", "None", ")", ":", "components", "=", "self", ".", "space", ".", "components", "(", "id", "=", "self", "[", "'component_id...
39.625
11.625
def collapse_nodes(graph, survivor_mapping: Mapping[BaseEntity, Set[BaseEntity]]) -> None: """Collapse all nodes in values to the key nodes, in place. :param pybel.BELGraph graph: A BEL graph :param survivor_mapping: A dictionary with survivors as their keys, and iterables of the corresponding victims as ...
[ "def", "collapse_nodes", "(", "graph", ",", "survivor_mapping", ":", "Mapping", "[", "BaseEntity", ",", "Set", "[", "BaseEntity", "]", "]", ")", "->", "None", ":", "inconsistencies", "=", "surviors_are_inconsistent", "(", "survivor_mapping", ")", "if", "inconsis...
43
26.875
def computePerturbedExpectation(self, u_n, A_n, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False): """Compute the expectation of an observable of phase space function A(x) for a single new state. Parameters ---------- u_n : np.ndarray, float,...
[ "def", "computePerturbedExpectation", "(", "self", ",", "u_n", ",", "A_n", ",", "compute_uncertainty", "=", "True", ",", "uncertainty_method", "=", "None", ",", "warning_cutoff", "=", "1.0e-10", ",", "return_theta", "=", "False", ")", ":", "if", "len", "(", ...
41.292929
26.777778
def set_pkg_chk_sum(self, doc, chk_sum): """Sets the package check sum, if not already set. chk_sum - A string Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_chk_...
[ "def", "set_pkg_chk_sum", "(", "self", ",", "doc", ",", "chk_sum", ")", ":", "self", ".", "assert_package_exists", "(", ")", "if", "not", "self", ".", "package_chk_sum_set", ":", "self", ".", "package_chk_sum_set", "=", "True", "doc", ".", "package", ".", ...
41.916667
10.333333
def get_configure(self, repo=None, name=None, groups=None, main_cfg=False): """ Get the vent.template settings for a given tool by looking at the plugin_manifest """ constraints = locals() ...
[ "def", "get_configure", "(", "self", ",", "repo", "=", "None", ",", "name", "=", "None", ",", "groups", "=", "None", ",", "main_cfg", "=", "False", ")", ":", "constraints", "=", "locals", "(", ")", "del", "constraints", "[", "'main_cfg'", "]", "status"...
42.0625
14.229167
def get_default_subject_guide(campus='seattle'): """ Returns a default SubjectGuide model for the passed campus: seattle, bothell, tacoma """ url = "{}/{}/{}".format(subject_guide_url_prefix, 'defaultGuide', campus) headers = {'Accept': 'application/json'} response = SubjectGuide_DAO()....
[ "def", "get_default_subject_guide", "(", "campus", "=", "'seattle'", ")", ":", "url", "=", "\"{}/{}/{}\"", ".", "format", "(", "subject_guide_url_prefix", ",", "'defaultGuide'", ",", "campus", ")", "headers", "=", "{", "'Accept'", ":", "'application/json'", "}", ...
34
17.333333
def _set_time(self, time): """ Set time in both class and hdf5 file """ if len(self.time) == 0 : self.time = np.array(time) if self.h5 is not None: self.h5.create_dataset('time', self.time.shape, dtype=self.time.dtype, data=self.time, compression="gzip", s...
[ "def", "_set_time", "(", "self", ",", "time", ")", ":", "if", "len", "(", "self", ".", "time", ")", "==", "0", ":", "self", ".", "time", "=", "np", ".", "array", "(", "time", ")", "if", "self", ".", "h5", "is", "not", "None", ":", "self", "."...
50.3
23.6