Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
364,400
def process_response(self, req, resp, resource): if not resource and resp.status == falcon.HTTP_404: abort(exceptions.RouteNotFound) elif resp.status == falcon.HTTP_405: abort(exceptions.MethodNotAllowed)
Post-processing of the response (after routing). Some fundamental errors can't be intercepted any other way in Falcon. These include 404 when the route isn't found & 405 when the method is bunk. Falcon will try to send its own errors. In these cases, intercept them & replace th...
364,401
def search(searchList, matchStr, numSyllables=None, wordInitial=, wordFinal=, spanSyllable=, stressedSyllable=, multiword=, pos=None): okonlynoDFSVNR matchStr = _prepRESearchStr(matchStr, wordInitial, wordFinal, spanSyllable, stressedSyllable) ...
Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible...
364,402
def cut_action_callback(self, *event): if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None: _, dict_paths = self.get_view_selection() stored_data_list = [] for dict_path_as_list in dict_paths: if dict_path_as_list:...
Add a copy and cut all selected row dict value pairs to the clipboard
364,403
def _merge_relative_path(dst_path, rel_path): norm_rel_path = os.path.normpath(rel_path.lstrip("/")) if norm_rel_path == ".": return dst_path if norm_rel_path.startswith(".."): raise ValueError("Relative path %r is invalid." % rel_path) merged = os.path.join(dst_path, norm_rel_path) ...
Merge a relative tar file to a destination (which can be "gs://...").
364,404
def groupIcon( cls, groupName, default = None ): if ( cls._groupIcons is None ): cls._groupIcons = {} if ( not default ): default = projexui.resources.find() return cls._groupIcons.get(nativestring(groupName), default)
Returns the icon for the inputed group name. :param groupName | <str> default | <str> || None :return <str>
364,405
def _get_stddevs(self, stddev_types, pgv): assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(pgv) std[pgv <= 25] = 0.20 idx = (pgv > 25) & (pgv <= 50) std[idx] = 0.20 - 0.05 * (pgv[...
Return standard deviations as defined in equation 3.5.5-1 page 151
364,406
def preview(klass, account, **kwargs): params = {} params.update(kwargs) if in params and isinstance(params[], list): params[] = .join(map(str, params[])) resource = klass.TWEET_ID_PREVIEW if params.get() else klass.TWEET_PREVIEW resource = resour...
Returns an HTML preview of a tweet, either new or existing.
364,407
def lookup_symbols(self, symbols, as_of_date, fuzzy=False, country_code=None): if not symbols: return [] multi_country = country_code is None if fuzzy: f = self._lookup_s...
Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols] but potentially faster because repeated lookups are memoized. Parameters ---------- symbols : sequence[str] Sequence of ticker symbols to reso...
364,408
def convert_label_indexer(index, label, index_name=, method=None, tolerance=None): new_index = None if isinstance(label, slice): if method is not None or tolerance is not None: raise NotImplementedError( ) indexer = ind...
Given a pandas.Index and labels (e.g., from __getitem__) for one dimension, return an indexer suitable for indexing an ndarray along that dimension. If `index` is a pandas.MultiIndex and depending on `label`, return a new pandas.Index or pandas.MultiIndex (otherwise return None).
364,409
def field(self): if not self.__field: default_field = inflection.underscore(self.__name) if isinstance(self, orb.ReferenceColumn): default_field += self.__field = default_field return self.__field or default_field
Returns the field name that this column will have inside the database. :return <str>
364,410
def sim_strcmp95(src, tar, long_strings=False): return Strcmp95().sim(src, tar, long_strings)
Return the strcmp95 similarity of two strings. This is a wrapper for :py:meth:`Strcmp95.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison long_strings : bool Set to True to increase the probability of a match when ...
364,411
def render_requests_data_to_html(self, data, file_name, context={}): file_path = os.path.join(self.html_dir, file_name) logger.info( % file_path) data = format_data(data) data.update(context) data.update(domain=self.domain) with open(file_path, ) as fp: ...
Render to HTML file
364,412
def ready_print(worker, output, error): global COUNTER COUNTER += 1 print(COUNTER, output, error)
Local test helper.
364,413
def is_holiday(now=None, holidays="/etc/acct/holidays"): now = _Time(now) if not os.path.exists(holidays): raise Exception("There is no holidays file: %s" % holidays) f = open(holidays, "r") line = f.readline() while line[0] == : line = f.readline() (year, primestar...
is_holiday({now}, {holidays="/etc/acct/holidays"}
364,414
def ProcessResponse(self, client_id, response): precondition.AssertType(client_id, Text) downsampled = rdf_client_stats.ClientStats.Downsampled(response) if data_store.AFF4Enabled(): urn = rdf_client.ClientURN(client_id).Add("stats") with aff4.FACTORY.Create( urn, aff4_stats.Cli...
Actually processes the contents of the response.
364,415
def get_members(pkg_name, module_filter = None, member_filter = None): modules = get_modules(pkg_name, module_filter) ret = {} for m in modules: members = dict(("{0}.{1}".format(v.__module__, k), v) for k, v in getmembers(m, member_filter)) ret.update(members) return ret
返回包中所有符合条件的模块成员。 参数: pkg_name 包名称 module_filter 模块名过滤器 def (module_name) member_filter 成员过滤器 def member_filter(module_member_object)
364,416
def authenticationAndCipheringRequest( AuthenticationParameterRAND_presence=0, CiphKeySeqNr_presence=0): a = TpPd(pd=0x3) b = MessageType(mesType=0x12) d = CipheringAlgorithmAndImeisvRequest() e = ForceToStandbyAndAcRefer...
AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9
364,417
def list_nodes(conn=None, call=None): if call == : raise SaltCloudSystemExit( ) ret = {} for node, info in list_nodes_full(conn=conn).items(): for key in (, , , , , , , , ): ret.setdefault(node, {}).setdefault(key, info.get(key)) return ret
Return a list of VMs CLI Example .. code-block:: bash salt-cloud -f list_nodes myopenstack
364,418
def perform(self): if self._driver.w3c: self.w3c_actions.perform() else: for action in self._actions: action()
Performs all stored actions.
364,419
def is_json(value, schema = None, json_serializer = None, **kwargs): try: value = validators.json(value, schema = schema, json_serializer = json_serializer, **kwargs) ...
Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. :param value: The value to evaluate. :param schema...
364,420
def get_connected_components_as_subgraphs(graph): components = get_connected_components(graph) list_of_graphs = [] for c in components: edge_ids = set() nodes = [graph.get_node(node) for node in c] for n in nodes: for e in n[]: ...
Finds all connected components of the graph. Returns a list of graph objects, each representing a connected component. Returns an empty list for an empty graph.
364,421
def equal(self, cwd): cmd = ["diff"] cmd.append("-q") cmd.append(self.left.get_name()) cmd.append(self.right.get_name()) try: Process(cmd).run(cwd=cwd, suppress_output=True) except SubprocessError as e: if e.get_returncode() == 1: ...
Returns True if left and right are equal
364,422
def register_form_factory(Form): class CsrfDisabledProfileForm(ProfileForm): def __init__(self, *args, **kwargs): kwargs = _update_with_csrf_disabled(kwargs) super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs) class RegisterForm(Form): ...
Factory for creating an extended user registration form.
364,423
def merge(cls, source_blocks): if len(source_blocks) == 1: return source_blocks[0] source_blocks.sort(key=operator.attrgetter()) main_block = source_blocks[0] boot_lines = main_block.boot_lines source_lines = [source_line for source_block in source_blocks f...
Merge multiple SourceBlocks together
364,424
async def _get_entity_from_string(self, string): phone = utils.parse_phone(string) if phone: try: for user in (await self( functions.contacts.GetContactsRequest(0))).users: if user.phone == phone: re...
Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side effect of adding the found users to the session database, so it ...
364,425
def new_worker_pool(self, name: str, min_workers: int = 0, max_workers: int = 1, max_seconds_idle: int = DEFAULT_WORKER_POOL_MAX_SECONDS_IDLE): if not self.running: return self.immediate_worker worker = self._new_worker_pool(name, min_workers, max_workers, ma...
Creates a new worker pool and starts it. Returns the Worker that schedules works to the pool.
364,426
def send(self, envelope): if not self.is_connected: self._connect() msg = envelope.to_mime_message() to_addrs = [envelope._addrs_to_header([addr]) for addr in envelope._to + envelope._cc + envelope._bcc] return self._conn.sendmail(msg[], to_addrs, msg.as_string())
Sends an *envelope*.
364,427
def exit_if_path_exists(self): if os.path.exists(self.output_path): ui.error(c.MESSAGES["path_exists"], self.output_path) sys.exit(1)
Exit early if the path cannot be found.
364,428
def parse_rules(self): try: rule_options = self.config.items() except configparser.NoSectionError: raise LogRaptorConfigError("the app %r has no defined rules!" % self.name) rules = [] for option, value in rule_options: patt...
Add a set of rules to the app, dividing between filter and other rule set
364,429
def serial_udb_extra_f6_encode(self, sue_PITCHGAIN, sue_PITCHKD, sue_RUDDER_ELEV_MIX, sue_ROLL_ELEV_MIX, sue_ELEVATOR_BOOST): return MAVLink_serial_udb_extra_f6_message(sue_PITCHGAIN, sue_PITCHKD, sue_RUDDER_ELEV_MIX, sue_ROLL_ELEV_MIX, sue_ELEVATOR_BOOST)
Backwards compatible version of SERIAL_UDB_EXTRA F6: format sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Proportional Control (float) sue_PITCHKD : Serial UDB Extra Pitch Rate Control (float) sue_RUDDER_ELEV_MIX : Serial UDB Extra Rudder to...
364,430
def supports_string_match_type(self, string_match_type=None): from .osid_errors import IllegalState, NullArgument if not string_match_type: raise NullArgument() if self._kwargs[] not in []: raise IllegalState() return string_match_type in self.ge...
Tests if the given string match type is supported. arg: string_match_type (osid.type.Type): a string match type return: (boolean) - ``true`` if the given string match type Is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``STRING`` raise: Null...
364,431
def patch(): from twisted.application.service import Service old_startService = Service.startService old_stopService = Service.stopService def startService(self): assert not self.running, "%r already running" % (self,) return old_startService(self) def stopService(self): ...
Patch startService and stopService so that they check the previous state first. (used for debugging only)
364,432
def download_apk(self, path=): apk_fd, apk_fn = tempfile.mkstemp(prefix=, suffix=) os.close(apk_fd) try: _download_url(self.artifact_url(), apk_fn) shutil.copy(apk_fn, os.path.join(path, )) finally: os.unlink(apk_fn)
Download Android .apk @type path: @param path:
364,433
def __default(self, ast_token): if self.list_level == 1: if self.list_entry is None: self.list_entry = ast_token elif not isinstance(ast_token, type(self.list_entry)): self.final_ast_tokens.append(ast_token) elif self.list_level == 0: ...
Handle tokens inside the list or outside the list.
364,434
def head(self, rows): rows_bool = [True] * min(rows, len(self._index)) rows_bool.extend([False] * max(0, len(self._index) - rows)) return self.get(indexes=rows_bool)
Return a Series of the first N rows :param rows: number of rows :return: Series
364,435
def start_file(filename): from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices url = QUrl() url.setUrl(filename) return QDesktopServices.openUrl(url)
Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False.
364,436
def export_to_dom(self): namespaces = + \ + \ namespaces = namespaces%(self.target_lems_version,self.target_lems_version,self.schema_location) xmlstr = %namespaces for include in self.includes: xmlstr += include.toxml()...
Exports this model to a DOM.
364,437
def prepare_child_message(self, gas: int, to: Address, value: int, data: BytesOrView, code: bytes, **kwargs: Any) -> Message: ...
Helper method for creating a child computation.
364,438
def extend(self, source, new_image_name, s2i_args=None): s2i_args = s2i_args or [] c = self._s2i_command(["build"] + s2i_args + [source, self.get_full_name()]) if new_image_name: c.append(new_image_name) try: run_cmd(c) except subprocess.CalledPro...
extend this s2i-enabled image using provided source, raises ConuException if `s2i build` fails :param source: str, source used to extend the image, can be path or url :param new_image_name: str, name of the new, extended image :param s2i_args: list of str, additional options and argumen...
364,439
def to_markdown(self): if self.type == "text": return self.text elif self.type == "url" or self.type == "image": return "[" + self.text + "](" + self.attributes["ref"] + ")" elif self.type == "title": return " return None
Converts to markdown :return: item in markdown format
364,440
def dumpindented(self, pn, indent=0): page = self.readpage(pn) print(" " * indent, page) if page.isindex(): print(" " * indent, end="") self.dumpindented(page.preceeding, indent + 1) for p in range(len(page.index)): print(" ...
Dump all nodes of the current page with keys indented, showing how the `indent` feature works
364,441
def authenticate(self, username, password): url = URLS[] data = { "grant_type": "password", "client_id": self.client_id, "client_secret": self.client_secret, "username": username, "password": password } r = requests.pos...
Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters ---------- username : str password : str Returns ------- requests.Response access token is saved in self.access_token refre...
364,442
def p_function_body(p): assert p[1].kind == p[0] = p[1] if len(p) == 3: p[0].redirects.extend(p[2]) assert p[0].pos[0] < p[0].redirects[-1].pos[1] p[0].pos = (p[0].pos[0], p[0].redirects[-1].pos[1])
function_body : shell_command | shell_command redirection_list
364,443
def settle(ctx, symbol, amount, account): print_tx(ctx.bitshares.asset_settle(Amount(amount, symbol), account=account))
Fund the fee pool of an asset
364,444
def _read_reader_macro(ctx: ReaderContext) -> LispReaderForm: start = ctx.reader.advance() assert start == " token = ctx.reader.peek() if token == "{": return _read_set(ctx) elif token == "(": return _read_function(ctx) elif token == ""{token}' in reader macro")
Return a data structure evaluated as a reader macro from the input stream.
364,445
def create(cls, photo, title, description=): if not isinstance(photo, Photo): raise TypeError, "Photo expected" method = data = _dopost(method, auth=True, title=title,\ description=description,\ primary_photo_id=photo.i...
Create a new photoset. photo - primary photo
364,446
def check(f): if hasattr(f, ): return f else: @wraps(f) def decorated(*args, **kwargs): return check_conditions(f, args, kwargs) decorated.wrapped_fn = f return decorated
Wraps the function with a decorator that runs all of the pre/post conditions.
364,447
def _scalar_pattern_uniform_op_left(func): @wraps(func) def verif(self, patt): if isinstance(patt, ScalarPatternUniform): if self._dsphere.shape == patt._dsphere.shape: return ScalarPatternUniform(func(self, self._dsphere, ...
Decorator for operator overloading when ScalarPatternUniform is on the left.
364,448
def pdf(self): r n, a, b = self.n, self.a, self.b k = np.arange(n + 1) probs = binom(n, k) * beta(k + a, n - k + b) / beta(a, b) return probs
r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)}, \qquad k = 0, \ldots, n, ...
364,449
def flatten_egginfo_json( pkg_names, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None): working_set = working_set or default_working_set dists = find_packages_requirements_dists( pkg_names, working_set=working_set) return flatten_dist_egginfo_json( dists, filenam...
A shorthand calling convention where the package name is supplied instead of a distribution. Originally written for this: Generate a flattened package.json with packages `pkg_names` that are already installed within the current Python environment (defaults to the current global working_set which s...
364,450
def _set_tasks_state(self, value): if value not in states.state_numbers.keys(): raise ValueError(obj=self._uid, attribute=, expected_value=states.state_numbers.keys(), actual_value=value) for tas...
Purpose: Set state of all tasks of the current stage. :arguments: String
364,451
def _collect_config(self): kwargs = {} sections = (, , ) for section in sections: kwargs.update(self._collect_section(section)) return kwargs
Collects all info from three sections
364,452
def create_mv_rule(tensorprod_rule, dim): def mv_rule(order, sparse=False, part=None): if sparse: order = numpy.ones(dim, dtype=int)*order tensorprod_rule_ = lambda order, part=part:\ tensorprod_rule(order, part=part) return chaospy.quad.spar...
Convert tensor product rule into a multivariate quadrature generator.
364,453
def get_item_content(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) query_pa...
GetItemContent. Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download. :param str path: Version contr...
364,454
def get_meta_data_editor(self, for_gaphas=True): meta_gaphas = self.meta[][] meta_opengl = self.meta[][] assert isinstance(meta_gaphas, Vividict) and isinstance(meta_opengl, Vividict) parental_conversion_from_opengl = self._parent and self._parent().temp[] ...
Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default...
364,455
def _compare_frame_rankings(ref, est, transitive=False): idx = np.argsort(ref) ref_sorted = ref[idx] est_sorted = est[idx] levels, positions, counts = np.unique(ref_sorted, return_index=True, return_counts=Tr...
Compute the number of ranking disagreements in two lists. Parameters ---------- ref : np.ndarray, shape=(n,) est : np.ndarray, shape=(n,) Reference and estimate ranked lists. `ref[i]` is the relevance score for point `i`. transitive : bool If true, all pairs of reference le...
364,456
def follow_double_underscores(obj, field_name=None, excel_dialect=True, eval_python=False, index_error_value=None): content_type__namemath.sqrt(len(obj.content_type.name)) if not obj: return obj if isinstance(field_name, list): split_fields = field_name else: split_fields = re_mo...
Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators >>> from django.contrib.auth.models import Permission >>> import math >>> p = Permission.objects.all()[0] >>> follow_double_underscores(p, 'content_type__name') == p.content_type.name True >>> ...
364,457
def _process_mrk_acc_view(self): line_counter = 0 LOG.info("mapping markers to internal identifiers") raw = .join((self.rawdir, )) col = [ , , , , , ] with open(raw, ) as fh: fh.readline() for line in f...
Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return:
364,458
def map_indices(fn, iterable, indices): r index_set = set(indices) for i, arg in enumerate(iterable): if i in index_set: yield fn(arg) else: yield arg
r""" Map a function across indices of an iterable. Notes ----- Roughly equivalent to, though more efficient than:: lambda fn, iterable, *indices: (fn(arg) if i in indices else arg for i, arg in enumerate(iterable)) Examples -------- >>> a =...
364,459
def process_chat(self, chat: types.Chat): if not chat: return yield , chat.id yield , chat.type if self.include_content: yield , chat.full_name if chat.username: yield , f"@{chat.username}"
Generate chat data :param chat: :return:
364,460
def install_ansible_support(from_ppa=True, ppa_location=): if from_ppa: charmhelpers.fetch.add_source(ppa_location) charmhelpers.fetch.apt_update(fatal=True) charmhelpers.fetch.apt_install() with open(ansible_hosts_path, ) as hosts_file: hosts_file.write()
Installs the ansible package. By default it is installed from the `PPA`_ linked from the ansible `website`_ or from a ppa specified by a charm config.. .. _PPA: https://launchpad.net/~rquillo/+archive/ansible .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu ...
364,461
def create_model(self, parent, name, multiplicity=, **kwargs): if parent.category != Category.MODEL: raise IllegalArgumentError("The parent should be of category ") data = { "name": name, "parent": parent.id, "multiplicity": multiplicity ...
Create a new child model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the fronten...
364,462
def get_image(self, filename: str=None) -> None: if filename is None: filename = "{0}.png".format(self.name) endpoint = "/account/{0}/savings-goals/{1}/photo".format( self._account_uid, self.uid ) response = get( _url(endpoint, s...
Download the photo associated with a Savings Goal.
364,463
def reset(): colors = [(0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, .75, 0.), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.)] for code, color in zip("bgrmyck", colors): rgb = mpl.colors.colorConverter.to_rgb(color) mpl.colors.colorConverter.colors[code] = rgb mpl.colors...
full reset of matplotlib default style and colors
364,464
def local_rfcformat(dt): weekday = [, , , , , , ][dt.weekday()] month = [ , , , , , , , , , , , , ][dt.month - 1] tz_offset = dt.strftime() return % ( weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second, tz_offset, )
Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset.
364,465
def source_sum_err(self): if self._error is not None: if self._is_completely_masked: return np.nan * self._error_unit else: return np.sqrt(np.sum(self._error_values ** 2)) else: return None
The uncertainty of `~photutils.SourceProperties.source_sum`, propagated from the input ``error`` array. ``source_sum_err`` is the quadrature sum of the total errors over the non-masked pixels within the source segment: .. math:: \\Delta F = \\sqrt{\\sum_{i \\in S} \\s...
364,466
def create_request_url(self, interface, method, version, parameters): if in parameters: parameters[] = self.apikey else: parameters.update({ : self.apikey, : self.format}) version = "v%04d" % (version) url = "http://api.steampowered.com/%s/%s/%s/?%s" % ...
Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the method.
364,467
def _create_inbound_stream(self, config=None): if config is None: raise ValueError() name = self._get_stream_name(config) stream_handlers = self._get_stream_handlers(config, name) stream_input = config.get(, None) if stream_input is None: raise(c...
Creates an inbound stream from its config. Params: config: stream configuration as read by ait.config Returns: stream: a Stream Raises: ValueError: if any of the required config values are missing
364,468
def _string_width(self, s): s = str(s) w = 0 for char in s: char = ord(char) w += self.character_widths[char] return w * self.font_size / 1000.0
Get width of a string in the current font
364,469
def all(self, archived=False, limit=None, page=None): path = partial(_path, self.adapter) if not archived: path = _path(self.adapter) else: path = _path(self.adapter, ) return self._get(path, limit=limit, page=page)
get all adapter data.
364,470
def parse(self, vd, extent_loc): (descriptor_type, identifier, self.version, self.flags, self.system_identifier, self.volume_identifier, unused1, space_size_le, space_size_be, self.escape_sequences, set_size_le, set_size_be, seqnum_le, seqnum_be, logical_blo...
Parse a Volume Descriptor out of a string. Parameters: vd - The string containing the Volume Descriptor. extent_loc - The location on the ISO of this Volume Descriptor. Returns: Nothing.
364,471
def random_dna(n): return coral.DNA(.join([random.choice() for i in range(n)]))
Generate a random DNA sequence. :param n: Output sequence length. :type n: int :returns: Random DNA sequence of length n. :rtype: coral.DNA
364,472
def numbered_syllable_to_accented(syllable): def keep_case_replace(s, vowel, replacement): accented = s.replace(vowel, replacement) if syllable[0].isupper(): return accented[0].upper() + accented[1:] return accented tone = syllable[-1] if tone == : return re...
Convert a numbered pinyin syllable to an accented pinyin syllable. Implements the following algorithm, modified from https://github.com/tsroten/zhon: 1. If the syllable has an 'a' or 'e', put the tone over that vowel. 2. If the syllable has 'ou', place the tone over the 'o'. 3. Otherwise, p...
364,473
def sort_url_qsl(cls, raw_url, **kwargs): parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) return cls._join_url(parsed_url, sorted(qsl, **kwargs))
Do nothing but sort the params of url. raw_url: the raw url to be sorted; kwargs: (optional) same kwargs for ``sorted``.
364,474
def rpc_get_name_at( self, name, block_height, **con_info ): if not check_name(name): return {: , : 400} if not check_block(block_height): return self.success_response({: None}) db = get_db_state(self.working_dir) names_at = db.get_name_at( name, block_...
Get all the states the name was in at a particular block height. Does NOT work on expired names. Return {'status': true, 'record': ...}
364,475
def _parse_bug(self, data): if in data: data[] = self.url.replace(, str(data[])) bug = AttrDict(data) return bug
param data: dict of data from XML-RPC server, representing a bug. returns: AttrDict
364,476
def update_trigger(self, trigger): assert trigger is not None assert isinstance(trigger.id, str), "Value must be a string" the_time_period = { "start": { "expression": "after", "amount": trigger.start_after_millis }, "e...
Updates on the Alert API the trigger record having the ID of the specified Trigger object: the remote record is updated with data from the local Trigger object. :param trigger: the Trigger with updated data :type trigger: `pyowm.alertapi30.trigger.Trigger` :return: ``None`` if update is...
364,477
def add_identity(db, source, email=None, name=None, username=None, uuid=None): with db.connect() as session: try: identity_id = utils.uuid(source, email=email, name=name, username=username) except ValueError as e: raise Inval...
Add an identity to the registry. This function adds a new identity to the registry. By default, a new unique identity will be also added an associated to the new identity. When 'uuid' parameter is set, it creates a new identity that will be associated to the unique identity defined by 'uuid' that alrea...
364,478
def is_glacier(s3_client, bucket, prefix): response = s3_client.list_objects_v2(Bucket=bucket, Prefix=prefix, MaxKeys=3) for key in response[]: if key.get(, ) == : return True return False
Check if prefix is archived in Glacier, by checking storage class of first object inside that prefix Arguments: s3_client - boto3 S3 client (not service) bucket - valid extracted bucket (without protocol and prefix) example: sowplow-events-data prefix - valid S3 prefix (usually, run_id...
364,479
def make_unary(lineno, operator, operand, func=None, type_=None): return symbols.UNARY.make_node(lineno, operator, operand, func, type_)
Wrapper: returns a Unary node
364,480
def axpy(x, y, a=1.0): from scipy.linalg import get_blas_funcs fn = get_blas_funcs([], [x, y])[0] fn(x, y, a)
Quick level-1 call to BLAS y = a*x+y. Parameters ---------- x : array_like nx1 real or complex vector y : array_like nx1 real or complex vector a : float real or complex scalar Returns ------- y : array_like Input variable y is rewritten Notes -...
364,481
def extract_ipfs_path_from_uri(value: str) -> str: parse_result = parse.urlparse(value) if parse_result.netloc: if parse_result.path: return "".join((parse_result.netloc, parse_result.path.rstrip("/"))) else: return parse_result.netloc else: return parse...
Return the path from an IPFS URI. Path = IPFS hash & following path.
364,482
def none_coalesce_handle(tokens): if len(tokens) == 1: return tokens[0] elif tokens[0].isalnum(): return "({b} if {a} is None else {a})".format( a=tokens[0], b=none_coalesce_handle(tokens[1:]), ) else: return "(lambda {x}: {b} if {x} is None else ...
Process the None-coalescing operator.
364,483
async def disconnect(self): if self._connection: log.debug() await self._connection.close() self._connection = None
Shut down the watcher task and close websockets.
364,484
def _get_cpu_cores_per_run0(coreLimit, num_of_threads, allCpus, cores_of_package, siblings_of_core): if coreLimit > len(allCpus): sys.exit("Cannot run benchmarks with {0} CPU cores, only {1} CPU cores available.".format(coreLimit, len(allCpus))) if coreLimit * num_of_threads > len(allCpus): ...
This method does the actual work of _get_cpu_cores_per_run without reading the machine architecture from the file system in order to be testable. For description, c.f. above. Note that this method might change the input parameters! Do not call it directly, call getCpuCoresPerRun()! @param allCpus: t...
364,485
def get_version(mod, default="0.0.0"): name = mod if hasattr(mod, "__name__"): name = mod.__name__ try: import pkg_resources return pkg_resources.get_distribution(name).version except Exception as e: LOG.warning("Can't determine version for %s: %s", name, e, exc_i...
:param module|str mod: Module, or module name to find version for (pass either calling module, or its .__name__) :param str default: Value to return if version determination fails :return str: Determined version
364,486
def delete_object(self, bucket, obj, version_id): if version_id is None: with db.session.begin_nested(): ObjectVersion.delete(bucket, obj.key) db.session.commit() else: check_permission( current_permis...
Delete an existing object. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :param version_id: The version ID. :returns: A Flask response.
364,487
def find_features(feats, sequ, annotated, start_pos, cutoff): feats_a = list(feats.keys()) j = 0 s = 0 en = 0 start = 0 for i in range(0, len(sequ)): if j <= len(feats_a)-1: if i > int(feats[feats_a[j]].location.end): j += 1 if(sequ[i] == ): ...
find_features - Finds the reference sequence features in the alignments and records the positions :param feats: Dictonary of sequence features :type feats: ``dict`` :param sequ: The sequence alignment for the input sequence :type sequ: ``List`` :param annotated: dictonary of the annotated features...
364,488
def dirty(field,ttl=None): "decorator to cache the result of a function until a field changes" if ttl is not None: raise NotImplementedError() def decorator(f): @functools.wraps(f) def wrapper(self,*args,**kwargs): d=self.dirty_cache[field] if field in self.dirty_cache else self.dirty_c...
decorator to cache the result of a function until a field changes
364,489
def make_figure_uhs(extractors, what): import matplotlib.pyplot as plt fig = plt.figure() got = {} for i, ex in enumerate(extractors): uhs = ex.get(what) for kind in uhs.kind: got[ex.calc_id, kind] = uhs[kind] oq = ex.oqparam n_poes = len(oq.poes) periods =...
$ oq plot 'uhs?kind=mean&site_id=0'
364,490
def from_vrep(config, vrep_host=, vrep_port=19997, scene=None, tracked_objects=[], tracked_collisions=[], id=None, shared_vrep_io=None): if shared_vrep_io is None: vrep_io = VrepIO(vrep_host, vrep_port) else: vrep_io = shared_vrep_io vreptime = vrep_time(vre...
Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) :type config: str or dict :param str vrep_host: host of the V-REP server :param int vrep_port: port of the V-REP server :param str scene: path to the V-REP scene to load...
364,491
def setup_logger(logger, logfile): global _REGISTERED_LOGGER_HANDLERS logger.setLevel(logging.DEBUG) if is_none_or_empty(logfile): handler = logging.StreamHandler() else: handler = logging.FileHandler(logfile, encoding=) logging.getLogger().addHandler(handler) formatt...
Set up logger
364,492
def list_file_jobs(cls, offset=None, limit=None, api=None): api = api or cls._API return super(AsyncJob, cls)._query( api=api, url=cls._URL[], offset=offset, limit=limit, )
Query ( List ) async jobs :param offset: Pagination offset :param limit: Pagination limit :param api: Api instance :return: Collection object
364,493
def download(self, itemID, savePath): if os.path.isdir(savePath) == False: os.makedirs(savePath) url = self._url + "/%s/download" % itemID params = { } if len(params.keys()): url = url + "?%s" % urlencode(params) return self._get(url=url,...
downloads an item to local disk Inputs: itemID - unique id of item to download savePath - folder to save the file in
364,494
def make_callback_children(self, name, *args, **kwdargs): if hasattr(self, ): num = len(self.objects) - 1 while num >= 0: obj = self.objects[num] if isinstance(obj, Callbacks): obj.make_callback(name, *args, **kwda...
Invoke callbacks on all objects (i.e. layers) from the top to the bottom, returning when the first one returns True. If none returns True, then make the callback on our 'native' layer.
364,495
def vdm_b(vdm, lat): rad = old_div(np.pi, 180.) fact = ((6.371e6)**3) * 1e7 colat = (90. - lat) * rad return vdm * (np.sqrt(1 + 3 * (np.cos(colat)**2))) / fact
Converts a virtual dipole moment (VDM) or a virtual axial dipole moment (VADM; input in units of Am^2) to a local magnetic field value (output in units of tesla) Parameters ---------- vdm : V(A)DM in units of Am^2 lat: latitude of site in degrees Returns ------- B: local magnetic f...
364,496
def load(self, providers, symbols, start, end, logger, backend, **kwargs): logger = logger or logging.getLogger(self.__class__.__name__) start, end = self.dates(start, end) data = {} for sym in symbols: symbol = self.parse_symbol(sym, prov...
Load symbols data. :keyword providers: Dictionary of registered data providers. :keyword symbols: list of symbols to load. :keyword start: start date. :keyword end: end date. :keyword logger: instance of :class:`logging.Logger` or ``None``. :keyword backend: :clas...
364,497
def trnIndextoCoord(self, i): x = i % self.trnWidth y = i / self.trnWidth return x, y
Map 1D cell index to a 2D coordinate :param i: integer 1D cell index :return: (x, y), a 2D coordinate
364,498
def calculate_authentication_data(self, key): if self.key_id == KEY_ID_NONE: return if self.key_id == KEY_ID_HMAC_SHA_1_96: digestmod = hashlib.sha1 data_length = 20 elif self.key_id == KEY_ID_HMAC_SHA_256_128: digestmo...
Calculate the authentication data based on the current key-id and the given key.
364,499
def ordered_covering(routing_table, target_length, aliases=dict(), no_raise=False): aliases = dict(aliases) routing_table = sorted( routing_table, key=lambda entry: _get_generality(entry.key, entry.mask) ) while target_length is None or len(rout...
Reduce the size of a routing table by merging together entries where possible. .. warning:: The input routing table *must* also include entries which could be removed and replaced by default routing. .. warning:: It is assumed that the input routing table is not in any particular...