code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def request(self, *args, **kwargs): try: return self._http.request(*args, timeout=TIMEOUT, **kwargs) except Exception as exc: raise RequestException(exc, args, kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier keyword_argument identifier identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier identifier identifier
Issue the HTTP request capturing any errors that may occur.
def delayed_close(closable): close = getattr(closable, "close", None) if close: def replacement_close(*args, **kw): pass setattr(closable, "close", replacement_close) try: yield closable finally: if close: setattr(closable, "close", close) closable.close()
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block pass_statement expression_statement call identifier argument_list identifier string string_start string_content string_end identifier try_statement block expression_statement yield identifier finally_clause block if_statement identifier block expression_statement call identifier argument_list identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list
Delay close until this contextmanager dies
def factors(self, rank): self._check_rank(rank) return [result.factors for result in self.results[rank]]
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement list_comprehension attribute identifier identifier for_in_clause identifier subscript attribute identifier identifier identifier
Returns KTensor factors for models with specified rank.
def _input_file_as_html_links(cls, session: AppSession): scrape_result = session.factory['HTMLScraper'].scrape_file( session.args.input_file, encoding=session.args.local_encoding or 'utf-8' ) for context in scrape_result.link_contexts: yield context.link
module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier boolean_operator attribute attribute identifier identifier identifier string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement yield attribute identifier identifier
Read input file as HTML and return the links.
def json_serial(obj): if isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() raise TypeError('Type {} not serializable.'.format(type(obj)))
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier tuple attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier
Custom JSON serializer for objects not serializable by default.
def save_gradebook_column(self, gradebook_column_form, *args, **kwargs): if gradebook_column_form.is_for_update(): return self.update_gradebook_column(gradebook_column_form, *args, **kwargs) else: return self.create_gradebook_column(gradebook_column_form, *args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier
Pass through to provider GradebookColumnAdminSession.update_gradebook_column
def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]: if isinstance(expression, Operation): yield type(expression) for operand in op_iter(expression): yield from cls._flatterm_iter(operand) yield OPERATION_END elif isinstance(expression, SymbolWildcard): yield expression.symbol_type elif isinstance(expression, (Symbol, Wildcard)): yield expression else: assert False, "Unreachable unless a new unsupported expression type is added."
module function_definition identifier parameters identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block if_statement call identifier argument_list identifier identifier block expression_statement yield call identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement yield call attribute identifier identifier argument_list identifier expression_statement yield identifier elif_clause call identifier argument_list identifier identifier block expression_statement yield attribute identifier identifier elif_clause call identifier argument_list identifier tuple identifier identifier block expression_statement yield identifier else_clause block assert_statement false string string_start string_content string_end
Generator that yields the atoms of the expressions in prefix notation with operation end markers.
def repo_id(self, repo: str) -> str: if repo.startswith("http"): repo_id = re.sub(r"https?://(.www)?", "", repo) repo_id = re.sub(r"\.git/?$", "", repo_id) else: repo_id = repo.replace("file://", "") repo_id = re.sub(r"\.git/?$", "", repo_id) if repo_id.startswith("~"): repo_id = str(Path(repo_id).resolve()) repo_id = re.sub(r"[^a-zA-Z0-9._]+", "_", repo_id) return repo_id + hashlib.sha256(repo.encode("utf-8")).hexdigest()
module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_statement binary_operator identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list
Returns an unique identifier from a repo URL for the folder the repo is gonna be pulled in.
def sscan(self, key, cursor=0, match=None, count=None): tokens = [key, cursor] match is not None and tokens.extend([b'MATCH', match]) count is not None and tokens.extend([b'COUNT', count]) fut = self.execute(b'SSCAN', *tokens) return wait_convert(fut, lambda obj: (int(obj[0]), obj[1]))
module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier list identifier identifier expression_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list list string string_start string_content string_end identifier expression_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list_splat identifier return_statement call identifier argument_list identifier lambda lambda_parameters identifier tuple call identifier argument_list subscript identifier integer subscript identifier integer
Incrementally iterate Set elements.
def getAttributeUri(self, index): offset = self._get_attribute_offset(index) uri = self.m_attributes[offset + ATTRIBUTE_IX_NAMESPACE_URI] return uri
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier binary_operator identifier identifier return_statement identifier
Returns the numeric ID for the namespace URI of an attribute
def py_to_go_cookie(py_cookie): go_cookie = { 'Name': py_cookie.name, 'Value': py_cookie.value, 'Domain': py_cookie.domain, 'HostOnly': not py_cookie.domain_specified, 'Persistent': not py_cookie.discard, 'Secure': py_cookie.secure, 'CanonicalHost': py_cookie.domain, } if py_cookie.path_specified: go_cookie['Path'] = py_cookie.path if py_cookie.expires is not None: unix_time = datetime.datetime.fromtimestamp(py_cookie.expires) go_cookie['Expires'] = pyrfc3339.generate(unix_time, accept_naive=True) return go_cookie
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end not_operator attribute identifier identifier pair string string_start string_content string_end not_operator attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier keyword_argument identifier true return_statement identifier
Convert a python cookie to the JSON-marshalable Go-style cookie form.
def print_scoreboard(self): output = '' innings = [] away = [] home = [] for x in self: innings.append(x['inning']) away.append(x['away']) home.append(x['home']) output += 'Inning\t' for x in innings: output += str(x) + ' ' output += '\n' for x in innings: output += '---' output += '\nAway\t' + self.__enumerate_scoreboard(away) output += '\nHome\t' + self.__enumerate_scoreboard(home) return output
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier list expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end for_statement identifier identifier block expression_statement augmented_assignment identifier binary_operator call identifier argument_list identifier string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end for_statement identifier identifier block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list identifier return_statement identifier
Print object as a scoreboard.
def package_files(directory): paths = [] for (path, _, file_names) in walk(directory): for filename in file_names: paths.append(join('..', path, filename)) return paths
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement tuple_pattern identifier identifier identifier call identifier argument_list identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end identifier identifier return_statement identifier
Get list of data files to add to the package.
def save_img(object, handle, **kwargs): if isinstance(object, np.ndarray): normalized = _normalize_array(object) object = PIL.Image.fromarray(normalized) if isinstance(object, PIL.Image.Image): object.save(handle, **kwargs) else: raise ValueError("Can only save_img for numpy arrays or PIL.Images!")
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement call identifier argument_list identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end
Save numpy array as image file on CNS.
def _writeSuperLinks(self, superLinks, fileObject): for slink in superLinks: fileObject.write('SLINK %s %s\n' % ( slink.slinkNumber, slink.numPipes)) for node in slink.superNodes: fileObject.write('NODE %s %.2f %.2f %.6f %s %s %s %.6f %.6f\n' % ( node.nodeNumber, node.groundSurfaceElev, node.invertElev, node.manholeSA, node.nodeInletCode, node.cellI, node.cellJ, node.weirSideLength, node.orificeDiameter)) for pipe in slink.pipes: fileObject.write('PIPE %s %s %.6f %.6f %.6f %.6f %.2f %.6f %.6f\n' % ( pipe.pipeNumber, pipe.xSecType, pipe.diameterOrHeight, pipe.width, pipe.slope, pipe.roughness, pipe.length, pipe.conductance, pipe.drainSpacing))
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier
Write SuperLinks to File Method
def tryOrder(self, commit: Commit): canOrder, reason = self.canOrder(commit) if canOrder: self.logger.trace("{} returning request to node".format(self)) self.doOrder(commit) else: self.logger.debug("{} cannot return request to node: {}".format(self, reason)) return canOrder
module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier
Try to order if the Commit message is ready to be ordered.
def register (g): assert isinstance(g, Generator) id = g.id() __generators [id] = g for t in sequence.unique(g.target_types()): __type_to_generators.setdefault(t, []).append(g) base = id.split ('.', 100) [0] __generators_for_toolset.setdefault(base, []).append(g) invalidate_extendable_viable_source_target_type_cache()
module function_definition identifier parameters identifier block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier identifier identifier for_statement identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list block expression_statement call attribute call attribute identifier identifier argument_list identifier list identifier argument_list identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer expression_statement call attribute call attribute identifier identifier argument_list identifier list identifier argument_list identifier expression_statement call identifier argument_list
Registers new generator instance 'g'.
def escape_quotes(self, val): if self.is_string(val) and self._in_quotes(val, self.quote): middle = self.remove_quotes(val).replace("\\" + self.quote, self.quote) middle = middle.replace(self.quote, "\\" + self.quote) val = self.add_quotes(middle) return val
module function_definition identifier parameters identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier
Escape any quotes in a value
def init_progress_bar(self): disable = MapReduce._forked or not config.PROGRESS_BARS if disable: total = None else: self.iterable = list(self.iterable) total = len(self.iterable) return tqdm(total=total, disable=disable, leave=False, desc=self.description)
module function_definition identifier parameters identifier block expression_statement assignment identifier boolean_operator attribute identifier identifier not_operator attribute identifier identifier if_statement identifier block expression_statement assignment identifier none else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier false keyword_argument identifier attribute identifier identifier
Initialize and return a progress bar.
def calculate_mypypath() -> List[str]: typeshed_root = None count = 0 started = time.time() for parent in itertools.chain( Path(__file__).parents, Path(mypy.api.__file__).parents, Path(os.__file__).parents, ): count += 1 candidate = parent / 'lib' / 'mypy' / 'typeshed' if candidate.is_dir(): typeshed_root = candidate break candidate = parent / 'typeshed' if candidate.is_dir(): typeshed_root = candidate break LOG.debug( 'Checked %d paths in %.2fs looking for typeshed. Found %s', count, time.time() - started, typeshed_root, ) if not typeshed_root: return [] stdlib_dirs = ('3.7', '3.6', '3.5', '3.4', '3.3', '3.2', '3', '2and3') stdlib_stubs = [ typeshed_root / 'stdlib' / stdlib_dir for stdlib_dir in stdlib_dirs ] third_party_dirs = ('3.7', '3.6', '3', '2and3') third_party_stubs = [ typeshed_root / 'third_party' / tp_dir for tp_dir in third_party_dirs ] return [ str(p) for p in stdlib_stubs + third_party_stubs ]
module function_definition identifier parameters type generic_type identifier type_parameter type identifier block expression_statement assignment identifier none expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list attribute call identifier argument_list identifier identifier attribute call identifier argument_list attribute attribute identifier identifier identifier identifier attribute call identifier argument_list attribute identifier identifier identifier block expression_statement augmented_assignment identifier integer expression_statement assignment identifier binary_operator binary_operator binary_operator identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier identifier break_statement expression_statement assignment identifier binary_operator identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier identifier break_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier binary_operator call attribute identifier identifier argument_list identifier identifier if_statement not_operator identifier block return_statement list expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list_comprehension binary_operator binary_operator identifier string string_start string_content string_end identifier for_in_clause identifier identifier expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list_comprehension binary_operator binary_operator identifier string string_start string_content string_end identifier for_in_clause identifier identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier binary_operator identifier identifier
Return MYPYPATH so that stubs have precedence over local sources.
def distribute(build): build.packages.install("wheel") build.packages.install("twine") build.executables.run([ "python", "setup.py", "sdist", "bdist_wheel", "--universal", "upload", ]) build.executables.run([ "twine", "upload", "dist/*" ])
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end
distribute the uranium package
async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, event) conn_string = self._translate_conn_string(adapter_id, conn_string) elif conn_id is not None and self._get_property(conn_id, 'translate'): conn_string = self._translate_conn_string(adapter_id, conn_string) else: conn_string = "adapter/%d/%s" % (adapter_id, conn_string) await self.notify_event(conn_string, name, event)
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier elif_clause boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement await call attribute identifier identifier argument_list identifier identifier identifier
Handle an event received from an adapter.
def _start_ssh_agent(cls): env = dict() stdout = ClHelper.run_command('ssh-agent -s') lines = stdout.split('\n') for line in lines: if not line or line.startswith('echo '): continue line = line.split(';')[0] parts = line.split('=') if len(parts) == 2: env[parts[0]] = parts[1] return env
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end for_statement identifier identifier block if_statement boolean_operator not_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end block continue_statement expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment subscript identifier subscript identifier integer subscript identifier integer return_statement identifier
Starts ssh-agent and returns the environment variables related to it
def _backspace(self): if self.command == ':': return logger.log(5, "Snippet keystroke `Backspace`.") self.command = self.command[:-1]
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement expression_statement call attribute identifier identifier argument_list integer string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice unary_operator integer
Erase the last character in the snippet command.
def array_bytes(shape, dtype): return np.product(shape)*np.dtype(dtype).itemsize
module function_definition identifier parameters identifier identifier block return_statement binary_operator call attribute identifier identifier argument_list identifier attribute call attribute identifier identifier argument_list identifier identifier
Estimates the memory in bytes required for an array of the supplied shape and dtype
def image_task(self): uri = "/%s/task" % self.uri_base resp, resp_body = self.api.method_get(uri) return resp_body
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier
Returns a json-schema document that represents an task entity.
def parse_file(self, sourcepath): with open(sourcepath, 'r') as logfile: jsonlist = logfile.readlines() data = {} data['entries'] = [] for line in jsonlist: entry = self.parse_line(line) data['entries'].append(entry) if self.tzone: for e in data['entries']: e['tzone'] = self.tzone return data
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier if_statement attribute identifier identifier block for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier
Parse an object-per-line JSON file into a log data dict
def find_by_typename(self, typename): return self.find_by(lambda obj: type(obj).__name__ == typename)
module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier comparison_operator attribute call identifier argument_list identifier identifier identifier
List of all objects whose type has the given name.
def user(val, **kwargs): if not isinstance(val, six.integer_types): try: val = int(val) except (TypeError, ValueError): pass if not isinstance(val, (six.integer_types, six.string_types)): raise SaltInvocationError('Value must be a username or uid') elif isinstance(val, six.integer_types) and val < 0: raise SaltInvocationError('\'{0}\' is an invalid uid'.format(val)) return val
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause tuple identifier identifier block pass_statement if_statement not_operator call identifier argument_list identifier tuple attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end elif_clause boolean_operator call identifier argument_list identifier attribute identifier identifier comparison_operator identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier return_statement identifier
This can be either a string or a numeric uid
def retry_failed(FailAdmin, request, queryset): for task in queryset: async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {}) task.delete()
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block expression_statement call identifier argument_list attribute identifier identifier list_splat boolean_operator attribute identifier identifier tuple keyword_argument identifier attribute identifier identifier dictionary_splat boolean_operator attribute identifier identifier dictionary expression_statement call attribute identifier identifier argument_list
Submit selected tasks back to the queue.
def wsp(word): HEAVY = r'[ieaAoO]{1}[\.]*(u|y)[^ieaAoO]+(\.|$)' delimiters = [i for i, char in enumerate(word) if char == '.'] if len(delimiters) % 2 != 0: delimiters.append(len(word)) unstressed = [] for i, d in enumerate(delimiters): if i % 2 == 0: unstressed.extend(range(d + 1, delimiters[i + 1])) heavies = re.finditer(HEAVY, word) violations = sum(1 for m in heavies if m.start(0) in unstressed) return violations
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier if_clause comparison_operator identifier string string_start string_content string_end if_statement comparison_operator binary_operator call identifier argument_list identifier integer integer block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator binary_operator identifier integer integer block expression_statement call attribute identifier identifier argument_list call identifier argument_list binary_operator identifier integer subscript identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier generator_expression integer for_in_clause identifier identifier if_clause comparison_operator call attribute identifier identifier argument_list integer identifier return_statement identifier
Return the number of unstressed heavy syllables.
def show_metadata_converter(self): from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) dialog = MetadataConverterDialog( parent=self.iface.mainWindow(), iface=self.iface, ) dialog.exec_()
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list
Show InaSAFE Metadata Converter.
def _cnvkit_fix(cnns, background_cnn, items, ckouts): return [_cnvkit_fix_base(cnns, background_cnn, items, ckouts)]
module function_definition identifier parameters identifier identifier identifier identifier block return_statement list call identifier argument_list identifier identifier identifier identifier
Normalize samples, correcting sources of bias.
def _get_cookies_as_dict(): config = ConfigParser.SafeConfigParser() config.read(_config) if config.has_section('cookies'): cookie_dict = {} for option in config.options('cookies'): option_key = option.upper() if option == 'jsessionid' else option cookie_dict[option_key] = config.get('cookies', option) return cookie_dict
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list comparison_operator identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier
Get cookies as a dict
def principal_unit(): principal_unit = os.environ.get('JUJU_PRINCIPAL_UNIT', None) if principal_unit == '': return os.environ['JUJU_UNIT_NAME'] elif principal_unit is not None: return principal_unit for reltype in relation_types(): for rid in relation_ids(reltype): for unit in related_units(rid): md = _metadata_unit(unit) if not md: continue subordinate = md.pop('subordinate', None) if not subordinate: return unit return None
module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier string string_start string_end block return_statement subscript attribute identifier identifier string string_start string_content string_end elif_clause comparison_operator identifier none block return_statement identifier for_statement identifier call identifier argument_list block for_statement identifier call identifier argument_list identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement not_operator identifier block return_statement identifier return_statement none
Returns the principal unit of this unit, otherwise None
def find_deck(provider: Provider, key: str, version: int, prod: bool=True) -> Optional[Deck]: pa_params = param_query(provider.network) if prod: p2th = pa_params.P2TH_addr else: p2th = pa_params.test_P2TH_addr rawtx = provider.getrawtransaction(key, 1) deck = deck_parser((provider, rawtx, 1, p2th)) return deck
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier true type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call identifier argument_list tuple identifier identifier integer identifier return_statement identifier
Find specific deck by deck id.
def _reset_changes(self): self._original = {} if self.last_updated is not None: self._original['last_updated'] = self.last_updated
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier
Stores current values for comparison later
def cached_generator(function): cache_variable = '_cached_' + function.__name__ @wraps(function) def function_wrapper(obj, *args, **kwargs): try: for item in getattr(obj, cache_variable): yield item except AttributeError: setattr(obj, cache_variable, []) cache = getattr(obj, cache_variable) for item in function(obj, *args, **kwargs): cache.append(item) yield item return function_wrapper
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block for_statement identifier call identifier argument_list identifier identifier block expression_statement yield identifier except_clause identifier block expression_statement call identifier argument_list identifier identifier list expression_statement assignment identifier call identifier argument_list identifier identifier for_statement identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement yield identifier return_statement identifier
Method decorator caching a generator's yielded items.
def summarize_sec2hdrgos(self, sec2d_hdrgos): hdrgos_all = set([]) hdrgos_grouped = set() hdrgos_ungrouped = set() sections_grouped = set() for sectionname, hdrgos in sec2d_hdrgos: self._chk_hdrgoids(hdrgos) hdrgos_all.update(hdrgos) if sectionname != HdrgosSections.secdflt: hdrgos_grouped.update(hdrgos) sections_grouped.add(sectionname) else: hdrgos_ungrouped.update(hdrgos) return {'G': hdrgos_grouped, 'S': sections_grouped, 'U': hdrgos_all.difference(hdrgos_grouped)}
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier
Get counts of header GO IDs and sections.
def initialize_path(self, path_num=None): self.state = copy(self.initial_state) return self.state
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier return_statement attribute identifier identifier
initialize consumer for next path
def log(array, cutoff): arr = numpy.copy(array) arr[arr < cutoff] = cutoff return numpy.log(arr)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier comparison_operator identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier
Compute the logarithm of an array with a cutoff on the small values
def OnLabelSizeIntCtrl(self, event): self.attrs["labelsize"] = event.GetValue() post_command_event(self, self.DrawChartMsg)
module function_definition identifier parameters identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier attribute identifier identifier
Label size IntCtrl event handler
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None: for key, value in meta.items(): if key in META_FIELDS: if type(value) is not META_FIELDS[key]: raise ValidationError( f"Values for {key} are expected to have the type {META_FIELDS[key]}, " f"instead got {type(value)}." ) elif allow_extra_meta_fields: if key[:2] != "x-": raise ValidationError( "Undefined meta fields need to begin with 'x-', " f"{key} is not a valid undefined meta field." ) else: raise ValidationError( f"{key} is not a permitted meta field. To allow undefined fields, " "set `allow_extra_meta_fields` to True." )
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type identifier type none block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block if_statement comparison_operator call identifier argument_list identifier subscript identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content interpolation identifier string_content interpolation subscript identifier identifier string_content string_end string string_start string_content interpolation call identifier argument_list identifier string_content string_end elif_clause identifier block if_statement comparison_operator subscript identifier slice integer string string_start string_content string_end block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start interpolation identifier string_content string_end else_clause block raise_statement call identifier argument_list concatenated_string string string_start interpolation identifier string_content string_end string string_start string_content string_end
Validates that every key is one of `META_FIELDS` and has a value of the expected type.
def to_json(self): if not self.is_data_loaded: self._import_data() def jsonify_dict(base_dict): new_dict = {} for key, val in base_dict.items(): new_dict[key] = val.to_json() return new_dict hot_wks = jsonify_dict(self.extreme_hot_weeks) cold_wks = jsonify_dict(self.extreme_cold_weeks) typ_wks = jsonify_dict(self.typical_weeks) grnd_temps = jsonify_dict(self.monthly_ground_temperature) return { 'location': self.location.to_json(), 'data_collections': [dc.to_json() for dc in self._data], 'metadata': self.metadata, 'heating_dict': self.heating_design_condition_dictionary, 'cooling_dict': self.cooling_design_condition_dictionary, 'extremes_dict': self.extreme_design_condition_dictionary, 'extreme_hot_weeks': hot_wks, 'extreme_cold_weeks': cold_wks, 'typical_weeks': typ_wks, "monthly_ground_temps": grnd_temps, "is_ip": self._is_ip, "is_leap_year": self.is_leap_year, "daylight_savings_start": self.daylight_savings_start, "daylight_savings_end": self.daylight_savings_end, "comments_1": self.comments_1, "comments_2": self.comments_2 }
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list return_statement identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier
Convert the EPW to a dictionary.
def exists(self, filename): client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/") if r.get("Contents") or r.get("CommonPrefixes"): return True return False
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block return_statement true return_statement false
Determines whether a path exists or not.
def asyncImap(asyncCallable, *iterables): deferreds = imap(asyncCallable, *iterables) return gatherResults(deferreds, consumeErrors=True)
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier return_statement call identifier argument_list identifier keyword_argument identifier true
itertools.imap for deferred callables
def _is_dataset(uri, config_path): uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) return storage_broker.has_admin_metadata()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list
Helper function for determining if a URI is a dataset.
def touch(filename, timestamp): if timestamp is not None: timestamp = (timestamp, timestamp) from os import utime utime(filename, timestamp)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier tuple identifier identifier import_from_statement dotted_name identifier dotted_name identifier expression_statement call identifier argument_list identifier identifier
set the mtime of a file
def _handle_wikilink_separator(self): self._context ^= contexts.WIKILINK_TITLE self._context |= contexts.WIKILINK_TEXT self._emit(tokens.WikilinkSeparator())
module function_definition identifier parameters identifier block expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Handle the separator between a wikilink's title and its text.
def write_dot(build_context, conf: Config, out_f): not_buildenv_targets = get_not_buildenv_targets(build_context) prebuilt_targets = get_prebuilt_targets(build_context) out_f.write('strict digraph {\n') for node in build_context.target_graph.nodes: if conf.show_buildenv_deps or node in not_buildenv_targets: cached = node in prebuilt_targets fillcolor = 'fillcolor="grey",style=filled' if cached else '' color = TARGETS_COLORS.get( build_context.targets[node].builder_name, 'black') out_f.write(' "{}" [color="{}",{}];\n'.format(node, color, fillcolor)) out_f.writelines(' "{}" -> "{}";\n'.format(u, v) for u, v in build_context.target_graph.edges if conf.show_buildenv_deps or (u in not_buildenv_targets and v in not_buildenv_targets)) out_f.write('}\n\n')
module function_definition identifier parameters identifier typed_parameter identifier type identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end for_statement identifier attribute attribute identifier identifier identifier block if_statement boolean_operator attribute identifier identifier comparison_operator identifier identifier block expression_statement assignment identifier comparison_operator identifier identifier expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute subscript attribute identifier identifier identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier generator_expression call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier attribute attribute identifier identifier identifier if_clause boolean_operator attribute identifier identifier parenthesized_expression boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end
Write build graph in dot format to `out_f` file-like object.
def generate_split_tsv_lines(fn, header): for line in generate_tsv_psms_line(fn): yield {x: y for (x, y) in zip(header, line.strip().split('\t'))}
module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list identifier block expression_statement yield dictionary_comprehension pair identifier identifier for_in_clause tuple_pattern identifier identifier call identifier argument_list identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end
Returns dicts with header-keys and psm statistic values
def __resize_surface_extents(self): self.__origin.X = self.image.get_width() * self.__untransformed_nor_origin.X self.__origin.Y = self.image.get_height() * self.__untransformed_nor_origin.Y self.source.width = self.image.get_width() self.source.height = self.image.get_height()
module function_definition identifier parameters identifier block expression_statement assignment attribute attribute identifier identifier identifier binary_operator call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier binary_operator call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier call attribute attribute identifier identifier identifier argument_list
Handles surface cleanup once a scale or rotation operation has been performed.
def create_consumer(self): with self.connection_pool.acquire(block=True) as conn: yield self.consumer(conn)
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true as_pattern_target identifier block expression_statement yield call attribute identifier identifier argument_list identifier
Context manager that yields an instance of ``Consumer``.
def parse(self, stream): lines = re.sub("[\r\n]+", "\n", stream.read()).split("\n") for line in lines: self.parseline(line)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Parse the given stream
def pull(self): repo_root = settings.REPO_ROOT pull_from_origin(join(repo_root, self.name))
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list call identifier argument_list identifier attribute identifier identifier
Pull from the origin.
def header_footer_exists(filepath): with open(filepath) as f: return re.search(Utils.exp, f.read())
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list
Check if directory-components is listed in requirements files.
def load(self, name, location='local'): path = self._get_path(name, location, file_ext='.json') if op.exists(path): return _load_json(path) path = self._get_path(name, location, file_ext='.pkl') if op.exists(path): return _load_pickle(path) logger.debug("The file `%s` doesn't exist.", path) return {}
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list identifier block return_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list identifier block return_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement dictionary
Load saved data from the cache directory.
def show(self, imgs, ax=None): ax = ax or plt.gca() if type(imgs) is not list: imgs = [imgs] for i, img in enumerate(imgs): ax.imshow(img, cmap=plt.get_cmap("plasma")) ax.axis("off")
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Visualize the persistence image
def pre_save(self, model_instance, add): file = getattr(model_instance, self.attname) if file and not file._committed: file.name = self._clean_file_name(model_instance, file.name) file.file = self._resize_image(model_instance, file) file.save(file.name, file, save=False) return file
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier if_statement boolean_operator identifier not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier false return_statement identifier
Resizes, commits image to storage, and returns field's value just before saving.
def make_rawr_zip_payload(rawr_tile, date_time=None): if date_time is None: date_time = gmtime()[0:6] buf = StringIO() with zipfile.ZipFile(buf, mode='w') as z: for fmt_data in rawr_tile.all_formatted_data: zip_info = zipfile.ZipInfo(fmt_data.name, date_time) z.writestr(zip_info, fmt_data.data, zipfile.ZIP_DEFLATED) return buf.getvalue()
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier subscript call identifier argument_list slice integer integer expression_statement assignment identifier call identifier argument_list with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list
make a zip file from the rawr tile formatted data
def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN, max_len=MAX_STRLEN, **kwargs): from syn.five import unichr return unicode(rand_str(min_char, max_char, min_len, max_len, unichr))
module function_definition identifier parameters default_parameter identifier identifier default_parameter identifier identifier default_parameter identifier identifier default_parameter identifier identifier dictionary_splat_pattern identifier block import_from_statement dotted_name identifier identifier dotted_name identifier return_statement call identifier argument_list call identifier argument_list identifier identifier identifier identifier identifier
For values in the unicode range, regardless of Python version.
def valid_project(self): try: path = self.projects.get_active_project_path() except AttributeError: return if bool(path): if not self.projects.is_valid_project(path): if path: QMessageBox.critical( self, _('Error'), _("<b>{}</b> is no longer a valid Spyder project! " "Since it is the current active project, it will " "be closed automatically.").format(path)) self.projects.close_project()
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list except_clause identifier block return_statement if_statement call identifier argument_list identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list string string_start string_content string_end call attribute call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Handle an invalid active project.
def build_system_error(cls, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(Status.SYSTEM_ERROR, errors)
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier conditional_expression list identifier not_operator call identifier argument_list identifier identifier identifier return_statement call identifier argument_list attribute identifier identifier identifier
Utility method to build a HTTP 500 System Error response
def create_reader(self, name, *args, **kwargs): self._check_format(name) return self._formats[name]['reader'](*args, **kwargs)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call subscript subscript attribute identifier identifier identifier string string_start string_content string_end argument_list list_splat identifier dictionary_splat identifier
Create a new reader instance for a given format.
def to_index_variable(self): return IndexVariable(self.dims, self._data, self._attrs, encoding=self._encoding, fastpath=True)
module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true
Return this variable as an xarray.IndexVariable
def max_pv_count(self): self.open() count = lvm_vg_get_max_pv(self.handle) self.close() return count
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Returns the maximum allowed physical volume count.
def postalCodeLookup(self, countryCode, postalCode): params = {"country": countryCode, "postalcode": postalCode} d = self._call("postalCodeLookupJSON", params) d.addCallback(operator.itemgetter("postalcodes")) return d
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
Looks up locations for this country and postal code.
def write(file_name, data): with open(file_name, 'w') as f: f.write(encode(data))
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier
Encode and write a Hip file.
def create_from_flux(cls, params, emin, emax, flux, scale=1.0): params = params.copy() params[0] = 1.0 params[0] = flux / cls.eval_flux(emin, emax, params, scale=scale) return cls(params, scale)
module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier float block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier integer float expression_statement assignment subscript identifier integer binary_operator identifier call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier
Create a spectral function instance given its flux.
def clear_canvas(self): self.fig = None self.fmt = None self._qpix_buffer = [] self.repaint()
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier list expression_statement call attribute identifier identifier argument_list
Clear the figure that was painted on the widget.
async def _process_lines(self, pattern: Optional[str] = None) -> None: if pattern is not None: cmp = re.compile(pattern) _LOGGER.debug("Start working with pattern '%s'.", pattern) while self.is_running: try: line = await self._input.readline() if not line: break line = line.decode() except Exception: break match = True if pattern is None else cmp.search(line) if match: _LOGGER.debug("Process: %s", line) await self._que.put(line) try: await self._loop.run_in_executor(None, self._proc.wait) finally: await self._que.put(None) _LOGGER.debug("Close read ffmpeg output.")
module function_definition identifier parameters identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier none type none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier while_statement attribute identifier identifier block try_statement block expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block break_statement expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block break_statement expression_statement assignment identifier conditional_expression true comparison_operator identifier none call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement await call attribute attribute identifier identifier identifier argument_list identifier try_statement block expression_statement await call attribute attribute identifier identifier identifier argument_list none attribute attribute identifier identifier identifier finally_clause block expression_statement await call attribute attribute identifier identifier identifier argument_list none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Read line from pipe they match with pattern.
def _find_colour(particle, start_index, screen_data): _, fg2, attr2, bg2 = screen_data index = start_index for i, colours in enumerate(particle.colours): if (fg2, attr2, bg2) == colours: index = i break return index
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier identifier expression_statement assignment identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator tuple identifier identifier identifier identifier block expression_statement assignment identifier identifier break_statement return_statement identifier
Helper function to find an existing colour in the particle palette.
def ec2_instances(): "Use the EC2 API to get a list of all machines" region = boto.ec2.get_region(REGION) reservations = region.connect().get_all_instances() instances = [] for reservation in reservations: instances += reservation.instances return instances
module function_definition identifier parameters block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block expression_statement augmented_assignment identifier attribute identifier identifier return_statement identifier
Use the EC2 API to get a list of all machines
def extendMarkdown(self, md, md_globals): md.parser.blockprocessors.add('table', TableProcessor(md.parser), '<hashheader')
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end
Add an instance of TableProcessor to BlockParser.
def _process(self, metric): if not self.enabled: return try: try: self.lock.acquire() self.process(metric) except Exception: self.log.error(traceback.format_exc()) finally: if self.lock.locked(): self.lock.release()
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement try_statement block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list finally_clause block if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list
Decorator for processing handlers with a lock, catching exceptions
def operations(self): ops = [] for e in self.expressions: if hasattr(e, 'op'): ops.append(e.op) return ops
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier
A list of all operations done by the IRSB, as libVEX enum names
def try_except_handler(self, node): excepted_types = [] for handler in node.handlers: if handler.type is None: excepted_types = None break if isinstance(handler.type, ast.Tuple): excepted_types.extend([exception_type for exception_type in handler.type.elts]) else: excepted_types.append(handler.type) new_exception_list = self.ignore_exceptions if self.ignore_exceptions is not None: if excepted_types is None: new_exception_list = None else: new_exception_list = list(set(excepted_types + self.ignore_exceptions)) old_exception_handlers, self.ignore_exceptions = \ self.ignore_exceptions, new_exception_list node.body = [self.visit(node_item) for node_item in node.body] self.ignore_exceptions = old_exception_handlers
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier none break_statement if_statement call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier none else_clause block expression_statement assignment identifier call identifier argument_list call identifier argument_list binary_operator identifier attribute identifier identifier expression_statement assignment pattern_list identifier attribute identifier identifier line_continuation expression_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier
Handler for try except statement to ignore excepted exceptions.
def _get_f2rx(self, C, r_x, r_1, r_2): drx = (r_x - r_1) / (r_2 - r_1) return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.))
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator identifier identifier return_statement binary_operator binary_operator subscript attribute identifier identifier string string_start string_content string_end parenthesized_expression binary_operator subscript identifier string string_start string_content string_end identifier parenthesized_expression binary_operator subscript identifier string string_start string_content string_end parenthesized_expression binary_operator identifier float
Defines the f2 scaling coefficient defined in equation 10
def run_pylint(self): if (self.get_option('save_before', True) and not self.main.editor.save()): return self.switch_to_plugin() self.analyze(self.main.editor.get_current_filename())
module function_definition identifier parameters identifier block if_statement parenthesized_expression boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end true not_operator call attribute attribute attribute identifier identifier identifier identifier argument_list block return_statement expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list
Run pylint code analysis
def docstring_with_summary(docstring, pairs, key_header, summary_type): return "\n".join( [docstring, "Summary of {}:".format(summary_type), ""] + summary_table(pairs, key_header) + [""] )
module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list binary_operator binary_operator list identifier call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_end call identifier argument_list identifier identifier list string string_start string_end
Return a string joining the docstring with the pairs summary table.
def dict_partial_cmp(target_dict, dict_list, ducktype): for called_dict in dict_list: if len(target_dict) > len(called_dict): continue intersection = {} for item in target_dict: dtype = ducktype(target_dict[item]) if hasattr(dtype, "mtest"): if item in called_dict and dtype.mtest(called_dict[item]): intersection[item] = target_dict[item] else: if item in called_dict and dtype == called_dict[item]: intersection[item] = target_dict[item] if intersection == target_dict: return True return False
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block continue_statement expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement boolean_operator comparison_operator identifier identifier call attribute identifier identifier argument_list subscript identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier else_clause block if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier subscript identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier if_statement comparison_operator identifier identifier block return_statement true return_statement false
Whether partial dict are in dict_list or not
def upload_file(request): if request.method == 'POST': form = MediaForm(request.POST, request.FILES) if form.is_valid(): context_dict = {} try: context_dict['copied_files'] = update_media_file( request.FILES['zip_file']) except Exception as e: context_dict['error_message'] = e.message return render(request, 'django_admin/transfer_media_message.html', context_dict) else: form = MediaForm() return render(request, 'django_admin/upload_media.html', {'form': form})
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier dictionary try_statement block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list identifier string string_start string_content string_end identifier else_clause block expression_statement assignment identifier call identifier argument_list return_statement call identifier argument_list identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier
Upload a Zip File Containing a single file containing media.
def parse_changelog(args: Any) -> Tuple[str, str]: with open("CHANGELOG.rst", "r") as file: match = re.match( pattern=r"(.*?Unreleased\n---+\n)(.+?)(\n*[^\n]+\n---+\n.*)", string=file.read(), flags=re.DOTALL, ) assert match header, changes, tail = match.groups() tag = "%s - %s" % (args.tag, datetime.date.today().isoformat()) tagged = "\n%s\n%s\n%s" % (tag, "-" * len(tag), changes) if args.verbose: print(tagged) return "".join((header, tagged, tail)), changes
module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier type identifier block with_statement with_clause with_item as_pattern call identifier argument_list string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier assert_statement identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence escape_sequence string_end tuple identifier binary_operator string string_start string_content string_end call identifier argument_list identifier identifier if_statement attribute identifier identifier block expression_statement call identifier argument_list identifier return_statement expression_list call attribute string string_start string_end identifier argument_list tuple identifier identifier identifier identifier
Return an updated changelog and and the list of changes.
def _mutect2_filter(broad_runner, in_file, out_file, ref_file): params = ["-T", "FilterMutectCalls", "--reference", ref_file, "--variant", in_file, "--output", out_file] return broad_runner.cl_gatk(params, os.path.dirname(out_file))
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier
Filter of MuTect2 calls, a separate step in GATK4.
def show_busy(self): self.progress_bar.show() self.question_group.setEnabled(False) self.question_group.setVisible(False) enable_busy_cursor() self.repaint() qApp.processEvents() self.busy = True
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list false expression_statement call attribute attribute identifier identifier identifier argument_list false expression_statement call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true
Hide the question group box and enable the busy cursor.
def do_gh(self, arg): if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.lastEvent: self.lastEvent.continueStatus = win32.DBG_EXCEPTION_HANDLED return self.do_go(arg)
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier
gh - go with exception handled
def start(self): self.publish_properties() self.subscribe_topics() gc.collect() self.set_state("ready") while True: try: if not utils.wlan.isconnected(): utils.wifi_connect() self.publish_data() self.mqtt.check_msg() idle() sleep(1) except KeyboardInterrupt: self.set_state("disconnected") self.mqtt.disconnect()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end while_statement true block try_statement block if_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list expression_statement call identifier argument_list integer except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list
publish device and node properties, run forever
def process_m2m_through_save(self, obj, created=False, **kwargs): if not created: return self._process_m2m_through(obj, 'post_add')
module function_definition identifier parameters identifier identifier default_parameter identifier false dictionary_splat_pattern identifier block if_statement not_operator identifier block return_statement expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end
Process M2M post save for custom through model.
def component_doi(soup): component_doi = [] object_id_tags = raw_parser.object_id(soup, pub_id_type = "doi") component_list = components(soup) position = 1 for tag in object_id_tags: component_object = {} component_object["doi"] = doi_uri_to_doi(tag.text) component_object["position"] = position for component in component_list: if "doi" in component and component["doi"] == component_object["doi"]: component_object["type"] = component["type"] component_doi.append(component_object) position = position + 1 return component_doi
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier for_statement identifier identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator identifier integer return_statement identifier
Look for all object-id of pub-type-id = doi, these are the component DOI tags
def generate(self, step, params): params = step.recurse(base.DictFactory, params, force_sequence=step.sequence) filename, content = self._make_content(params) return django_files.File(content.file, filename)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier
Fill in the field.
def on_max_tab_name_length_changed(self, spin): val = int(spin.get_value()) self.settings.general.set_int('max-tab-name-length', val) self.prefDlg.update_vte_subwidgets_states()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Changes the value of max_tab_name_length in dconf
def load_entry_point(self, group, name): ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load()
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple tuple identifier identifier return_statement call attribute identifier identifier argument_list
Return the `name` entry point of `group` or raise ImportError
def oplog_thread_join(self): LOG.info("MongoConnector: Stopping all OplogThreads") for thread in self.shard_set.values(): thread.join()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list
Stops all the OplogThreads
def composite_decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): total = [] for weight,iso in zip(self.weights,self.isochrones): subfunc = getattr(iso,func.__name__) total.append(weight*subfunc(*args,**kwargs)) return np.sum(total,axis=0) return wrapper
module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier call identifier argument_list list_splat identifier dictionary_splat identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier integer return_statement identifier
Decorator for wrapping functions that calculate a weighted sum
def s_demand(self, bus): Svl = array([complex(g.p, g.q) for g in self.generators if (g.bus == bus) and g.is_load], dtype=complex64) Sd = complex(bus.p_demand, bus.q_demand) return -sum(Svl) + Sd
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list list_comprehension call identifier argument_list attribute identifier identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator parenthesized_expression comparison_operator attribute identifier identifier identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier return_statement binary_operator unary_operator call identifier argument_list identifier identifier
Returns the total complex power demand.
def generate_megaman_manifold(sampling=2, nfolds=2, rotate=True, random_state=None): X, c = generate_megaman_data(sampling) for i in range(nfolds): X = np.hstack([_make_S_curve(x) for x in X.T]) if rotate: rand = check_random_state(random_state) R = rand.randn(X.shape[1], X.shape[1]) U, s, VT = np.linalg.svd(R) X = np.dot(X, U) return X, c
module function_definition identifier parameters default_parameter identifier integer default_parameter identifier integer default_parameter identifier true default_parameter identifier none block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier integer subscript attribute identifier identifier integer expression_statement assignment pattern_list identifier identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement expression_list identifier identifier
Generate a manifold of the megaman data
def focus_prev_sibling(self): mid = self.get_selected_mid() localroot = self._sanitize_position((mid,)) if localroot == self.get_focus()[1]: newpos = self._tree.prev_sibling_position(mid) if newpos is not None: newpos = self._sanitize_position((newpos,)) else: newpos = localroot if newpos is not None: self.body.set_focus(newpos)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier if_statement comparison_operator identifier subscript call attribute identifier identifier argument_list integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier else_clause block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier
focus previous sibling of currently focussed message in thread tree
def _nested_lookup(document, references, operation): if isinstance(document, list): for d in document: for result in NestedLookup._nested_lookup(d, references, operation): yield result if isinstance(document, dict): for k, v in document.items(): if operation(k, v): references.append((document, k)) yield v elif isinstance(v, dict): for result in NestedLookup._nested_lookup(v, references, operation): yield result elif isinstance(v, list): for d in v: for result in NestedLookup._nested_lookup(d, references, operation): yield result
module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block for_statement identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier identifier block expression_statement yield identifier if_statement call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier expression_statement yield identifier elif_clause call identifier argument_list identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier identifier block expression_statement yield identifier elif_clause call identifier argument_list identifier identifier block for_statement identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier identifier block expression_statement yield identifier
Lookup a key in a nested document, yield a value
def translate_escaped_str(cls, str_val): if isinstance(str_val, string_types): str_val = str_val.encode('unicode_escape') if sys.version_info >= (3, 0): str_val = str_val.decode('utf-8') str_val = str_val.replace('"', r'\"') return '"{}"'.format(str_val)
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier tuple integer integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement call attribute string string_start string_content string_end identifier argument_list identifier
Reusable by most interpreters
def _get_backends(): backends = [] backend_paths = getattr( settings, 'MAMA_CAS_SERVICE_BACKENDS', ['mama_cas.services.backends.SettingsBackend'] ) for backend_path in backend_paths: backend = import_string(backend_path)() backends.append(backend) return backends
module function_definition identifier parameters block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call call identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Retrieve the list of configured service backends.