Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
389,000
def fetch_request_token(self, oauth_request): try: token = self._get_token(oauth_request, ) except Error: version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: callba...
Processes a request_token request and returns the request token on success.
389,001
async def send_chat_action(self, chat_id: typing.Union[base.Integer, base.String], action: base.String) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.SEND_CHAT_ACTION, payload) return result
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). We only recommend using this method when a response from the bot will take ...
389,002
def proximal_convex_conj_l2(space, lam=1, g=None): r prox_l2 = proximal_l2(space, lam=lam, g=g) return proximal_convex_conj(prox_l2)
r"""Proximal operator factory of the convex conj of the l2-norm/distance. Function for the proximal operator of the convex conjugate of the functional F where F is the l2-norm (or distance to g, if given):: F(x) = lam ||x - g||_2 with x and g elements in ``space``, scaling factor lam, and given ...
389,003
def resolve_profile(name, include_expired=False, include_name_record=False, hostport=None, proxy=None): assert hostport or proxy, name_rec = get_name_record(name, include_history=False, include_expired=include_expired, include_grace=False, proxy=proxy, hostport=hostport) if in name_rec: ...
Resolve a name to its profile. This is a multi-step process: 1. get the name record 2. get the zone file 3. parse the zone file to get its URLs (if it's not well-formed, then abort) 4. fetch and authenticate the JWT at each URL (abort if there are none) 5. extract the profile JSON and return tha...
389,004
def nolist(self, account): assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=[], account=self)
Remove an other account from any list of this account
389,005
def is_file(cls, file): peeked_data = wpull.string.printable_bytes( wpull.util.peek_file(file)).lower() if b in peeked_data: return VeryFalse if re.search(br, peeked_data): return True
Return whether the file is likely CSS.
389,006
def _derive_stereographic(): from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix x_c, y_c, z_c, x, y, z = symbols() around_z = atan2(x_c, y_c) around_x = acos(-z_c) v = Matrix([x, y, z]) xo, yo, zo = rot_axis1(around_x) * rot_axis3(-around_z) * v ...
Compute the formulae to cut-and-paste into the routine below.
389,007
def _read_regex(ctx: ReaderContext) -> Pattern: s = _read_str(ctx, allow_arbitrary_escapes=True) try: return langutil.regex_from_str(s) except re.error: raise SyntaxError(f"Unrecognized regex pattern syntax: {s}")
Read a regex reader macro from the input stream.
389,008
def process_request(self, num_pending, ports, request_blocking=False): if any(port in self._step_requests for port in ports): port = [x for x in ports if x in self._step_requests][0] self._worker_backend_socket.send_pyobj( self._step_requests.pop(por...
port is the open port at the worker, num_pending is the num_pending of stack. A non-zero num_pending means that the worker is pending on something while looking for new job, so the worker should not be killed.
389,009
def invokeRunnable(self): runnable = self.runnable if runnable is None: self.deleteFromStore() else: try: self.running = True newTime = runnable.run() finally: self.running = False self._resc...
Run my runnable, and reschedule or delete myself based on its result. Must be run in a transaction.
389,010
def gene_counts(self): return { gene_name: len(group) for (gene_name, group) in self.groupby_gene_name().items() }
Returns number of elements overlapping each gene name. Expects the derived class (VariantCollection or EffectCollection) to have an implementation of groupby_gene_name.
389,011
def on_start(self): logger.info() if self.config[] == 0: logger.info() return self.in_future.report_status()
Runs when the actor is started and schedules a status update
389,012
def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx): import scipy.linalg.lapack npt = bd_all.shape[0] n = bd_idx.shape[1] kvalues = np.zeros(npt) sigmasq = np.zeros(npt) for i in np.nonzero(~mask)[0]: b_selector = bd_idx[i] b...
Solves the kriging system by looping over all specified points. Uses only a certain number of closest points. Not very memory intensive, but the loop is done in pure Python.
389,013
def stop_archive(self, archive_id): response = requests.post(self.endpoints.archive_url(archive_id) + , headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout) if response.status_code < 300: return Archive(self, response.json()) elif response.status_code ==...
Stops an OpenTok archive that is being recorded. Archives automatically stop recording after 90 minutes or when all clients have disconnected from the session being archived. @param [String] archive_id The archive ID of the archive you want to stop recording. :rtype: The Archive objec...
389,014
def get(self, sid): return ReservationContext( self._version, workspace_sid=self._solution[], task_sid=self._solution[], sid=sid, )
Constructs a ReservationContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext
389,015
def _controller(self): def server_controller(cmd_id, cmd_body, _): if not self.init_logginig: head = + str( self.kvstore.rank) + logging.basicConfig(level=logging.DEBUG, format=head) ...
Return the server controller.
389,016
def to_json(self): return { : self.location.to_json(), : [des_d.to_json() for des_d in self.design_days] }
Convert the Design Day to a dictionary.
389,017
def run_parse(self): parsedset = {} parsedset[] = [] for log in self.input_files: parsemodule = self.parse_modules[self.args.parser] try: if self.args.tzone: parsemodule.tzone = self.args.tzone except NameE...
Parse one or more log files
389,018
def _load_cpp4(self, filename): ccp4 = CCP4.CCP4() ccp4.read(filename) grid, edges = ccp4.histogramdd() self.__init__(grid=grid, edges=edges, metadata=self.metadata)
Initializes Grid from a CCP4 file.
389,019
def compute_region_border(start, end): cells = defaultdict(Cell) start_row = row_number(start) end_row = row_number(end) if end % 0x10 == 0: end_row -= 1 if start_row == end_row: for i in range(start, end): cells[i].top = True else: for i in range(...
given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance has boolean properties "top", "bottom", "left", and...
389,020
def gene_names(self): return self.ensembl.gene_names_at_locus( self.contig, self.start, self.end)
Return names of all genes which overlap this variant. Calling this method is significantly cheaper than calling `Variant.genes()`, which has to issue many more queries to construct each Gene object.
389,021
def ldr(scatterer, h_pol=True): Z = scatterer.get_Z() if h_pol: return (Z[0,0] - Z[0,1] + Z[1,0] - Z[1,1]) / \ (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1]) else: return (Z[0,0] + Z[0,1] - Z[1,0] - Z[1,1]) / \ (Z[0,0] + Z[0,1] + Z[1,0] + Z[1,1])
Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR.
389,022
def downloaded(name, version=None, pkgs=None, fromrepo=None, ignore_epoch=None, **kwargs): ret = {: name, : {}, : None, : } if not in __salt__: ret[] = False ret[] = \ ...
.. versionadded:: 2017.7.0 Ensure that the package is downloaded, and that it is the correct version (if specified). Currently supported for the following pkg providers: :mod:`yumpkg <salt.modules.yumpkg>` and :mod:`zypper <salt.modules.zypper>` :param str name: The name of the package to...
389,023
def canonicalize(message): if message.is_multipart() \ or message.get() != : return mime_to_bytes(message, 0).replace( b, b).replace(b, b).replace(b, b) else: message_header = message_body = message.get_payload(decode=True) for k, v in message.item...
Function to convert an email Message to standard format string :param message: email.Message to be converted to standard string :return: the standard representation of the email message in bytes
389,024
def __deserialize_model(self, data, klass): if not klass.swagger_types: return data kwargs = {} for attr, attr_type in iteritems(klass.swagger_types): if data is not None \ and klass.attribute_map[attr] in data \ and isinstance(data...
Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object.
389,025
def get_billing_report(self, month, **kwargs): kwargs[] = True if kwargs.get(): return self.get_billing_report_with_http_info(month, **kwargs) else: (data) = self.get_billing_report_with_http_info(month, **kwargs) return data
Get billing report. # noqa: E501 Fetch the billing report generated for the currently authenticated commercial non-subtenant account. Billing reports for subtenant accounts are included in their aggregator's billing report response. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v3/b...
389,026
def total(self): feats = imap(lambda name: self[name], self._counters()) return sum(chain(*map(lambda mset: map(abs, mset.values()), feats)))
Returns sum of all counts in all features that are multisets.
389,027
def execute_prepared_cql3_query(self, itemId, values, consistency): self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_execute_prepared_cql3_query(itemId, values, consistency) return d
Parameters: - itemId - values - consistency
389,028
def a_stays_connected(ctx): ctx.ctrl.connected = True ctx.device.connected = False return True
Stay connected.
389,029
def exit(self, status=EXIT_OK, message=None): if not self.parser: self.parser = argparse.ArgumentParser() if self.msg_on_error_only: if status != EXIT_OK: self.parser.exit(status, None) else: ...
Terminate the script.
389,030
def load(self, filepath): for attributeLines in oboTermParser(filepath): oboTerm = _attributeLinesToDict(attributeLines) if oboTerm[] not in self.oboTerms: self.oboTerms[oboTerm[]] = oboTerm else: oldOboTerm = self.oboTerms...
Import '[Term]' entries from an .obo file.
389,031
def unionByName(self, other): return DataFrame(self._jdf.unionByName(other._jdf), self.sql_ctx)
Returns a new :class:`DataFrame` containing union of rows in this and another frame. This is different from both `UNION ALL` and `UNION DISTINCT` in SQL. To do a SQL-style set union (that does deduplication of elements), use this function followed by :func:`distinct`. The difference between th...
389,032
def process_event(self, c): if c == "": sys.exit() elif c in key_directions: self.move_entity(self.player, *vscale(self.player.speed, key_directions[c])) else: return "try arrow keys, w, a, s, d, or ctrl-D (you pressed %r)" % c return self.ti...
Returns a message from tick() to be displayed if game is over
389,033
def _establish_tunnel(self, connection, address): host = .format(address[0]) if in address[0] else address[0] port = address[1] request = RawRequest(, .format(host, port)) self.add_auth_header(request) stream = Stream(connection, keep_alive=True) _logger.debu...
Establish a TCP tunnel. Coroutine.
389,034
def to_type(self, tokens): result = [] name_tokens = [] reference = pointer = array = False inside_array = False empty_array = True templated_tokens = [] def add_type(): if not name_tokens: return nam...
Convert [Token,...] to [Class(...), ] useful for base classes. For example, code like class Foo : public Bar<x, y> { ... }; the "Bar<x, y>" portion gets converted to an AST. Returns: [Class(...), ...]
389,035
def get_vexrc(options, environ): if options.config and not os.path.exists(options.config): raise exceptions.InvalidVexrc("nonexistent config: {0!r}".format(options.config)) filename = options.config or os.path.expanduser() vexrc = config.Vexrc.from_file(filename, environ) return v...
Get a representation of the contents of the config file. :returns: a Vexrc instance.
389,036
def set_mode(self, mode): if not mode in [self.STRICT_MIN_LENGTH, self.DROP_TRAILING_SILENCE, self.STRICT_MIN_LENGTH | self.DROP_TRAILING_SILENCE, 0]: raise ValueError("Wrong value for mode") self._mode = mode self._strict_min_length = (mode & self...
:Parameters: `mode` : *(int)* New mode, must be one of: - `StreamTokenizer.STRICT_MIN_LENGTH` - `StreamTokenizer.DROP_TRAILING_SILENCE` - `StreamTokenizer.STRICT_MIN_LENGTH | StreamTokenizer.DROP_TRAILING_SILENCE` - `0` See `Stre...
389,037
def fromBban(bban): countryCode = "XE" remainder = mod9710(iso13616Prepare(countryCode + "00" + bban)) checkDigit = ("0" + str(98 - remainder))[-2:] return Iban(countryCode + checkDigit + bban)
Convert the passed BBAN to an IBAN for this country specification. Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/Int...
389,038
def _run_cmd_line_code(self): if self.code_to_run: line = self.code_to_run try: self.log.info("Running code given at command line (c=): %s" % line) self.shell.run_cell(line, store_history=False) except: ...
Run code or file specified at the command-line
389,039
def to_routing_header(params): if sys.version_info[0] < 3: return urlencode(params).replace("%2F", "/") return urlencode( params, safe="/", )
Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]): A dictionary containing the request parameters used for routing. Returns: str: The routing header string.
389,040
def add_file_arg(self, filename): self.__arguments.append(filename) if filename not in self.__input_files: self.__input_files.append(filename)
Add a file argument to the executable. Arguments are appended after any options and their order is guaranteed. Also adds the file name to the list of required input data for this job. @param filename: file to add as argument.
389,041
def get_vnetwork_vms_input_last_rcvd_instance(self, **kwargs): config = ET.Element("config") get_vnetwork_vms = ET.Element("get_vnetwork_vms") config = get_vnetwork_vms input = ET.SubElement(get_vnetwork_vms, "input") last_rcvd_instance = ET.SubElement(input, "last-rcvd-...
Auto Generated Code
389,042
def check_prompt_code(response): num_code = response.find("div", {"jsname": "EKvSSd"}) if num_code: print("numerical code for prompt: {}".format(num_code.string))
Sometimes there is an additional numerical code on the response page that needs to be selected on the prompt from a list of multiple choice. Print it if it's there.
389,043
def _generate_null_hocr(output_hocr, output_sidecar, image): from PIL import Image im = Image.open(image) w, h = im.size with open(output_hocr, , encoding="utf-8") as f: f.write(HOCR_TEMPLATE.format(w, h)) with open(output_sidecar, , encoding=) as f: f.write()
Produce a .hocr file that reports no text detected on a page that is the same size as the input image.
389,044
def get_activity_photos(self, activity_id, size=None, only_instagram=False): params = {} if not only_instagram: params[] = if size is not None: params[] = size result_fetcher = functools.partial(self.protocol.get, ...
Gets the photos from an activity. http://strava.github.io/api/v3/photos/ :param activity_id: The activity for which to fetch kudos. :type activity_id: int :param size: the requested size of the activity's photos. URLs for the photos will be returned that best match ...
389,045
def transfer_owner(self, new_owner: Address) -> TxReceipt: tx_hash = self.registry.functions.transferOwner(new_owner).transact() return self.w3.eth.waitForTransactionReceipt(tx_hash)
Transfers ownership of this registry instance to the given ``new_owner``. Only the ``owner`` is allowed to transfer ownership. * Parameters: * ``new_owner``: The address of the new owner.
389,046
def readline(self): b = super(PtyProcessUnicode, self).readline() return self.decoder.decode(b, final=False)
Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed.
389,047
def _set_source(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("src_interface_type src_interface_name destination dst_interface_type dst_interface_name",source.source, yang_name="source", rest_name="source", parent=self, is_container=, u...
Setter method for source, mapped from YANG variable /acl_mirror/source (list) If this variable is read-only (config: false) in the source YANG file, then _set_source is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_source() directly.
389,048
def _refresh_resource_index(self, resource): if self._resource_config(resource, , True): self.elastic(resource).indices.refresh(self._resource_index(resource))
Refresh index for given resource. :param resource: resource name
389,049
def load_code(self): a = self.load_int() b = self.load_int() key = get_keys(a, b) padsize = (b + 15) & ~0xf intsize = padsize/4 data = self.bufstr[self.bufpos:self.bufpos+padsize] data = list(struct.unpack( % intsize, data)) tea_decipher(data, key) self.bufpos += padsize ...
Returns a Python code object like xdis.unmarshal.load_code(), but in we decrypt the data in self.bufstr. That is: * calculate the TEA key, * decrypt self.bufstr * create and return a Python code-object
389,050
async def main(): async with ClientSession() as websession: try: client = Client(websession) await client.load_local(, , websession) for controller in client.controllers.values(): print() print(.format(controller.name)) ...
Run.
389,051
def override (overrider_id, overridee_id): assert isinstance(overrider_id, basestring) assert isinstance(overridee_id, basestring) __overrides.setdefault(overrider_id, []).append(overridee_id)
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately ...
389,052
def export_pages(root_page, export_unpublished=False): pages = Page.objects.descendant_of(root_page, inclusive=True).order_by().specific() if not export_unpublished: pages = pages.filter(live=True) page_data = [] exported_paths = set() for (i, page) in enumerate(pages): parent_...
Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures th...
389,053
def _calculate_mapping_reads(items, work_dir, input_backs=None): out_file = os.path.join(work_dir, "mapping_reads.txt") if not utils.file_exists(out_file): lines = [] for data in items: count = 0 for line in subprocess.check_output([ "samtools", "idxs...
Calculate read counts from samtools idxstats for each sample. Optionally moves over pre-calculated mapping counts from a background file.
389,054
def rebuild(self, recreate=True, force=False, **kwargs): "Recreate (if needed) the wx_obj and apply new properties" needs_rebuild = any([isinstance(spec, (StyleSpec, InitSpec)) for spec_name, spec in self._meta.specs.items() if spec...
Recreate (if needed) the wx_obj and apply new properties
389,055
def compare_version(version1, version2): def normalize(v): return [int(x) for x in re.sub(r,, v).split(".")] return (normalize(version1) > normalize(version2))-(normalize(version1) < normalize(version2))
Compares two versions.
389,056
def write_antenna(page, args, seg_plot=None, grid=False, ipn=False): from pylal import antenna page.h3() page.add() page.h3.close() th = [] td = [] th2 = [] td2 = [] ifos = [args.ifo_tag[i:i+2] for i in range(0, len(args.ifo_tag), 2)] if ipn: antenna_ifo = {} ...
Write antenna factors to merkup.page object page and generate John's detector response plot.
389,057
def cleanPolyline(elem, options): pts = parseListOfPoints(elem.getAttribute()) elem.setAttribute(, scourCoordinates(pts, options, True))
Scour the polyline points attribute
389,058
def backfill_previous_messages(self, reverse=False, limit=10): res = self.client.api.get_room_messages(self.room_id, self.prev_batch, direction="b", limit=limit) events = res["chunk"] if not reverse: events = reversed(events) ...
Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back.
389,059
def callable_name(callable_obj): try: if (isinstance(callable_obj, type) and issubclass(callable_obj, param.ParameterizedFunction)): return callable_obj.__name__ elif (isinstance(callable_obj, param.Parameterized) and in callable_obj.params()): ...
Attempt to return a meaningful name identifying a callable or generator
389,060
def add_hook(self, name, func): if name in self.__hook_reversed: self._hooks[name].insert(0, func) else: self._hooks[name].append(func)
Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request regardless of i...
389,061
def _handle_pong(self, ts, *args, **kwargs): log.info("BitfinexWSS.ping(): Ping received! (%ss)", ts - self.ping_timer) self.ping_timer = None
Handles pong messages; resets the self.ping_timer variable and logs info message. :param ts: timestamp, declares when data was received by the client :return:
389,062
def filter_by(self, values, exclude=False): from .sframe import SFrame as _SFrame column_name = if not isinstance(values, SArray): if not _is_non_string_iterable(values): values = [values] ...
Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it to one before filtering. Parameters ---------- ...
389,063
def get_keywords_from_text(text_lines, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False,...
Extract keywords from the list of strings. :param text_lines: list of strings (will be normalized before being joined into one string) :param taxonomy_name: string, name of the taxonomy_name :param output_mode: string - text|html|marcxml|raw :param output_limit: int :param spires: boolean, ...
389,064
def matchPatterns(patterns, keys): results = [] if patterns: for pattern in patterns: prog = re.compile(pattern) for key in keys: if prog.match(key): results.append(key) else: return None return results
Returns a subset of the keys that match any of the given patterns :param patterns: (list) regular expressions to match :param keys: (list) keys to search for matches
389,065
def removeChild(self, child): try: self.children.remove(child) self.blocks.remove(child) child.parentNode = None child.ownerDocument = None for subChild in child.getAllChildNodes(): subC...
removeChild - Remove a child tag, if present. @param child <AdvancedTag> - The child to remove @return - The child [with parentNode cleared] if removed, otherwise None. NOTE: This removes a tag. If removing a text block, use #removeText function. If y...
389,066
def subdivide(self): r left_nodes, right_nodes = _curve_helpers.subdivide_nodes(self._nodes) left = Curve(left_nodes, self._degree, _copy=False) right = Curve(right_nodes, self._degree, _copy=False) return left, right
r"""Split the curve :math:`B(s)` into a left and right half. Takes the interval :math:`\left[0, 1\right]` and splits the curve into :math:`B_1 = B\left(\left[0, \frac{1}{2}\right]\right)` and :math:`B_2 = B\left(\left[\frac{1}{2}, 1\right]\right)`. In order to do this, also reparameteri...
389,067
def status_set(workload_state, message): valid_states = [, , , ] if workload_state not in valid_states: raise ValueError( .format(workload_state) ) cmd = [, workload_state, message] try: ret = subprocess.call(cmd) if ret == 0: return excep...
Set the workload state with a message Use status-set to set the workload state with a message which is visible to the user via juju status. If the status-set command is not found then assume this is juju < 1.23 and juju-log the message unstead. workload_state -- valid juju workload state. message ...
389,068
def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: return Double(context.jvm_view().ArcSinVertex, label, cast_to_double_vertex(input_vertex))
Takes the inverse sin of a vertex, Arcsin(vertex) :param input_vertex: the vertex
389,069
def simplify(self): node = self.node.simplify() if node is self.node: return self else: return _expr(node)
Return a simplified expression.
389,070
def do_gate_matrix(self, matrix: np.ndarray, qubits: Sequence[int]) -> : unitary = lifted_gate_matrix(matrix=matrix, qubit_inds=qubits, n_qubits=self.n_qubits) self.density = unitary.dot(self.density).dot(np.conj(unitary).T) return self
Apply an arbitrary unitary; not necessarily a named gate. :param matrix: The unitary matrix to apply. No checks are done :param qubits: A list of qubits to apply the unitary to. :return: ``self`` to support method chaining.
389,071
def strlify(a): t matter, but some functions in Python 3 brick when they get bytes instead of a string, so ita1b2c3a1b2c3a1b2c3a1b2c3a1b2c3a1b2c3a1b2c3a1b2c3" in the middle of them. Obviously it" in the middle of the string. Use this for making sure base 16/58/64 objects are in string format. ...
Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so it's safer to just strl...
389,072
def _lval_add_towards_polarity(x, polarity): if x < 0: if polarity < 0: return Lval(, x) return Lval(, x) elif polarity > 0: return Lval(, x) return Lval(, x)
Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity.
389,073
def yield_sorted_by_type(*typelist): def decorate(fun): @wraps(fun) def decorated(*args, **kwds): return iterate_by_type(fun(*args, **kwds), typelist) return decorated return decorate
a useful decorator for the collect_impl method of SuperChange subclasses. Caches the yielded changes, and re-emits them collected by their type. The order of the types can be specified by listing the types as arguments to this decorator. Unlisted types will be yielded last in no guaranteed order. G...
389,074
def _initiate_resumable_upload(self, stream, metadata, num_retries): chunk_size = _DEFAULT_CHUNKSIZE transport = self._http headers = _get_upload_headers(self._connection.USER_AGENT) upload_url = _RESUMABLE_URL_TEMPLATE.format(project=self.project) uplo...
Initiate a resumable upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type num_retries: int :param num_retries: Number of upload retries. (Deprecated: This...
389,075
def make_decoder(activation, latent_size, output_shape, base_depth): deconv = functools.partial( tf.keras.layers.Conv2DTranspose, padding="SAME", activation=activation) conv = functools.partial( tf.keras.layers.Conv2D, padding="SAME", activation=activation) decoder_net = tf.keras.Sequential([ ...
Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distri...
389,076
def options(self): response = self.repo.api.http_request(, self.uri) return response.headers
Small method to return headers of an OPTIONS request to self.uri Args: None Return: (dict) response headers from OPTIONS request
389,077
def decode_packet(data): if _debug: decode_packet._debug("decode_packet %r", data) if not data: return None d = decode_ethernet(data) pduSource = Address(d[]) pduDestination = Address(d[]) data = d[] if (d[] == 0x8100): if _debug: decode_packet._debug("...
decode the data, return some kind of PDU.
389,078
def get_time_interval(time1, time2): try: time1 = time.mktime(time.strptime(time1, )) time2 = time.mktime(time.strptime(time2, )) seconds = (datetime.datetime.fromtimestamp(time2) - datetime.datetime.fromtimestamp(time1)).seconds days = seconds / 86400 ...
get the interval of two times
389,079
def submatrix(dmat, indices_col, n_neighbors): n_samples_transform, n_samples_fit = dmat.shape submat = np.zeros((n_samples_transform, n_neighbors), dtype=dmat.dtype) for i in numba.prange(n_samples_transform): for j in numba.prange(n_neighbors): submat[i, j] = dmat[i, indices_col[i...
Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consists of the indices of the columns. n_neighbors: int...
389,080
def _gte(field, value, document): try: return document.get(field, None) >= value except TypeError: return False
Returns True if the value of a document field is greater than or equal to a given value
389,081
def _init_args(self): p = argparse.ArgumentParser(__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) p.add_argument(, type=str, nargs=3, help=) p.add_argument(, default=None, type=str, ...
Get enrichment arg parser.
389,082
def run(self): ret = eventlet.spawn(self.context(self.func)) eventlet.sleep(self.seconds) try: ret.wait() except Exception: traceback.print_exc() self.thread = eventlet.spawn(self.run)
Invoke the function repeatedly on a timer.
389,083
def filter_with_schema(self, model=None, context=None): if model is None or self.schema is None: return self._schema.filter( model=model, context=context if self.use_context else None )
Perform model filtering with schema
389,084
def list_all_by_reqvip(self, id_vip, pagination): uri = "api/pools/pool_list_by_reqvip/" data = dict() data["start_record"] = pagination.start_record data["end_record"] = pagination.end_record data["asorting_cols"] = pagination.asorting_cols data["searchable_c...
List All Pools To Populate Datatable :param pagination: Object Pagination :return: Following dictionary:{ "total" : < total >, "pools" :[{ "id": < id > ...
389,085
def setup_logging(): fmt = handler_stderr = logging.StreamHandler(sys.stderr) handler_stderr.setFormatter(logging.Formatter(fmt)) if OPTIONS[] == 1: handler_stderr.addFilter(logging.Filter(__name__)) root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) root_l...
Called when __name__ == '__main__' below. Sets up logging library. All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages.
389,086
def _padleft(width, s, has_invisible=True): iwidth = width + len(s) - len(_strip_invisible(s)) if has_invisible else width fmt = "{0:>%ds}" % iwidth return fmt.format(s)
Flush right. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True
389,087
def global_defaults(): defaults = InvokeConfig.global_defaults() ours = { "connect_kwargs": {}, "forward_agent": False, "gateway": None, "load_ssh_configs": True, "port": 22, ...
Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtrees controlling behavior of ``run``...
389,088
def reward(self, action=None): reward = 0. if self._check_success(): reward = 1.0 if self.reward_shaping: cube_pos = self.sim.data.body_xpos[self.cube_body_id] gripper_site_pos = self.sim.data.site_xpos[self.eef_site_...
Reward function for the task. The dense reward has three components. Reaching: in [0, 1], to encourage the arm to reach the cube Grasping: in {0, 0.25}, non-zero if arm is grasping the cube Lifting: in {0, 1}, non-zero if arm has lifted the cube The sparse reward o...
389,089
def SendVoicemail(self, Username): if self._Api.protocol >= 6: self._DoCommand( % Username) else: self._DoCommand( % Username)
Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet.
389,090
def list_files(tag=None, sat_id=None, data_path=None, format_str=None, supported_tags=None, fake_daily_files_from_monthly=False, two_digit_year_break=None): if data_path is not None: if format_str is None: try: format_str = supported_ta...
Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are <tag strings>...
389,091
def read(self, to_read, timeout_ms): if not isinstance(to_read, baseinteger): raise TypeError("to_read can only be an instance of type baseinteger") if not isinstance(timeout_ms, baseinteger): raise TypeError("timeout_ms can only be an instance of type baseinteger") ...
Reads data from this file. in to_read of type int Number of bytes to read. in timeout_ms of type int Timeout (in ms) to wait for the operation to complete. Pass 0 for an infinite timeout. return data of type str Array of data read. rais...
389,092
def _split_symbol_mappings(df, exchanges): mappings = df[list(mapping_columns)] with pd.option_context(, None): mappings[] = mappings.index mappings.reset_index(drop=True, inplace=True) asset_exchange = df[ [, ] ].sort_values().groupby(level=0)[].nth(-1) _check_symbol...
Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_info : pd.DataFrame The asset info with one ...
389,093
def sleep_and_retry(func): @wraps(func) def wrapper(*args, **kargs): while True: try: return func(*args, **kargs) except RateLimitException as exception: time.sleep(exception.period_remaining) return wrapper
Return a wrapped function that rescues rate limit exceptions, sleeping the current thread until rate limit resets. :param function func: The function to decorate. :return: Decorated function. :rtype: function
389,094
def filter_and_transform_data(df, settings): df["length_filter"] = True settings["filtered"] = False if settings.get("alength") and settings.get("bam"): settings["lengths_pointer"] = "aligned_lengths" logging.info("Using aligned read lengths for plotting.") else: settings["...
Perform filtering on the data based on arguments set on commandline - use aligned length or sequenced length (bam mode only) - hide outliers from length plots* - hide reads longer than maxlength or shorter than minlength from length plots* - filter reads with a quality below minqual - use log10 scal...
389,095
def MatrixSolve(a, rhs, adj): return np.linalg.solve(a if not adj else _adjoint(a), rhs),
Matrix solve op.
389,096
def validate(self, collection: BioCCollection): for document in collection.documents: self.validate_doc(document)
Validate a single collection.
389,097
def _timeout_handler(self, signum, frame): msgfmt = self.exit(code=self._timeout_code, message=msgfmt.format(self._timeout_delay))
internal timeout handler
389,098
def write(self, data): if self._ignore_write_operations: return assert self.is_connected() try: self._connection.send(data.encode()) except socket.error: self.close() self._ignore_write_operations = True
Sends some data to the client.
389,099
def _read_configuration(config_filename): config = ConfigParser() config.read(config_filename) if in config[]: path = os.path.dirname(config_filename) + + config.get(, ) config_supplement = ConfigParser() config_supplement.read(path) else: ...
Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser)