text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def check_user(user): ''' Check user and assign process uid/gid. ''' if salt.utils.platform.is_windows(): return True if user == salt.utils.user.get_user(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: ...
[ "def", "check_user", "(", "user", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "return", "True", "if", "user", "==", "salt", ".", "utils", ".", "user", ".", "get_user", "(", ")", ":", "return", "True", "i...
34.319149
18.489362
def connect(self, (host, port)): ''' Connect using a host,port tuple ''' super(GeventTransport, self).connect((host, port), klass=socket.socket)
[ "def", "connect", "(", "self", ",", "(", "host", ",", "port", ")", ")", ":", "super", "(", "GeventTransport", ",", "self", ")", ".", "connect", "(", "(", "host", ",", "port", ")", ",", "klass", "=", "socket", ".", "socket", ")" ]
34.4
21.2
def is_anion_cation_bond(valences, ii, jj): """ Checks if two given sites are an anion and a cation. :param valences: list of site valences :param ii: index of a site :param jj: index of another site :return: True if one site is an anion and the other is a cation (from the valences) """ ...
[ "def", "is_anion_cation_bond", "(", "valences", ",", "ii", ",", "jj", ")", ":", "if", "valences", "==", "'undefined'", ":", "return", "True", "if", "valences", "[", "ii", "]", "==", "0", "or", "valences", "[", "jj", "]", "==", "0", ":", "return", "Tr...
38.769231
13.846154
def fit_offset_and_rotation(coords0, coords1): """Fit a rotation and a traslation between two sets points. Fit a rotation matrix and a traslation bewtween two matched sets consisting of M N-dimensional points Parameters ---------- coords0 : (M, N) array_like coords1 : (M, N) array_lke ...
[ "def", "fit_offset_and_rotation", "(", "coords0", ",", "coords1", ")", ":", "coords0", "=", "numpy", ".", "asarray", "(", "coords0", ")", "coords1", "=", "numpy", ".", "asarray", "(", "coords1", ")", "cp", "=", "coords0", ".", "mean", "(", "axis", "=", ...
22.618182
21.418182
async def cluster_delslots(self, *slots): """ Set hash slots as unbound in the cluster. It determines by it self what node the slot is in and sends it there Returns a list of the results for each processed slot. """ cluster_nodes = self._nodes_slots_to_slots_nodes(await ...
[ "async", "def", "cluster_delslots", "(", "self", ",", "*", "slots", ")", ":", "cluster_nodes", "=", "self", ".", "_nodes_slots_to_slots_nodes", "(", "await", "self", ".", "cluster_nodes", "(", ")", ")", "res", "=", "list", "(", ")", "for", "slot", "in", ...
41.916667
22.75
def upgrade(name=None, pkgs=None, refresh=True, skip_verify=False, normalize=True, minimal=False, obsoletes=True, **kwargs): ''' Run a full system upgrade (a ``yum upgrade`` or ``dnf upgrade``), or upgrade specified packages...
[ "def", "upgrade", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "refresh", "=", "True", ",", "skip_verify", "=", "False", ",", "normalize", "=", "True", ",", "minimal", "=", "False", ",", "obsoletes", "=", "True", ",", "*", "*", "kwargs", ...
32.537313
25.502488
def download_article_from_ids(**id_dict): """Download an article in XML format from Elsevier matching the set of ids. Parameters ---------- <id_type> : str You can enter any combination of eid, doi, pmid, and/or pii. Ids will be checked in that order, until either content has been found...
[ "def", "download_article_from_ids", "(", "*", "*", "id_dict", ")", ":", "valid_id_types", "=", "[", "'eid'", ",", "'doi'", ",", "'pmid'", ",", "'pii'", "]", "assert", "all", "(", "[", "k", "in", "valid_id_types", "for", "k", "in", "id_dict", ".", "keys",...
37.15625
20.40625
def _prune(self): """Shorten hypotheses to the best k ones.""" self.hypotheses = sorted(self.hypotheses, key=lambda e: e['probability'], reverse=True)[:self.k]
[ "def", "_prune", "(", "self", ")", ":", "self", ".", "hypotheses", "=", "sorted", "(", "self", ".", "hypotheses", ",", "key", "=", "lambda", "e", ":", "e", "[", "'probability'", "]", ",", "reverse", "=", "True", ")", "[", ":", "self", ".", "k", "...
47.4
14.2
def do_for(parser, token): ''' {% for a, b, c in iterable %} {% endfor %} We create the structure: with ContextWrapper(context) as context: for a, b, c in iterable: context.update(a=a, b=b, c=c) ... If there is a {% empty %} clause, we create: if iterable...
[ "def", "do_for", "(", "parser", ",", "token", ")", ":", "code", "=", "ast", ".", "parse", "(", "'for %s: pass'", "%", "token", ",", "mode", "=", "'exec'", ")", "# Grab the ast.For node", "loop", "=", "code", ".", "body", "[", "0", "]", "# Wrap its source...
22.603175
21.238095
def _init_module_cache(): """ Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done. """ # While there are not loaded modules, load these ones if len(FieldTranslation._modules) < len...
[ "def", "_init_module_cache", "(", ")", ":", "# While there are not loaded modules, load these ones", "if", "len", "(", "FieldTranslation", ".", "_modules", ")", "<", "len", "(", "FieldTranslation", ".", "_model_module_paths", ")", ":", "for", "module_path", "in", "Fie...
43.333333
27
def menu(self, prompt, choices): """Presents a selection menu and returns the user's choice. Args: prompt (str): Text to ask the user what to select. choices (Sequence[str]): Values for the user to select from. Returns: The value selected by the user, or ``N...
[ "def", "menu", "(", "self", ",", "prompt", ",", "choices", ")", ":", "menu", "=", "[", "prompt", "]", "+", "[", "\"{0}. {1}\"", ".", "format", "(", "*", "choice", ")", "for", "choice", "in", "enumerate", "(", "choices", ",", "start", "=", "1", ")",...
33
23.083333
def __assembleURL(self, url, groupId): """private function that assembles the URL for the community.Group class""" from ..packages.six.moves.urllib_parse import urlparse parsed = urlparse(url) communityURL = "%s://%s%s/sharing/rest/community/groups/%s" % (parsed.scheme, parsed.ne...
[ "def", "__assembleURL", "(", "self", ",", "url", ",", "groupId", ")", ":", "from", ".", ".", "packages", ".", "six", ".", "moves", ".", "urllib_parse", "import", "urlparse", "parsed", "=", "urlparse", "(", "url", ")", "communityURL", "=", "\"%s://%s%s/shar...
60.666667
25.111111
def get_coord_box(centre_x, centre_y, distance): """Get the square boundary coordinates for a given centre and distance""" """Todo: return coordinates inside a circle, rather than a square""" return { 'top_left': (centre_x - distance, centre_y + distance), 'top_right': (centre_x + distance, ...
[ "def", "get_coord_box", "(", "centre_x", ",", "centre_y", ",", "distance", ")", ":", "\"\"\"Todo: return coordinates inside a circle, rather than a square\"\"\"", "return", "{", "'top_left'", ":", "(", "centre_x", "-", "distance", ",", "centre_y", "+", "distance", ")", ...
52.666667
19
async def storage(dev: Device): """Print storage information.""" storages = await dev.get_storage_list() for storage in storages: click.echo(storage)
[ "async", "def", "storage", "(", "dev", ":", "Device", ")", ":", "storages", "=", "await", "dev", ".", "get_storage_list", "(", ")", "for", "storage", "in", "storages", ":", "click", ".", "echo", "(", "storage", ")" ]
33
7.4
def series_with_permutation(self, other): """Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: The composite permutation circuit (could also be the identity circuit for n channels) "...
[ "def", "series_with_permutation", "(", "self", ",", "other", ")", ":", "combined_permutation", "=", "tuple", "(", "[", "self", ".", "permutation", "[", "p", "]", "for", "p", "in", "other", ".", "permutation", "]", ")", "return", "CPermutation", ".", "creat...
37.846154
18.384615
def expand_all(self): """ Expand all positions; works only if the underlying tree allows it. """ if implementsCollapseAPI(self._tree): self._tree.expand_all() self._walker.clear_cache() self.refresh()
[ "def", "expand_all", "(", "self", ")", ":", "if", "implementsCollapseAPI", "(", "self", ".", "_tree", ")", ":", "self", ".", "_tree", ".", "expand_all", "(", ")", "self", ".", "_walker", ".", "clear_cache", "(", ")", "self", ".", "refresh", "(", ")" ]
32.625
9.875
def to_ped(self): """ Return a generator with the info in ped format. Yields: An iterator with the family info in ped format """ ped_header = [ '#FamilyID', 'IndividualID', 'PaternalID', 'MaternalID', ...
[ "def", "to_ped", "(", "self", ")", ":", "ped_header", "=", "[", "'#FamilyID'", ",", "'IndividualID'", ",", "'PaternalID'", ",", "'MaternalID'", ",", "'Sex'", ",", "'Phenotype'", ",", "]", "extra_headers", "=", "[", "'InheritanceModel'", ",", "'Proband'", ",", ...
31.690909
18.236364
def severity(self, severity): """Sets the severity of this Message. Message severity # noqa: E501 :param severity: The severity of this Message. # noqa: E501 :type: str """ if severity is None: raise ValueError("Invalid value for `severity`, must not be `N...
[ "def", "severity", "(", "self", ",", "severity", ")", ":", "if", "severity", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `severity`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"MARKETING\"", ",", "\"INFO\"", ","...
36.722222
21.611111
def parse_authorization_header(authorization_header): """Parse an OAuth authorization header into a list of 2-tuples""" auth_scheme = 'OAuth '.lower() if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme): items = parse_http_list(authorization_header[len(auth_scheme):]) ...
[ "def", "parse_authorization_header", "(", "authorization_header", ")", ":", "auth_scheme", "=", "'OAuth '", ".", "lower", "(", ")", "if", "authorization_header", "[", ":", "len", "(", "auth_scheme", ")", "]", ".", "lower", "(", ")", ".", "startswith", "(", "...
48.4
17.1
def get_nt_challenge_response(self, lm_challenge_response, server_certificate_hash): """ [MS-NLMP] v28.0 2016-07-14 3.3.1 - NTLM v1 Authentication 3.3.2 - NTLM v2 Authentication This method returns the NtChallengeResponse key based on the ntlm_compatibility chosen and t...
[ "def", "get_nt_challenge_response", "(", "self", ",", "lm_challenge_response", ",", "server_certificate_hash", ")", ":", "if", "self", ".", "_negotiate_flags", "&", "NegotiateFlags", ".", "NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY", "and", "self", ".", "_ntlm_compatibility...
66.355932
44.389831
def _make_field_info(self, field_name, field): """ Create the information that the template needs to render a form field for this field. """ supported_field_types = ( (Integer, 'integer'), (Float, 'float'), (Boolean, 'boolean'), (String, 's...
[ "def", "_make_field_info", "(", "self", ",", "field_name", ",", "field", ")", ":", "supported_field_types", "=", "(", "(", "Integer", ",", "'integer'", ")", ",", "(", "Float", ",", "'float'", ")", ",", "(", "Boolean", ",", "'boolean'", ")", ",", "(", "...
54.640777
25.048544
def set_active_current(self, axis, amp): """ This method sets only the 'active' current, i.e., the current for an axis' movement. Smoothie driver automatically resets the current for pipette axis to a low current (dwelling current) after each move """ self._smoothie_drive...
[ "def", "set_active_current", "(", "self", ",", "axis", ",", "amp", ")", ":", "self", ".", "_smoothie_driver", ".", "set_active_current", "(", "{", "axis", ".", "name", ":", "amp", "}", ")" ]
50.285714
18.571429
def month(abbr=False, numerical=False): """Return a random (abbreviated if `abbr`) month name or month number if `numerical`. """ if numerical: return random.randint(1, 12) else: if abbr: return random.choice(MONTHS_ABBR) else: return random.choice(MON...
[ "def", "month", "(", "abbr", "=", "False", ",", "numerical", "=", "False", ")", ":", "if", "numerical", ":", "return", "random", ".", "randint", "(", "1", ",", "12", ")", "else", ":", "if", "abbr", ":", "return", "random", ".", "choice", "(", "MONT...
28.545455
12.636364
def simple_request(self, request, *args, **kwargs): """Create and send a request to the server. This method implements a very small subset of the options possible to send an request. It is provided as a shortcut to sending a simple request. Parameters ---------- ...
[ "def", "simple_request", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO (NM 2016-11-03) This method should really live on the lower level", "# katcp_client in client.py, is generally useful IMHO", "use_mid", "=", "kwargs", ".", "ge...
34.76087
23.152174
def get_manifest(self, metadata): """ Get latest manifest as specified in repomd.xml :type metadata: dict :param metadata: dictionary representation of repomd.xml """ manifest_path = "{0}/{1}".format(self.url, metadata['location']) req = requests.get(manifest_pat...
[ "def", "get_manifest", "(", "self", ",", "metadata", ")", ":", "manifest_path", "=", "\"{0}/{1}\"", ".", "format", "(", "self", ".", "url", ",", "metadata", "[", "'location'", "]", ")", "req", "=", "requests", ".", "get", "(", "manifest_path", ",", "stre...
38.842105
17.157895
def distances_indices_groups(self, points, delta=None, delta_factor=0.05, sign=False): """ Computes the distances from the plane to each of the points. Positive distances are on the side of the normal of the plane while negative distances are on the other side. Indices sorting the points from cl...
[ "def", "distances_indices_groups", "(", "self", ",", "points", ",", "delta", "=", "None", ",", "delta_factor", "=", "0.05", ",", "sign", "=", "False", ")", ":", "distances", ",", "indices", "=", "self", ".", "distances_indices_sorted", "(", "points", "=", ...
77
41.857143
def updateSynapses(self, segment, synapses, delta): """Update a set of synapses of the given segment, delta can be permanenceInc, or permanenceDec. retval: True if synapse reached 0 """ reached0 = False if delta > 0: for synapse in synapses: segment[synapse][2] = newValue = ...
[ "def", "updateSynapses", "(", "self", ",", "segment", ",", "synapses", ",", "delta", ")", ":", "reached0", "=", "False", "if", "delta", ">", "0", ":", "for", "synapse", "in", "synapses", ":", "segment", "[", "synapse", "]", "[", "2", "]", "=", "newVa...
28.074074
20.962963
def copy(srcpath, dstpath, overwrite=True): """Copies the file or directory at `srcpath` to `dstpath`. Returns True if successful, False otherwise.""" # Handle bail conditions. if not op.exists(srcpath): return False if not overwrite: if op.isfile(dstpath): return False ...
[ "def", "copy", "(", "srcpath", ",", "dstpath", ",", "overwrite", "=", "True", ")", ":", "# Handle bail conditions.", "if", "not", "op", ".", "exists", "(", "srcpath", ")", ":", "return", "False", "if", "not", "overwrite", ":", "if", "op", ".", "isfile", ...
35.135135
13.918919
def mk_set_headers(self, data, columns): """ figure out sizes and create header fmt """ columns = tuple(columns) lens = [] for key in columns: value_len = max(len(str(each.get(key, ''))) for each in data) # account for header lengths lens.append(max(v...
[ "def", "mk_set_headers", "(", "self", ",", "data", ",", "columns", ")", ":", "columns", "=", "tuple", "(", "columns", ")", "lens", "=", "[", "]", "for", "key", "in", "columns", ":", "value_len", "=", "max", "(", "len", "(", "str", "(", "each", ".",...
33.166667
17.666667
def _shutdownBatchSystem(self): """ Shuts down current batch system if it has been created. """ assert self._batchSystem is not None startTime = time.time() logger.debug('Shutting down batch system ...') self._batchSystem.shutdown() logger.debug('... fini...
[ "def", "_shutdownBatchSystem", "(", "self", ")", ":", "assert", "self", ".", "_batchSystem", "is", "not", "None", "startTime", "=", "time", ".", "time", "(", ")", "logger", ".", "debug", "(", "'Shutting down batch system ...'", ")", "self", ".", "_batchSystem"...
37.363636
13.909091
def write(self, file): """Write YAML campaign template to the given open file """ render( self.template, file, benchmarks=self.benchmarks, hostname=socket.gethostname(), )
[ "def", "write", "(", "self", ",", "file", ")", ":", "render", "(", "self", ".", "template", ",", "file", ",", "benchmarks", "=", "self", ".", "benchmarks", ",", "hostname", "=", "socket", ".", "gethostname", "(", ")", ",", ")" ]
27
12.666667
def query(**kwargs): """Queries for work items based on their criteria. Args: queue_name: Optional queue name to restrict to. build_id: Optional build ID to restrict to. release_id: Optional release ID to restrict to. run_id: Optional run ID to restrict to. count: How ma...
[ "def", "query", "(", "*", "*", "kwargs", ")", ":", "count", "=", "kwargs", ".", "get", "(", "'count'", ",", "None", ")", "task_list", "=", "_query", "(", "*", "*", "kwargs", ")", "task_dict_list", "=", "[", "_task_to_dict", "(", "task", ")", "for", ...
34.642857
20.464286
def remove(self, msg, callback): """Remove a callback from the callback list. msg: Message template callback: Callback method to remove. If callback is None, all callbacks for the message template are removed. """ if callback is None: self._dict.pop(...
[ "def", "remove", "(", "self", ",", "msg", ",", "callback", ")", ":", "if", "callback", "is", "None", ":", "self", ".", "_dict", ".", "pop", "(", "msg", ",", "None", ")", "else", ":", "cb", "=", "self", ".", "_dict", ".", "get", "(", "msg", ",",...
32.130435
16.347826
def scaffold_coords(rings): """ assign scaffold coordinate and angle {node: (coords, angle)} """ rs = deque(sorted(rings, key=len, reverse=True)) base = rs.popleft() first = base[0] coords = {first: [0, 0, 0, 1]} attach_spiro(coords, base, first) # display(coords) while rs: ...
[ "def", "scaffold_coords", "(", "rings", ")", ":", "rs", "=", "deque", "(", "sorted", "(", "rings", ",", "key", "=", "len", ",", "reverse", "=", "True", ")", ")", "base", "=", "rs", ".", "popleft", "(", ")", "first", "=", "base", "[", "0", "]", ...
29.478261
10.565217
def _cmd_down(self): """Downgrade to a revision""" revision = self._get_revision() if not self._rev: self._log(0, "downgrading current revision") else: self._log(0, "downgrading to revision %s" % revision) # execute from latest to oldest revision f...
[ "def", "_cmd_down", "(", "self", ")", ":", "revision", "=", "self", ".", "_get_revision", "(", ")", "if", "not", "self", ".", "_rev", ":", "self", ".", "_log", "(", "0", ",", "\"downgrading current revision\"", ")", "else", ":", "self", ".", "_log", "(...
45.769231
16
def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): """Executes the init functionality.""" f...
[ "def", "do_init", "(", "dev", "=", "False", ",", "requirements", "=", "False", ",", "allow_global", "=", "False", ",", "ignore_pipfile", "=", "False", ",", "skip_lock", "=", "False", ",", "system", "=", "False", ",", "concurrent", "=", "True", ",", "depl...
37.209677
19.096774
def exists(self, primary_key): ''' a method to determine if record exists :param primary_key: string with primary key of record :return: boolean to indicate existence of record ''' select_statement = self.table.select(self.table).where(...
[ "def", "exists", "(", "self", ",", "primary_key", ")", ":", "select_statement", "=", "self", ".", "table", ".", "select", "(", "self", ".", "table", ")", ".", "where", "(", "self", ".", "table", ".", "c", ".", "id", "==", "primary_key", ")", "record_...
34.142857
24.428571
def raise_(type_, value=None, traceback=None): # pylint: disable=W0613 """ Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is...
[ "def", "raise_", "(", "type_", ",", "value", "=", "None", ",", "traceback", "=", "None", ")", ":", "# pylint: disable=W0613", "prev_exc", ",", "prev_tb", "=", "sys", ".", "exc_info", "(", ")", "[", "1", ":", "]", "proxy_class", "=", "construct_exc_class", ...
36.230769
21
def data(self) -> Sequence[Tuple[float, float]]: """Returns a sequence of tuple pairs with the first item being a Rabi angle and the second item being the corresponding excited state probability. """ return [(angle, prob) for angle, prob in zip(self._rabi_angles, ...
[ "def", "data", "(", "self", ")", "->", "Sequence", "[", "Tuple", "[", "float", ",", "float", "]", "]", ":", "return", "[", "(", "angle", ",", "prob", ")", "for", "angle", ",", "prob", "in", "zip", "(", "self", ".", "_rabi_angles", ",", "self", "....
54
18.571429
def polygon(surf, points, color): """Draw an antialiased filled polygon on a surface""" gfxdraw.aapolygon(surf, points, color) gfxdraw.filled_polygon(surf, points, color) x = min([x for (x, y) in points]) y = min([y for (x, y) in points]) xm = max([x for (x, y) in points]) ym = max([y for ...
[ "def", "polygon", "(", "surf", ",", "points", ",", "color", ")", ":", "gfxdraw", ".", "aapolygon", "(", "surf", ",", "points", ",", "color", ")", "gfxdraw", ".", "filled_polygon", "(", "surf", ",", "points", ",", "color", ")", "x", "=", "min", "(", ...
31.083333
12.5
def seconds_to_hms(input_seconds): """Convert seconds to human-readable time.""" minutes, seconds = divmod(input_seconds, 60) hours, minutes = divmod(minutes, 60) hours = int(hours) minutes = int(minutes) seconds = str(int(seconds)).zfill(2) return hours, minutes, seconds
[ "def", "seconds_to_hms", "(", "input_seconds", ")", ":", "minutes", ",", "seconds", "=", "divmod", "(", "input_seconds", ",", "60", ")", "hours", ",", "minutes", "=", "divmod", "(", "minutes", ",", "60", ")", "hours", "=", "int", "(", "hours", ")", "mi...
29.3
13.2
def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]): """Try to guess a reasonable database name by looking at the repository path""" if value: return value if ctx.params["repository"]: return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE) raise...
[ "def", "default_database", "(", "ctx", ":", "click", ".", "Context", ",", "_param", ":", "Parameter", ",", "value", ":", "Optional", "[", "str", "]", ")", ":", "if", "value", ":", "return", "value", "if", "ctx", ".", "params", "[", "\"repository\"", "]...
41.111111
26.333333
def related(self, *, exclude_self=False): """ Get a QuerySet for all trigger log objects for the same connected model. Args: exclude_self (bool): Whether to exclude this log object from the result list """ manager = type(self)._default_manager queryset = mana...
[ "def", "related", "(", "self", ",", "*", ",", "exclude_self", "=", "False", ")", ":", "manager", "=", "type", "(", "self", ")", ".", "_default_manager", "queryset", "=", "manager", ".", "related_to", "(", "self", ")", "if", "exclude_self", ":", "queryset...
35.833333
17.333333
def fast_stats(data): """ Compute base statistics about submissions """ total_submission = len(data) total_submission_best = 0 total_submission_best_succeeded = 0 for submission in data: if "best" in submission and submission["best"]: total_submission_best = total_s...
[ "def", "fast_stats", "(", "data", ")", ":", "total_submission", "=", "len", "(", "data", ")", "total_submission_best", "=", "0", "total_submission_best_succeeded", "=", "0", "for", "submission", "in", "data", ":", "if", "\"best\"", "in", "submission", "and", "...
39.454545
22.5
def logical_chassis_fwdl_sanity_input_file(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity") config = logical_chassis_fwdl_sanity input = ET.SubElement(logical_chassis_fwdl_san...
[ "def", "logical_chassis_fwdl_sanity_input_file", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "logical_chassis_fwdl_sanity", "=", "ET", ".", "Element", "(", "\"logical_chassis_fwdl_sanity\"", ")", "co...
41.333333
13.583333
def is_dicom_file(filename): """ Util function to check if file is a dicom file the first 128 bytes are preamble the next 4 bytes should contain DICM otherwise it is not a dicom :param filename: file to check for the DICM header block :type filename: six.string_types :returns: True if it is...
[ "def", "is_dicom_file", "(", "filename", ")", ":", "file_stream", "=", "open", "(", "filename", ",", "'rb'", ")", "file_stream", ".", "seek", "(", "128", ")", "data", "=", "file_stream", ".", "read", "(", "4", ")", "file_stream", ".", "close", "(", ")"...
31.791667
16.291667
def average_values_for_plot(self, metric_store, data, averaging_factor): """ Create the time series for the various metrics, averaged over the aggregation period being used for plots :param dict metric_store: The metric store used to store all the parsed log data :param dict data: Dict with all the met...
[ "def", "average_values_for_plot", "(", "self", ",", "metric_store", ",", "data", ",", "averaging_factor", ")", ":", "for", "column", ",", "groups_store", "in", "metric_store", ".", "items", "(", ")", ":", "for", "group", ",", "time_store", "in", "groups_store"...
57.652174
37.217391
def save(self, filename, _url, **kwargs): """ This will stream the results to a file called <filename> This will return the url for a Request instead of actually performing the request, and then store it in self['label']. :param filename: str of the full path of the file to save...
[ "def", "save", "(", "self", ",", "filename", ",", "_url", ",", "*", "*", "kwargs", ")", ":", "api_call", "=", "self", ".", "_create_api_call", "(", "'save'", ",", "_url", ",", "kwargs", ")", "api_call", ".", "filename", "=", "filename", "data", "=", ...
39.463415
17.365854
def reboot(self, devices): """Reboot one or more devices. """ for device in devices: self.logger.info('Rebooting: %s', device.id) try: device.reboot() except packet.baseapi.Error: raise PacketManagerException('Unable to reboot i...
[ "def", "reboot", "(", "self", ",", "devices", ")", ":", "for", "device", "in", "devices", ":", "self", ".", "logger", ".", "info", "(", "'Rebooting: %s'", ",", "device", ".", "id", ")", "try", ":", "device", ".", "reboot", "(", ")", "except", "packet...
38.222222
14.333333
def get_item(self, item_index, force_download=False): """ Retrieve the metadata for a specific item in this ItemGroup :type item_index: int :param item_index: the index of the item :type force_download: Boolean :param force_download: True to download from the server ...
[ "def", "get_item", "(", "self", ",", "item_index", ",", "force_download", "=", "False", ")", ":", "return", "self", ".", "client", ".", "get_item", "(", "self", ".", "item_urls", "[", "item_index", "]", ",", "force_download", ")" ]
33.411765
20.823529
def load_config(): """Load a keyring using the config file in the config root.""" filename = 'keyringrc.cfg' keyring_cfg = os.path.join(platform.config_root(), filename) if not os.path.exists(keyring_cfg): return config = configparser.RawConfigParser() config.read(keyring_cfg) _l...
[ "def", "load_config", "(", ")", ":", "filename", "=", "'keyringrc.cfg'", "keyring_cfg", "=", "os", ".", "path", ".", "join", "(", "platform", ".", "config_root", "(", ")", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "keyri...
31.535714
22.678571
def add(self, elt): """Generic function to add objects to the daemon internal lists. Manage Broks, External commands and Messages (from modules queues) :param elt: object to add :type elt: alignak.AlignakObject :return: None """ if isinstance(elt, Brok): ...
[ "def", "add", "(", "self", ",", "elt", ")", ":", "if", "isinstance", "(", "elt", ",", "Brok", ")", ":", "# For brok, we tag the brok with our instance_id", "elt", ".", "instance_id", "=", "self", ".", "instance_id", "if", "elt", ".", "type", "==", "'monitori...
49.464286
16.125
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Edit a task """ if not id_checker(taskid): raise Exception("Invalid task id") course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) try: task_data = self.task_...
[ "def", "GET_AUTH", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "# pylint: disable=arguments-differ", "if", "not", "id_checker", "(", "taskid", ")", ":", "raise", "Exception", "(", "\"Invalid task id\"", ")", "course", ",", "__", "=", "self", ".", ...
36.875
25.95
async def _connect(self, remote_addresses): '''Connect to the proxy and perform a handshake requesting a connection to each address in addresses. Return an (open_socket, remote_address) pair on success. ''' assert remote_addresses exceptions = [] for remote_addr...
[ "async", "def", "_connect", "(", "self", ",", "remote_addresses", ")", ":", "assert", "remote_addresses", "exceptions", "=", "[", "]", "for", "remote_address", "in", "remote_addresses", ":", "sock", "=", "await", "self", ".", "_connect_one", "(", "remote_address...
38.666667
21.111111
def func_from_string(callable_str): """Return a live function from a full dotted path. Must be either a plain function directly in a module, a class function, or a static function. (No modules, classes, or instance methods, since those can't be called as tasks.)""" components = callable_str.split('.')...
[ "def", "func_from_string", "(", "callable_str", ")", ":", "components", "=", "callable_str", ".", "split", "(", "'.'", ")", "func", "=", "None", "if", "len", "(", "components", ")", "<", "2", ":", "raise", "ValueError", "(", "\"Need full dotted path to task fu...
38.028169
22.887324
def upstream_url(self, uri): "Returns the URL to the upstream data source for the given URI based on configuration" return self.application.options.upstream + self.request.uri
[ "def", "upstream_url", "(", "self", ",", "uri", ")", ":", "return", "self", ".", "application", ".", "options", ".", "upstream", "+", "self", ".", "request", ".", "uri" ]
63
31
def execute_with_client(quiet=False, bootstrap_server=False, create_client=True): """Decorator that gets a client and performs an operation on it.""" def wrapper(f): def wrapper2(self, *args, **kwargs): client = self.current_client( ...
[ "def", "execute_with_client", "(", "quiet", "=", "False", ",", "bootstrap_server", "=", "False", ",", "create_client", "=", "True", ")", ":", "def", "wrapper", "(", "f", ")", ":", "def", "wrapper2", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs...
35.0625
12.625
def _tracker_str(item): """Returns a string representation of the tracker object for the given item. Args: item: object to get tracker for. fqdn (str): fully-qualified domain name of the object. """ instance = tracker(item) if instance is not None: if isinstance(instance...
[ "def", "_tracker_str", "(", "item", ")", ":", "instance", "=", "tracker", "(", "item", ")", "if", "instance", "is", "not", "None", ":", "if", "isinstance", "(", "instance", ",", "str", ")", ":", "return", "instance", "elif", "isinstance", "(", "instance"...
32.157895
15.368421
def dump(self, value): """Dumps the value to string. :returns: Returns the stringified version of the value. :raises: TypeError, ValueError """ value = self.__convert__(value) self.__validate__(value) return self.__serialize__(value)
[ "def", "dump", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "__convert__", "(", "value", ")", "self", ".", "__validate__", "(", "value", ")", "return", "self", ".", "__serialize__", "(", "value", ")" ]
28.2
13.2
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
[ "def", "parse_timestamp", "(", "timestamp", ")", ":", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "timestamp", ")", "return", "dt", ".", "astimezone", "(", "dateutil", ".", "tz", ".", "tzutc", "(", ")", ")" ]
43
3.75
def EvalPecoff(self, hashers=None): """If the file is a PE/COFF file, computes authenticode hashes on it. This checks if the input file is a valid PE/COFF image file (e.g. a Windows binary, driver, or DLL) and if yes, sets up a 'finger' for fingerprinting in Authenticode style. If available, the 'S...
[ "def", "EvalPecoff", "(", "self", ",", "hashers", "=", "None", ")", ":", "try", ":", "extents", "=", "self", ".", "_PecoffHeaderParser", "(", ")", "except", "struct", ".", "error", ":", "# Parsing the header failed. Just ignore this, and claim", "# that the file is ...
40.050847
19.474576
def load(self): """Loads a user's inventory Queries the user's inventory, parses each item, and adds each item to the inventory. Note this class should not be used directly, but rather usr.inventory should be used to access a user's inventory. Parameters ...
[ "def", "load", "(", "self", ")", ":", "self", ".", "items", "=", "{", "}", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/objects.phtml?type=inventory\"", ")", "# Indicates an empty inventory", "if", "\"You aren't carrying anything\"", ...
38.292683
20.487805
def open_tar(path_or_file, *args, **kwargs): """ A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately. """ (path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, string_types) else...
[ "def", "open_tar", "(", "path_or_file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "(", "path", ",", "fileobj", ")", "=", "(", "(", "path_or_file", ",", "None", ")", "if", "isinstance", "(", "path_or_file", ",", "string_types", ")", "else", ...
52.272727
30.818182
def cli_certify_core_number( config, min_value, max_value, value, ): """Console script for certify_number""" verbose = config['verbose'] if verbose: click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int") def parser(v): # Attempt a json/pickle decode: try: v ...
[ "def", "cli_certify_core_number", "(", "config", ",", "min_value", ",", "max_value", ",", "value", ",", ")", ":", "verbose", "=", "config", "[", "'verbose'", "]", "if", "verbose", ":", "click", ".", "echo", "(", "Back", ".", "GREEN", "+", "Fore", ".", ...
25.644444
17.666667
def plot(self, colorbar=True, cb_orientation='horizontal', tick_interval=[90, 90], minor_tick_interval=[30, 30], xlabel='Longitude', ylabel='Latitude', axes_labelsize=8, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the 9 components of t...
[ "def", "plot", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'horizontal'", ",", "tick_interval", "=", "[", "90", ",", "90", "]", ",", "minor_tick_interval", "=", "[", "30", ",", "30", "]", ",", "xlabel", "=", "'Longitude'", "...
47.023438
17.8125
def detect_languages(self, texts): """ Params: ::texts = Array of texts for detect languages Returns: Returns language present on array of text. """ text_list = TextUtils.format_list_to_send(texts) infos_translate = TextDe...
[ "def", "detect_languages", "(", "self", ",", "texts", ")", ":", "text_list", "=", "TextUtils", ".", "format_list_to_send", "(", "texts", ")", "infos_translate", "=", "TextDetectLanguageModel", "(", "text_list", ")", ".", "to_dict", "(", ")", "texts_for_detect", ...
45.214286
21.071429
def _ReadString( self, file_object, file_offset, data_type_map, description): """Reads a string. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_type_map (dtfabric.DataTypeMap): data type...
[ "def", "_ReadString", "(", "self", ",", "file_object", ",", "file_offset", ",", "data_type_map", ",", "description", ")", ":", "# pylint: disable=protected-access", "element_data_size", "=", "(", "data_type_map", ".", "_element_data_type_definition", ".", "GetByteSize", ...
33.361111
20.333333
def write(self, fh): """ Write set to a GFF3 format file. :param file fh: file handle for file to write to """ fh.write(GFF3_HEADER+"\n") for root in sorted(self.roots, key=self._recSortKey): self._writeRec(fh, root)
[ "def", "write", "(", "self", ",", "fh", ")", ":", "fh", ".", "write", "(", "GFF3_HEADER", "+", "\"\\n\"", ")", "for", "root", "in", "sorted", "(", "self", ".", "roots", ",", "key", "=", "self", ".", "_recSortKey", ")", ":", "self", ".", "_writeRec"...
29.888889
11.888889
def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters])
[ "def", "sanitize_host", "(", "host", ")", ":", "RFC952_characters", "=", "ascii_letters", "+", "digits", "+", "\".-\"", "return", "\"\"", ".", "join", "(", "[", "c", "for", "c", "in", "host", "[", "0", ":", "255", "]", "if", "c", "in", "RFC952_characte...
33.857143
21.571429
def Counter32(a, b, delta): """32bit counter aggregator with wrapping """ if b < a: c = 4294967295 - a return (c + b) / float(delta) return (b - a) / float(delta)
[ "def", "Counter32", "(", "a", ",", "b", ",", "delta", ")", ":", "if", "b", "<", "a", ":", "c", "=", "4294967295", "-", "a", "return", "(", "c", "+", "b", ")", "/", "float", "(", "delta", ")", "return", "(", "b", "-", "a", ")", "/", "float",...
23.5
13
def p_arg_list(p): """ arg_list : ident_init_opt | arg_list COMMA ident_init_opt """ if len(p) == 2: p[0] = node.expr_list([p[1]]) elif len(p) == 4: p[0] = p[1] p[0].append(p[3]) else: assert 0 assert isinstance(p[0], node.expr_list)
[ "def", "p_arg_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "node", ".", "expr_list", "(", "[", "p", "[", "1", "]", "]", ")", "elif", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0",...
22.615385
13.384615
def moveRows(self, parent, index_to, index_from, length): """Move a sub sequence in a list index_to must be smaller than index_from """ source = self.getItem(parent).childItems self.beginMoveRows( parent, index_from, index_from + length - 1, parent, index_to ...
[ "def", "moveRows", "(", "self", ",", "parent", ",", "index_to", ",", "index_from", ",", "length", ")", ":", "source", "=", "self", ".", "getItem", "(", "parent", ")", ".", "childItems", "self", ".", "beginMoveRows", "(", "parent", ",", "index_from", ",",...
28.529412
21.647059
def external_links(self) -> List['ExternalLink']: """Return a list of found external link objects. Note: Templates adjacent to external links are considered part of the link. In reality, this depends on the contents of the template: >>> WikiText( ... ...
[ "def", "external_links", "(", "self", ")", "->", "List", "[", "'ExternalLink'", "]", ":", "external_links", "=", "[", "]", "# type: List['ExternalLink']", "external_links_append", "=", "external_links", ".", "append", "type_to_spans", "=", "self", ".", "_type_to_spa...
41.446809
15.553191
def open_recruitment(self, n=1): """Open recruitment.""" logger.info("Opening Sim recruitment for {} participants".format(n)) return {"items": self.recruit(n), "message": "Simulated recruitment only"}
[ "def", "open_recruitment", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Opening Sim recruitment for {} participants\"", ".", "format", "(", "n", ")", ")", "return", "{", "\"items\"", ":", "self", ".", "recruit", "(", "n", ")", ...
55.25
21.5
def name(self, decl_string): """implementation details""" if not self.has_pattern(decl_string): return decl_string args_begin = decl_string.find(self.__begin) return decl_string[0: args_begin].strip()
[ "def", "name", "(", "self", ",", "decl_string", ")", ":", "if", "not", "self", ".", "has_pattern", "(", "decl_string", ")", ":", "return", "decl_string", "args_begin", "=", "decl_string", ".", "find", "(", "self", ".", "__begin", ")", "return", "decl_strin...
39.833333
7.833333
def set_handler(self, handler): """ Connect with a coroutine, which is scheduled when connection is made. This function will create a task, and when connection is closed, the task will be canceled. :param handler: :return: None """ if self._handler: ...
[ "def", "set_handler", "(", "self", ",", "handler", ")", ":", "if", "self", ".", "_handler", ":", "raise", "Exception", "(", "'Handler was already set'", ")", "if", "handler", ":", "self", ".", "_handler", "=", "async_task", "(", "handler", ",", "loop", "="...
34
18
def export_action_form_factory(formats): """ Returns an ActionForm subclass containing a ChoiceField populated with the given formats. """ class _ExportActionForm(ActionForm): """ Action form with export format ChoiceField. """ file_format = forms.ChoiceField( ...
[ "def", "export_action_form_factory", "(", "formats", ")", ":", "class", "_ExportActionForm", "(", "ActionForm", ")", ":", "\"\"\"\n Action form with export format ChoiceField.\n \"\"\"", "file_format", "=", "forms", ".", "ChoiceField", "(", "label", "=", "_", ...
32.142857
11
def safe_wraps(wrapper, *args, **kwargs): """Safely wraps partial functions.""" while isinstance(wrapper, functools.partial): wrapper = wrapper.func return functools.wraps(wrapper, *args, **kwargs)
[ "def", "safe_wraps", "(", "wrapper", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "while", "isinstance", "(", "wrapper", ",", "functools", ".", "partial", ")", ":", "wrapper", "=", "wrapper", ".", "func", "return", "functools", ".", "wraps", "(...
42.6
6.4
def get_ticker_price(self, ticker, startDate=None, endDate=None, fmt='json', frequency='daily'): """By default, return latest EOD Composite Price for a stock ticker. On average, each feed contains 3 data sources. Supported tickers + Avail...
[ "def", "get_ticker_price", "(", "self", ",", "ticker", ",", "startDate", "=", "None", ",", "endDate", "=", "None", ",", "fmt", "=", "'json'", ",", "frequency", "=", "'daily'", ")", ":", "url", "=", "self", ".", "_get_url", "(", "ticker", ",", "frequenc...
40.972973
19.756757
def to_output(self, value): """Convert value to process output format.""" return json.loads(resolwe_runtime_utils.save_file(self.name, value.path, *value.refs))
[ "def", "to_output", "(", "self", ",", "value", ")", ":", "return", "json", ".", "loads", "(", "resolwe_runtime_utils", ".", "save_file", "(", "self", ".", "name", ",", "value", ".", "path", ",", "*", "value", ".", "refs", ")", ")" ]
58
22.333333
def atomic_write(filename, content, overwrite=True, permissions=0o0644, encoding='utf-8'): ''' Write a file atomically by writing the file content to a temporary location first, then renaming the file. TODO: this relies pretty heavily on os.rename to ensure atomicity, but os.rename does not s...
[ "def", "atomic_write", "(", "filename", ",", "content", ",", "overwrite", "=", "True", ",", "permissions", "=", "0o0644", ",", "encoding", "=", "'utf-8'", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "not",...
40.225806
20.096774
def get_posts(self, count=10, offset=0, recent=True, tag=None, user_id=None, include_draft=False): """TODO: implement cursors support, if it will be needed. But for the regular blog, it is overhead and cost savings are minimal. """ query = self._client.que...
[ "def", "get_posts", "(", "self", ",", "count", "=", "10", ",", "offset", "=", "0", ",", "recent", "=", "True", ",", "tag", "=", "None", ",", "user_id", "=", "None", ",", "include_draft", "=", "False", ")", ":", "query", "=", "self", ".", "_client",...
31.488372
19.860465
def set_variable(self, key, value, per_reference=False, access_key=None, data_type=None): """Sets a global variable :param key: the key of the global variable to be set :param value: the new value of the global variable :param per_reference: a flag to decide if the variable should be st...
[ "def", "set_variable", "(", "self", ",", "key", ",", "value", ",", "per_reference", "=", "False", ",", "access_key", "=", "None", ",", "data_type", "=", "None", ")", ":", "key", "=", "str", "(", "key", ")", "# Ensure that we have the same string type for all k...
47
24.06383
def _split_line_with_offsets(line): """Split a line by delimiter, but yield tuples of word and offset. This function works by dropping all the english-like punctuation from a line (so parenthesis preceded or succeeded by spaces, periods, etc) and then splitting on spaces. """ for delimiter in r...
[ "def", "_split_line_with_offsets", "(", "line", ")", ":", "for", "delimiter", "in", "re", ".", "finditer", "(", "r\"[\\.,:\\;](?![^\\s])\"", ",", "line", ")", ":", "span", "=", "delimiter", ".", "span", "(", ")", "line", "=", "line", "[", ":", "span", "[...
36.225806
17.483871
def _get_detail_value(var, attr): """ Given a variable and one of its attributes that are available inside of a template, return its 'method' if it is a callable, its class name if it is a model manager, otherwise return its value """ value = getattr(var, attr) # Rename common Django class n...
[ "def", "_get_detail_value", "(", "var", ",", "attr", ")", ":", "value", "=", "getattr", "(", "var", ",", "attr", ")", "# Rename common Django class names", "kls", "=", "getattr", "(", "getattr", "(", "value", ",", "'__class__'", ",", "''", ")", ",", "'__na...
38.214286
16.928571
def pretty_flags(flags): """Return pretty representation of code flags.""" names = [] result = "0x%08x" % flags for i in range(32): flag = 1 << i if flags & flag: names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag))) flags ^= flag if not flags: ...
[ "def", "pretty_flags", "(", "flags", ")", ":", "names", "=", "[", "]", "result", "=", "\"0x%08x\"", "%", "flags", "for", "i", "in", "range", "(", "32", ")", ":", "flag", "=", "1", "<<", "i", "if", "flags", "&", "flag", ":", "names", ".", "append"...
29
16.666667
def parse_feed(content): """ utility function to parse feed """ feed = feedparser.parse(content) articles = [] for entry in feed['entries']: article = { 'title': entry['title'], 'link': entry['link'] } tr...
[ "def", "parse_feed", "(", "content", ")", ":", "feed", "=", "feedparser", ".", "parse", "(", "content", ")", "articles", "=", "[", "]", "for", "entry", "in", "feed", "[", "'entries'", "]", ":", "article", "=", "{", "'title'", ":", "entry", "[", "'tit...
29.647059
10.117647
def ABC(self): ''' A list of the triangle's vertices, list. ''' try: return self._ABC except AttributeError: pass self._ABC = [self.A, self.B, self.C] return self._ABC
[ "def", "ABC", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_ABC", "except", "AttributeError", ":", "pass", "self", ".", "_ABC", "=", "[", "self", ".", "A", ",", "self", ".", "B", ",", "self", ".", "C", "]", "return", "self", ".", ...
21.636364
20.545455
def get_parent_aligned_annotation(self, ref_id): """" Give the aligment annotation that a reference annotation belongs to directly, or indirectly through other reference annotations. :param str ref_id: Id of a reference annotation. :raises KeyError: If no annotation exists with the id or...
[ "def", "get_parent_aligned_annotation", "(", "self", ",", "ref_id", ")", ":", "parentTier", "=", "self", ".", "tiers", "[", "self", ".", "annotations", "[", "ref_id", "]", "]", "while", "\"PARENT_REF\"", "in", "parentTier", "[", "2", "]", "and", "len", "("...
55.076923
19.615385
def find_slave_widgets(self,tab): """return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the conversion tabNumber/wid...
[ "def", "find_slave_widgets", "(", "self", ",", "tab", ")", ":", "#convert from/to int/richIpythonWidget if needed", "if", "isinstance", "(", "tab", ",", "int", ")", ":", "tab", "=", "self", ".", "tab_widget", ".", "widget", "(", "tab", ")", "km", "=", "tab",...
49.04
27.72
def v1_tag_suggest(request, tags, prefix, parent=''): '''Provide fast suggestions for tag components. This yields suggestions for *components* of a tag and a given prefix. For example, given the tags ``foo/bar/baz`` and ``fob/bob``, here are some example completions (ordering may be different): ...
[ "def", "v1_tag_suggest", "(", "request", ",", "tags", ",", "prefix", ",", "parent", "=", "''", ")", ":", "prefix", "=", "prefix", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "parent", "=", "parent", ".", "decode", "(", "'utf-8'", ")",...
37.633333
22.766667
def initialize(self, currentdir, assetpath, cplist, cplistfile, executor, readonly, baseurl): ''' handles initial setup. ''' self.currentdir = currentdir self.assetpath = assetpath self.currentproject = cplist self.cplistfile = cplistfile ...
[ "def", "initialize", "(", "self", ",", "currentdir", ",", "assetpath", ",", "cplist", ",", "cplistfile", ",", "executor", ",", "readonly", ",", "baseurl", ")", ":", "self", ".", "currentdir", "=", "currentdir", "self", ".", "assetpath", "=", "assetpath", "...
28.5
15.928571
def request_length(self): """ Return length of next chunk upload. """ remainder = self.stop_at - self.offset return self.chunk_size if remainder > self.chunk_size else remainder
[ "def", "request_length", "(", "self", ")", ":", "remainder", "=", "self", ".", "stop_at", "-", "self", ".", "offset", "return", "self", ".", "chunk_size", "if", "remainder", ">", "self", ".", "chunk_size", "else", "remainder" ]
35.333333
10
def WriteClientActionRequests(self, requests): """Writes messages that should go to the client to the db.""" for r in requests: req_dict = self.flow_requests.get((r.client_id, r.flow_id), {}) if r.request_id not in req_dict: request_keys = [(r.client_id, r.flow_id, r.request_id) for r in req...
[ "def", "WriteClientActionRequests", "(", "self", ",", "requests", ")", ":", "for", "r", "in", "requests", ":", "req_dict", "=", "self", ".", "flow_requests", ".", "get", "(", "(", "r", ".", "client_id", ",", "r", ".", "flow_id", ")", ",", "{", "}", "...
44.5
18.083333
def autointerpret_specimen(self, specimen, step_size, calculation_type): """In Dev""" if self.COORDINATE_SYSTEM == 'geographic': block = self.Data[specimen]['zijdblock_geo'] elif self.COORDINATE_SYSTEM == 'tilt-corrected': block = self.Data[specimen]['zijdblock_tilt'] ...
[ "def", "autointerpret_specimen", "(", "self", ",", "specimen", ",", "step_size", ",", "calculation_type", ")", ":", "if", "self", ".", "COORDINATE_SYSTEM", "==", "'geographic'", ":", "block", "=", "self", ".", "Data", "[", "specimen", "]", "[", "'zijdblock_geo...
38.375
16.425
def _data_to_tensor(data_list, batch_size, name=None): r"""Returns batch queues from the whole data. Args: data_list: A list of ndarrays. Every array must have the same size in the first dimension. batch_size: An integer. name: A name for the operations (optional). Returns: ...
[ "def", "_data_to_tensor", "(", "data_list", ",", "batch_size", ",", "name", "=", "None", ")", ":", "# convert to constant tensor", "const_list", "=", "[", "tf", ".", "constant", "(", "data", ")", "for", "data", "in", "data_list", "]", "# create queue from consta...
38.1
23.75
def set_all_variables(self, delu_dict, delu_default): """ Sets all chemical potential values and returns a dictionary where the key is a sympy Symbol and the value is a float (chempot). Args: entry (SlabEntry): Computed structure entry of the slab delu_dict (...
[ "def", "set_all_variables", "(", "self", ",", "delu_dict", ",", "delu_default", ")", ":", "# Set up the variables", "all_delu_dict", "=", "{", "}", "for", "du", "in", "self", ".", "list_of_chempots", ":", "if", "delu_dict", "and", "du", "in", "delu_dict", ".",...
38.555556
21.962963
def resizeColumnsToContents(self): """Resize the columns to its contents.""" self._autosized_cols = set() self._resizeColumnsToContents(self.table_level, self.table_index, self._max_autosize_ms) self._update_layout()
[ "def", "resizeColumnsToContents", "(", "self", ")", ":", "self", ".", "_autosized_cols", "=", "set", "(", ")", "self", ".", "_resizeColumnsToContents", "(", "self", ".", "table_level", ",", "self", ".", "table_index", ",", "self", ".", "_max_autosize_ms", ")",...
47.666667
12.333333
def x(self, d): """ Allows to configure the X of the grid with one method call. Keys for the dictionary: property, min, max, step, base, expression Types: property=str, min=float, max=float, step=float, base=float, expression=str :param d: the dictionary with the parameters ...
[ "def", "x", "(", "self", ",", "d", ")", ":", "if", "\"property\"", "in", "d", ":", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"setXProperty\"", ",", "\"(Ljava/lang/String;)V\"", ",", "d", "[", "\"property\"", "]", ")", "if", "\"min\""...
46.142857
25.857143
def dump(data_structure): """Dump will create a human readable version of your data-structure. It will try to dump almost anything, it has recursion detection and will try to display the recursion in a meaningful way. :param data_structure: The structure to convert. When you freeze only content ...
[ "def", "dump", "(", "data_structure", ")", ":", "identity_set", "=", "set", "(", ")", "dup_set", "=", "set", "(", ")", "def", "dump_helper", "(", "data_structure", ")", ":", "if", "data_structure", "is", "None", ":", "return", "None", "# Primitive types don'...
29.145749
18.809717