code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList: return getElementsBy(self, cond)
module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type list identifier type identifier type identifier block return_statement call identifier argument_list identifier identifier
Get elements in this document which matches condition.
def block_header_verify( block_data, prev_hash, block_hash ): serialized_header = block_header_to_hex( block_data, prev_hash ) candidate_hash_bin_reversed = hashing.bin_double_sha256(binascii.unhexlify(serialized_header)) candidate_hash = binascii.hexlify( candidate_hash_bin_reversed[::-1] ) return bloc...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argume...
Verify whether or not bitcoind's block header matches the hash we expect.
def simple_state_machine(): from random import random from furious.async import Async number = random() logging.info('Generating a number... %s', number) if number > 0.25: logging.info('Continuing to do stuff.') return Async(target=simple_state_machine) return number
module function_definition identifier parameters block import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifie...
Pick a number, if it is more than some cuttoff continue the chain.
def action(cls, view): name = "%s:%s" % (cls.name, view.__name__) path = "%s/%s" % (cls.url, view.__name__) cls.actions.append((view.__doc__, path)) return cls.register(path, name=name)(view)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator string st...
Register admin view action.
def guess_mode(self, data): if data.ndim == 2: return "L" elif data.shape[-1] == 3: return "RGB" elif data.shape[-1] == 4: return "RGBA" else: raise ValueError( "Un-supported shape for image conversion %s" % list(data.shape)...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier integer block return_statement string string_start string_content string_end elif_clause comparison_operator subscript attribute identifier identifier unary_operator integer inte...
Guess what type of image the np.array is representing
def init_drivers(enable_debug_driver=False): for driver in DRIVERS: try: if driver != DebugDriver or enable_debug_driver: CLASSES.append(driver) except Exception: continue
module function_definition identifier parameters default_parameter identifier false block for_statement identifier identifier block try_statement block if_statement boolean_operator comparison_operator identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identif...
Initialize all the drivers.
def warn_disabled(scraperclass, reasons): out.warn(u"Skipping comic %s: %s" % (scraperclass.getName(), ' '.join(reasons.values())))
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list call attribute string string_start string_content st...
Print warning about disabled comic modules.
def add_letter_to_axis(ax, let, col, x, y, height): if len(let) == 2: colors = [col, "white"] elif len(let) == 1: colors = [col] else: raise ValueError("3 or more Polygons are not supported") for polygon, color in zip(let, colors): new_polygon = affinity.scale( ...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier list identifier string string_start string_content string_end elif_c...
Add 'let' with position x,y and height height to matplotlib axis 'ax'.
def source_pipe(self, source, ps=None): if isinstance(source, string_types): source = self.source(source) source.dataset = self.dataset source._bundle = self iter_source, source_pipe = self._iterable_source(source, ps) if self.limited_run: source_pipe.limi...
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment a...
Create a source pipe for a source, giving it access to download files to the local cache
def ReadAllClientActionRequests(self, client_id, cursor=None): query = ("SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, " "leased_count " "FROM client_action_requests " "WHERE client_id = %s") cursor.execute(query, [db_utils.ClientIDToInt(client_id)]) ret = [...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_co...
Reads all client messages available for a given client_id.
def _getUE4BuildInterrogator(self): ubtLambda = lambda target, platform, config, args: self._runUnrealBuildTool(target, platform, config, args, True) interrogator = UE4BuildInterrogator(self.getEngineRoot(), self._getEngineVersionDetails(), self._getEngineVersionHash(), ubtLambda) return interrogator
module function_definition identifier parameters identifier block expression_statement assignment identifier lambda lambda_parameters identifier identifier identifier identifier call attribute identifier identifier argument_list identifier identifier identifier identifier true expression_statement assignment identifier...
Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details
def text(value, encoding="utf-8", errors="strict"): if isinstance(value, text_type): return value elif isinstance(value, bytes): return text_type(value, encoding, errors) else: return text_type(value)
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block return_statement identifier elif_...
Convert a value to str on Python 3 and unicode on Python 2.
def check_section(node, section, keys=None): if keys: for key in keys: if key not in node: raise ValueError('Missing key %r inside %r node' % (key, section))
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement identifier block for_statement identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list binary_operator string string_...
Validate keys in a section
async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier await call attribute ...
Helper to create a cursor and execute the given multiquery.
def exclude_fields(obj, exclude=EXCLUDE): return dict([(k, getattr(obj, k)) for k in obj.__slots__ if k not in exclude])
module function_definition identifier parameters identifier default_parameter identifier identifier block return_statement call identifier argument_list list_comprehension tuple identifier call identifier argument_list identifier identifier for_in_clause identifier attribute identifier identifier if_clause comparison_o...
Return dict of object without parent attrs.
def highlightBlock(self, text): for expression, nth, format in self.rules: index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(nth) length = len(expression.cap(nth)) self.setFormat(index, length, format) ...
module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer while_statement comparison_opera...
Apply syntax highlighting to the given block of text.
def soviet_checksum(code): def sum_digits(code, offset=1): total = 0 for digit, index in zip(code[:7], count(offset)): total += int(digit) * index summed = (total / 11 * 11) return total - summed check = sum_digits(code, 1) if check == 10: check = sum_digi...
module function_definition identifier parameters identifier block function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier integer for_statement pattern_list identifier identifier call identifier argument_list subscript identifier slice i...
Courtesy of Sir Vlad Lavrov.
def signature(self): if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): greedy = isinstance(param.annotation, converters._Greedy) if param....
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block return_stat...
Returns a POSIX-like signature useful for help command output.
def error_message_and_exit(message, error_result): if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier integer ex...
Prints error messages in blue, the failed task result and quits.
def query(self, titles, pageids=None, cparams=None): query = self.QUERY.substitute( WIKI=self.uri, ENDPOINT=self.endpoint, TITLES=safequote(titles) or pageids) status = titles or pageids if pageids and not titles: query = query.replace('&titles=', ...
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier ...
Returns MediaWiki action=query query string
def sampleLocation(self): areaRatio = self.radius / (self.radius + self.height) if random.random() < areaRatio: return self._sampleLocationOnDisc() else: return self._sampleLocationOnSide()
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier if_statement comparison_operator call attribute identifier...
Simple method to sample uniformly from a cylinder.
def effect_info(self, mechanism, purview): return repertoire_distance( Direction.EFFECT, self.effect_repertoire(mechanism, purview), self.unconstrained_effect_repertoire(purview) )
module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier
Return the effect information for a mechanism over a purview.
def focus_prev(self): mid = self.get_selected_mid() localroot = self._sanitize_position((mid,)) if localroot == self.get_focus()[1]: newpos = self._tree.prev_position(mid) if newpos is not None: newpos = self._sanitize_position((newpos,)) else: ...
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 subsc...
focus previous message in depth first order
def _publish_match(self, publish, names=False, name_only=False): if names: for name in names: if not name_only and isinstance(name, re._pattern_type): if re.match(name, publish.name): return True else: op...
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block if_statement identifier block for_statement identifier identifier block if_statement boolean_operator not_operator identifier call identifier argument_list identifier attrib...
Check if publish name matches list of names or regex patterns
def deprecate_module_attribute(mod, deprecated): deprecated = set(deprecated) class Wrapper(object): def __getattr__(self, attr): if attr in deprecated: warnings.warn("Property %s is deprecated" % attr) return getattr(mod, attr) def __setattr__(self, attr,...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier class_definition identifier argument_list identifier block function_definition identifier parameters identifier identifier block if_statement comparison_operat...
Return a wrapped object that warns about deprecated accesses
def _validate_desc(self, desc): if desc is None: return desc if not isinstance(desc, STRING_TYPES): raise TypeError( "predicate description for Matching must be a string, " "got %r" % (type(desc),)) if not IS_PY3 and isinstance(desc, unicod...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator concatenated_s...
Validate the predicate description.
def to_dict(self): d = super(WaitTime, self).to_dict() d['condition'] = {'waitTime': {'waitTime': self.wait_time}} return d
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair stri...
Save this wait_time condition into a dictionary.
def step(self, **kwargs): kwargs.setdefault('linestyle', kwargs.pop('where', 'steps-post')) data = self.append(self.value[-1:], inplace=False) return data.plot(**kwargs)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement 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 str...
Create a step plot of this series
def walk_commands(self): for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement yield identifier if_statement call identifier argument_list identifier identifier block expression_s...
An iterator that recursively walks through all commands and subcommands.
def _note_reply_pending(self, option, state): if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].reply_pending = state
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list ex...
Record the status of requested Telnet options.
def initialize_weights_nn(data, means, lognorm=True): genes, cells = data.shape k = means.shape[1] if lognorm: data = log1p(cell_normalize(data)) for i in range(cells): for j in range(k): pass
module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier integer if_statement iden...
Initializes the weights with a nearest-neighbor approach using the means.
def add_f77_to_env(env): try: F77Suffixes = env['F77FILESUFFIXES'] except KeyError: F77Suffixes = ['.f77'] try: F77PPSuffixes = env['F77PPFILESUFFIXES'] except KeyError: F77PPSuffixes = [] DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes)
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier list string string_start string_content string_end...
Add Builders and construction variables for f77 to an Environment.
def current_state(self): field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(field_name, getattr(self, field_name)) for field_name in field_names])
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement list_comprehension call attribute identifier identifier argument_list attribute identifier identifier for_in_clause identifier attribute attribute identifier id...
Returns a ``field -> value`` dict of the current state of the instance.
def read_large_int(self, bits, signed=True): return int.from_bytes( self.read(bits // 8), byteorder='little', signed=signed)
module function_definition identifier parameters identifier identifier default_parameter identifier true block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator identifier integer keyword_argument identifier string string_start string_...
Reads a n-bits long integer value.
def dispatch(argdict): cmd = argdict['command'] ftc = getattr(THIS_MODULE, 'do_'+cmd) ftc(argdict)
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_en...
Call the command-specific function, depending on the command.
def cursor(self): if self._cursor is None: self._cursor = self.cursor_class(self, self.get_initial_elements()) return self._cursor
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list r...
Cache and return cursor_class instance
def full_redraw(self): self.left.draw_statuses(self.statuses, self.selected) self.right.draw(self.get_selected_status()) self.header.draw(self.user) self.draw_footer_status()
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call...
Perform a full redraw of the UI.
def plot_memory(calc_id=-1): dstore = util.read(calc_id) plots = [] for task_name in dstore['task_info']: mem = dstore['task_info/' + task_name]['mem_gb'] plots.append((task_name, mem)) plt = make_figure(plots) plt.show()
module function_definition identifier parameters default_parameter identifier unary_operator integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier subscript identifier string string_...
Plot the memory occupation
def complete_get(self, text, line, begidx, endidx): options = self.GET_OPTS if not text: completions = options else: completions = [f for f in options if f.startswith(text) ] return c...
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block expression_statement assignment identifier identifier else_clause block expression_statement...
completion for find command
def _get_dependencies_from_cache(ireq): if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"): return if ireq.editable: return try: deps = DEPENDENCY_CACHE[ireq] pyrq = REQUIRES_PYTHON_CACHE[ireq] except KeyError: return try: packaging.specifiers.SpecifierSet(...
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement if_statement attribute identifier identifier block return_statement try_statement block expression_s...
Retrieves dependencies for the requirement from the dependency cache.
def silence(self): sys.stdout = open(os.devnull, 'w') sys.stderr = open(os.devnull, 'w')
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier ar...
Route all stdout to null.
def govuk_template(context: Context, version='0.23.0', replace_fonts=True): if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')): return url = 'https://github.com/alphagov/govuk_template/releases' \ '/download/v{0}/django_govuk_template-{0}.tgz'.format(version) try: ...
module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true block if_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_lis...
Installs GOV.UK template
def fetch_libcapnp(savedir, url=None): is_preconfigured = False if url is None: url = libcapnp_url is_preconfigured = True dest = pjoin(savedir, 'capnproto-c++') if os.path.exists(dest): info("already have %s" % dest) return fname = fetch_archive(savedir, url, libcapn...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier false if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier true expression_sta...
download and extract libcapnp
def iter_xCharts(self): plot_tags = ( qn('c:area3DChart'), qn('c:areaChart'), qn('c:bar3DChart'), qn('c:barChart'), qn('c:bubbleChart'), qn('c:doughnutChart'), qn('c:line3DChart'), qn('c:lineChart'), qn('c:ofPieChart'), qn('c:pie3DChart'), qn('c:pieChart'), qn('c:...
module function_definition identifier parameters identifier block expression_statement assignment identifier tuple call identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end call identifier argument_list string string_start str...
Generate each xChart child element in document.
def build_table(self, table, force=False): sources = self._resolve_sources(None, [table]) for source in sources: self.build_source(None, source, force=force) self.unify_partitions()
module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list none list identifier for_statement identifier identifier block expression_statement call attribute identifier iden...
Build all of the sources for a table
def _create_worker(self, method, *args, **kwargs): thread = QThread() worker = RequestsDownloadWorker(method, args, kwargs) worker.moveToThread(thread) worker.sig_finished.connect(self._start) self._sig_download_finished.connect(worker.sig_download_finished) self._sig_dow...
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier identifie...
Create a new worker instance.
def _fetch_result(self): self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier
Fetch the queried object.
def _load_result(response, ret): if response['code'] is None: ret['comment'] = response['content'] elif response['code'] == 401: ret['comment'] = '401 Forbidden: Authentication required!' elif response['code'] == 404: ret['comment'] = response['content']['message'] elif response[...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end none block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string strin...
format the results of listing functions
def fit_for_distance(self): for prop in self.properties.keys(): if prop in self.ic.bands: return True return False
module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block return_statement true return_statement false
``True`` if any of the properties are apparent magnitudes.
def allParses(self,meter=None,include_bounded=False,one_per_meter=True): meter=self.get_meter(meter) try: parses=self.__parses[meter.id] if one_per_meter: toreturn=[] for _parses in parses: sofar=set() _parses2=[] for _p in _parses: _pm=_p.str_meter() if not _pm in sofar: ...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block expression_statement assig...
Return a list of lists of parses.
def cmd_repeat(self, args): if len(args) == 0: if len(self.repeats) == 0: print("No repeats") return for i in range(len(self.repeats)): print("%u: %s" % (i, self.repeats[i])) return if args[0] == 'add': if le...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call identifier argument_...
repeat a command at regular intervals
def prune_to_subset(self, subset, inplace=False): if not subset.issubset(self.labels): print('"subset" is not a subset') return if not inplace: t = self.copy() else: t = self t._tree.retain_taxa_with_labels(subset) t._tree.encode_bi...
module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_...
Prunes the Tree to just the taxon set given in `subset`
def WriteMessagesFile(file_descriptor, package, version, printer): _WriteFile(file_descriptor, package, version, _Proto2Printer(printer))
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list identifier identifier identifier call identifier argument_list identifier
Write the given extended file descriptor to out as a message file.
def filtered(self, efilter): if not self.params: self.params={'filter' : efilter} return self if not self.params.has_key('filter'): self.params['filter'] = efilter return self self.params['filter'].update(efilter) return self
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier dictionary pair string string_start string_content string_end identifier return_statement identifier if_statement n...
Applies a filter to the search
def rank(self): rank = re.findall(r'\d+', self._rank) if len(rank) == 0: return None return rank[0]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer ...
Returns an ``int`` of the team's rank at the time the game was played.
def _dfs(self, visited): if self not in visited: visited.add(self) for successor in self._children + self._followOns: successor._dfs(visited)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier binary_operator attribute identifier identifier attribute identifier ident...
Adds the job and all jobs reachable on a directed path from current node to the given set.
def slow_minimum_distance2(hull_a, hull_b): d2_min = np.iinfo(int).max for a in hull_a: if within_hull(a, hull_b): return 0 for b in hull_b: if within_hull(b, hull_a): return 0 for pt_a in hull_a: for pt_b in hull_b: d2_min = min(d2_min, np.sum...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block retu...
Do the minimum distance by exhaustive examination of all points
def _format_metric_name(self, m_name, cfunc): try: aggr = CFUNC_TO_AGGR[cfunc] except KeyError: aggr = cfunc.lower() try: m_name = CACTI_TO_DD[m_name] if aggr != 'avg': m_name += '.{}'.format(aggr) return m_name ...
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier subscript identifier identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statemen...
Format a cacti metric name into a Datadog-friendly name
def linreg_ols_qr(y, X): import numpy as np try: q, r = np.linalg.qr(np.dot(X.T, X)) return np.dot(np.dot(np.linalg.inv(r), q.T), np.dot(X.T, y)) except np.linalg.LinAlgError: print("LinAlgError: Factoring failed") return None
module function_definition identifier parameters identifier identifier block import_statement aliased_import dotted_name identifier identifier try_statement block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list call attribute ide...
Linear Regression, OLS, inverse by QR Factoring
def shelve(self): logger.info('creating shelve data') fname = str(self.create_path.absolute()) inst = sh.open(fname, writeback=self.writeback) self.is_open = True return inst
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argum...
Return an opened shelve object.
def ValidateIapJwt(iap_jwt, expected_audience): try: key_id = jwt.get_unverified_header(iap_jwt).get("kid") if not key_id: raise IAPValidationFailedError("No key ID") key = GetIapKey(key_id) decoded_jwt = jwt.decode( iap_jwt, key, algorithms=["ES256"], audience=expected_audience) ret...
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end if_statement not_operator identi...
Validates an IAP JWT.
def until_synced(self, timeout=None): futures = [r.until_synced(timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list attribute identifier...
Return a tornado Future; resolves when all subordinate clients are synced
def data_children(self) -> List["DataNode"]: res = [] for child in self.children: if isinstance(child, DataNode): res.append(child) elif not isinstance(child, SchemaTreeNode): res.extend(child.data_children()) return res
module function_definition identifier parameters identifier type generic_type identifier type_parameter type string string_start string_content string_end block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement call identifier argument_list ident...
Return the set of all data nodes directly under the receiver.
def insert_right(self, item): 'Insert a new item. If equal keys are found, add to the right' k = self._key(item) i = bisect_right(self._keys, k) self._keys.insert(i, k) self._items.insert(i, item)
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_lis...
Insert a new item. If equal keys are found, add to the right
def centroid(self): if self.v is None: raise ValueError('Mesh has no vertices; centroid is not defined') return np.mean(self.v, axis=0)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list attribute identifi...
Return the geometric center.
def clean(self): super(CTENode, self).clean() if self.parent and self.pk in getattr(self.parent, self._cte_node_path): raise ValidationError(_("A node cannot be made a descendant of itself."))
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier call identifier argument_li...
Prevents cycles in the tree.
def reset_all(self, suppress_logging=False): pool_names = list(self.pools) for name in pool_names: self.reset(name, suppress_logging)
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list ...
iterates thru the list of established connections and resets them by disconnecting and reconnecting
def publish(self, topic, message): self.connect() log.info('publish {}'.format(message)) self.client.publish(topic, message)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list id...
Publish an MQTT message to a topic.
def create_writer(self, name, *args, **kwargs): self._check_format(name) return self._formats[name]['writer'](*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 st...
Create a new writer instance for a given format.
def extern_store_i64(self, context_handle, i64): c = self._ffi.from_handle(context_handle) return c.to_value(i64)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier
Given a context and int32_t, return a new Handle to represent the int32_t.
def letter_set(self): end_str = ctypes.create_string_buffer(MAX_CHARS) cgaddag.gdg_letter_set(self.gdg, self.node, end_str) return [char for char in end_str.value.decode("ascii")]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier re...
Return the letter set of this node.
def flush(self): keys = list(self.keys()) if keys: return self.database.delete(*keys)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement identifier block return_statement call attribute attribute identifier identifier identifier argument_list list_splat ...
Remove all cached objects from the database.
def _is_ctype(self, ctype): if not self.valid: return False mime = self.content_type return self.ContentMimetypes.get(mime) == ctype
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement false expression_statement assignment identifier attribute identifier identifier return_statement comparison_operator call attribute attribute identifier identifi...
Return True iff content is valid and of the given type.
def main(): name = os.path.splitext(os.path.basename(__file__))[0] logging.basicConfig( format="%(asctime)s [%(process)s] %(levelname)s {} - %(message)s".format(name), level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--edges", metavar="FILENA...
module function_definition identifier parameters block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier integer expression_statement call attribute identifier id...
Main interface function for the command line.
def _add_unknown_char(self, string): if self.has_xvowel: self._promote_solitary_xvowel() self.unknown_char = string self._flush_char()
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifie...
Adds an unknown character to the stack.
def vfolders(access_key): fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Last Used', 'last_used'), ('Max Files', 'max_files'), ('Max Size', 'max_size'), ] if access_key is None: q = 'query { vfolders { $fields } }' else: q = 'query($a...
module function_definition identifier parameters identifier block expression_statement assignment identifier list tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end string string_start string_content string_end tuple stri...
List and manage virtual folders.
def elements(self): elements = [] for el in ct: if isinstance(el[1], datapoint.Element.Element): elements.append(el[1]) return elements
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement call identifier argument_list subscript identifier integer attribute attribute identifier identifier identifier block expression_statement call attribu...
Return a list of the elements which are not None
def as_dict(self): if hasattr(self, 'cust_dict'): return self.cust_dict if hasattr(self, 'attr_check'): self.attr_check() cls_bltns = set(dir(self.__class__)) return {a: getattr(self, a) for a in dir(self) if a not in cls_bltns}
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement attribute identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end...
returns an dict version of the object, based on it's attributes
def username(self): if self._username is None: if self.has_logged_in: self._username = self._get_username() else: raise AuthenticationError('Not logged in.') return self._username
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list else_clause ...
Username of the current API user
def load(filename: str, format: str = None): path = Path(filename).resolve() with path.open() as file: data = file.read() if format is None: loader, error_class = _load_autodetect, InvalidMofileFormat else: try: loader, error_class = formats[format] except Key...
module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list with_statement with_clause with_item as_pa...
Load a task file and get a ``Project`` back.
def block_events(self): BaseObject.block_events(self) for i in range(self._widget.topLevelItemCount()): self._widget.topLevelItem(i).param.blockSignals(True) return self
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute at...
Special version of block_events that loops over all tree elements.
def count_documents(self, filter={}, *args, **kwargs): result = self.collection.count_documents(filter, *args, **kwargs) return result
module function_definition identifier parameters identifier default_parameter identifier dictionary list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier list_splat identifier ...
Count all the documents in a collection accurately
def path(self): if self.parent: try: parent_path = self.parent.path.encode() except AttributeError: parent_path = self.parent.path return os.path.join(parent_path, self.name) return b"/"
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list except_clause identifier block expression_state...
Node's relative path from the root node
def __parseResponse(self, result): response = [] for data in result['data'] : result_dict={} for k,v in data.items() : column = self.getOutputColumn(k) if column != None: type = column.getSqlColumnType() if t...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier dictionary for_statement pattern_list identifier ident...
Parses the server response.
def insert_function(self, fname, ftype): "Inserts a new function" index = self.insert_id(fname, SharedData.KINDS.FUNCTION, [SharedData.KINDS.GLOBAL_VAR, SharedData.KINDS.FUNCTION], ftype) self.table[index].set_attribute("Params",0) return index
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier list at...
Inserts a new function
def _write_conf_file(): with open(CONF_FILE, "w") as f: f.write(DEFAULT_PROFTPD_CONF) logger.debug("'%s' created.", CONF_FILE)
module function_definition identifier parameters 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 identifier expression_s...
Write configuration file as it is defined in settings.
def window_from_array(array): from ...utils.lal import (find_typed_function) dtype = array.dtype seq = find_typed_function(dtype, 'Create', 'Sequence')(array.size) seq.data = array return find_typed_function(dtype, 'Create', 'WindowFromSequence')(seq)
module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call call identifier argume...
Convert a `numpy.ndarray` into a LAL `Window` object
def options(self): config = self._config o = {} o.update(self._default_smtp_options) o.update(self._default_message_options) o.update(self._default_backend_options) o.update(get_namespace(config, 'EMAIL_', valid_keys=o.keys())) o['port'] = int(o['port']) o...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement ...
Reads all EMAIL_ options and set default values.
def month_crumb(date): year = date.strftime('%Y') month = date.strftime('%m') month_text = DateFormat(date).format('F').capitalize() return Crumb(month_text, reverse('zinnia:entry_archive_month', args=[year, month]))
module function_definition identifier parameters identifier 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 ...
Crumb for a month.
def _heuristic_bin_width(obs): IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25) N = len(obs) return 2*IQR*N**(-1/3)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier integer call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call identif...
Optimal histogram bin width based on the Freedman-Diaconis rule
def _doc_property(klass, prop): header = "{klass}.{name}".format(klass=klass.__name__, name=_name(prop), ) docstring = _doc(prop) return _concat(header, docstring)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_l...
Generate the docstring of a property.
def resolveSystem(self, sysID): ret = libxml2mod.xmlACatalogResolveSystem(self._o, sysID) return ret
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier return_statement identifier
Try to lookup the catalog resource for a system ID
def random_secret() -> Secret: while True: secret = os.urandom(32) if secret != constants.EMPTY_HASH: return Secret(secret)
module function_definition identifier parameters type identifier block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list integer if_statement comparison_operator identifier attribute identifier identifier block return_statement call identifier argum...
Return a random 32 byte secret except the 0 secret since it's not accepted in the contracts
def df(self, qname_predicates:bool=False, keep_variable_type:bool=True) -> pd.DataFrame: local_df = self.df.copy() if qname_predicates: for col in self.columns: local_df.rename({col: self.g.qname(col)}) if not keep_variable_type: pass return local_...
module function_definition identifier parameters identifier typed_default_parameter identifier type identifier false typed_default_parameter identifier type identifier true type attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier arg...
Multi funcitonal DataFrame with settings
def list_users(self, envs=[], query="/users/"): juicer.utils.Log.log_debug( "List Users In: %s", ", ".join(envs)) for env in envs: juicer.utils.Log.log_info("%s:" % (env)) _r = self.connectors[env].get(query) if _r.status_code == Constants.PULP_GET_OK:...
module function_definition identifier parameters identifier default_parameter identifier list default_parameter identifier string string_start string_content string_end block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_cont...
List users in specified environments
def wrap_function(func): if is_text(func): return compile_expression(func) numarg = func.__code__.co_argcount if numarg == 0: def temp(row, rownum, rows): return func() return temp elif numarg == 1: def temp(row, rownum, rows): return func(row) ...
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier block return_statement call identifier argument_list identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identif...
RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH
def add_data_files(*include_dirs): 'called from setup.py in skeleton projects' data_files = [] for include_dir in include_dirs: for root, directories, filenames in os.walk(include_dir): include_files = [] for filename in filenames: if filename.endswith('.local...
module function_definition identifier parameters list_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block for_statement pattern_list identifier identifier identifier call attribute ide...
called from setup.py in skeleton projects
def dump_pytorch_graph(graph): f = "{:25} {:40} {} -> {}" print(f.format("kind", "scopeName", "inputs", "outputs")) for node in graph.nodes(): print(f.format(node.kind(), node.scopeName(), [i.unique() for i in node.inputs()], [i.unique() for i in node....
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_sta...
List all the nodes in a PyTorch graph.
def cut(list_, index=0): if isinstance(index, int): cut_ = lambda x: x[index] else: cut_ = lambda x: getattr(x, index) return list(map(cut_, list_))
module function_definition identifier parameters identifier default_parameter identifier integer block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier lambda lambda_parameters identifier subscript identifier identifier else_clause block expression_statem...
Cut a list by index or arg
def to_type(cls, typename): NAME_TYPES = {cls.TYPE_NAMES[x]: x for x in cls.TYPE_NAMES} return NAME_TYPES.get(typename, None)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary_comprehension pair subscript attribute identifier identifier identifier identifier for_in_clause identifier attribute identifier identifier return_statement call attribute identifier identi...
Converts a type ID to name. On error returns None