Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,000
def metric(self, name, filter_=None, description=""): return Metric(name, filter_, client=self, description=description)
Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be constructed. :type filter_: str :param filter_: the advanced logs filter expression defining the entries tracked by the metric. If not ...
365,001
def connect_edges(graph): paths = [] for start, end in graph.array(graph.kdims): start_ds = graph.nodes[:, :, start] end_ds = graph.nodes[:, :, end] if not len(start_ds) or not len(end_ds): raise ValueError() start = start_ds.array(start_ds.kdims[:2]) end...
Given a Graph element containing abstract edges compute edge segments directly connecting the source and target nodes. This operation just uses internal HoloViews operations and will be a lot slower than the pandas equivalent.
365,002
def recognize_using_websocket(self, audio, content_type, recognize_callback, model=None, language_customization_id=None, ...
Sends audio for speech recognition using web sockets. :param AudioSource audio: The audio to transcribe in the format specified by the `Content-Type` header. :param str content_type: The type of the input: audio/basic, audio/flac, audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg...
365,003
def delete(self, *objects, **kwargs): t re-call the object force = kwargs.get() from .model import Model, SKIP_ON_DELETE flat = [] items = deque() items.extend(objects) types = set() while items: o = items.popleft() if isi...
This method offers the ability to delete multiple entities in a single round trip to Redis (assuming your models are all stored on the same server). You can call:: session.delete(obj) session.delete(obj1, obj2, ...) session.delete([obj1, obj2, ...]) The key...
365,004
def zrange(key, start, stop, host=None, port=None, db=None, password=None): * server = _connect(host, port, db, password) return server.zrange(key, start, stop)
Get a range of values from a sorted set in Redis by index CLI Example: .. code-block:: bash salt '*' redis.zrange foo_sorted 0 10
365,005
def write_table(table, target, tablename=None, ilwdchar_compat=None, **kwargs): if tablename is None: tablename = table.meta.get(, None) if tablename is None: raise ValueError("please pass ``tablename=`` to specify the target " "LIGO_LW Table Nam...
Write a `~astropy.table.Table` to file in LIGO_LW XML format This method will attempt to write in the new `ligo.lw` format (if ``ilwdchar_compat`` is ``None`` or ``False``), but will fall back to the older `glue.ligolw` (in that order) if that fails (if ``ilwdchar_compat`` is ``None`` or ``True``).
365,006
def load_build_config(self, config=None): config = configs[0] return config
load a google compute config, meaning that we have the following cases: 1. the user has not provided a config file directly, we look in env. 2. the environment is not set, so we use a reasonable default 3. if the final string is not found as a file, we look for it in library 4. we load the ...
365,007
def hpx_to_coords(h, shape): x, z = hpx_to_axes(h, shape) x = np.sqrt(x[0:-1] * x[1:]) z = z[:-1] + 0.5 x = np.ravel(np.ones(shape) * x[:, np.newaxis]) z = np.ravel(np.ones(shape) * z[np.newaxis, :]) return np.vstack((x, z))
Generate an N x D list of pixel center coordinates where N is the number of pixels and D is the dimensionality of the map.
365,008
def weld_align(df_index_arrays, df_index_weld_types, series_index_arrays, series_index_weld_types, series_data, series_weld_type): weld_obj_index_df = weld_arrays_to_vec_of_struct(df_index_arrays, df_index_weld_types) weld_obj_series_dict = weld_data_to_dict(series_index_array...
Returns the data from the Series aligned to the DataFrame index. Parameters ---------- df_index_arrays : list of (numpy.ndarray or WeldObject) The index columns as a list. df_index_weld_types : list of WeldType series_index_arrays : numpy.ndarray or WeldObject The index of the Serie...
365,009
def can(ability, add_headers=None): client = ClientMixin(api_key=None) try: client.request(, endpoint= % ability, add_headers=add_headers) return True except Exception: pass return False
Test whether an ability is allowed.
365,010
def sendMessage(self, exchange, routing_key, message, properties=None, UUID=None): if properties is None: properties = pika.BasicProperties( content_type=self.content_type, delivery_mode=1, headers={} ) ...
With this function, you can send message to `exchange`. Args: exchange (str): name of exchange you want to message to be delivered routing_key (str): which routing key to use in headers of message message (str): body of message propert...
365,011
def update(context, id, etag, name, password, email, fullname, team_id, active): result = user.update(context, id=id, etag=etag, name=name, password=password, team_id=team_id, state=utils.active_string(active), email=email, ...
update(context, id, etag, name, password, email, fullname, team_id, active) Update a user. >>> dcictl user-update [OPTIONS] :param string id: ID of the user to update [required] :param string etag: Entity tag of the user resource [required] :param string name: Name of the user :...
365,012
def get_vars_in_expression(source): import compiler from compiler.ast import Node def get_vars_body(node, var_list=[]): if isinstance(node, Node): if node.__class__.__name__ == : for child in node.getChildren(): if child...
Get list of variable names in a python expression.
365,013
def get_time(self): if (self.steam_time_offset is None or (self.align_time_every and (time() - self._offset_last_check) > self.align_time_every) ): self.steam_time_offset = get_time_offset() if self.steam_time_offset is not None: self._offs...
:return: Steam aligned timestamp :rtype: int
365,014
def uncomment(comment): parent = comment.parentNode h = html.parser.HTMLParser() data = h.unescape(comment.data) try: node = minidom.parseString(data).firstChild except xml.parsers.expat.ExpatError: log.error() return None else: parent.replaceChild(node, co...
Converts the comment node received to a non-commented element, in place, and will return the new node. This may fail, primarily due to special characters within the comment that the xml parser is unable to handle. If it fails, this method will log an error and return None
365,015
def save_default_values(self): for parameter_container in self.default_value_parameter_containers: parameters = parameter_container.get_parameters() for parameter in parameters: set_inasafe_default_value_qsetting( self.settings, ...
Save InaSAFE default values.
365,016
def transacted(func): def transactionified(item, *a, **kw): return item.store.transact(func, item, *a, **kw) return mergeFunctionMetadata(func, transactionified)
Return a callable which will invoke C{func} in a transaction using the C{store} attribute of the first parameter passed to it. Typically this is used to create Item methods which are automatically run in a transaction. The attributes of the returned callable will resemble those of C{func} as closely a...
365,017
def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.build_slug())[:self._meta.get_field("slug").max_length] if not self.is_indexed: if kwargs is None: kwargs = {} kwargs["index"] = False content = super(Content...
creates the slug, queues up for indexing and saves the instance :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.content.Content`
365,018
def remove(self, id): before_len = len(self.model.db) self.model.db = [t for t in self.model.db if t["id"] != id] if not self._batch.enable.is_set(): self.model.save_db() return before_len - len(self.model.db)
Remove a object by id Args: id (int): Object's id should be deleted Returns: len(int): affected rows
365,019
async def get_data(self): try: with async_timeout.timeout(5, loop=self._loop): response = await self._session.get( .format(self.url, self.sensor_id)) _LOGGER.debug( "Response from luftdaten.info: %s", response.status) ...
Retrieve the data.
365,020
def _serve_forever_wrapper(self, _srv, poll_interval=0.1): self.logger.info(.format( address_to_str(_srv.local_address), address_to_str(_srv.remote_address)) ) _srv.serve_forever(poll_interval) self.logger.info(.format( address_to_str(_srv....
Wrapper for the server created for a SSH forward
365,021
def bifurcation_partitions(neurites, neurite_type=NeuriteType.all): return map(_bifurcationfunc.bifurcation_partition, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, neurite_filter=is_type(neurite_type)))
Partition at bifurcation points of a collection of neurites
365,022
def encode_multiple_layers(out, features_by_layer, zoom): precision = precision_for_zoom(zoom) geojson = {} for layer_name, features in features_by_layer.items(): fs = create_layer_feature_collection(features, precision) geojson[layer_name] = fs json.dump(geojson, out)
features_by_layer should be a dict: layer_name -> feature tuples
365,023
def create_el(name, text=None, attrib=None): if attrib is None: attrib = {} el = ET.Element(name, attrib) if text is not None: el.text = text return el
Create element with given attributes and set element.text property to given text value (if text is not None) :param name: element name :type name: str :param text: text node value :type text: str :param attrib: attributes :type attrib: dict :returns: xml element :rtype: Element
365,024
def _parse_log_statement(options): for i in options: if _is_reference(i): _add_reference(i, _current_statement) elif _is_junction(i): _add_junction(i) elif _is_inline_definition(i): _add_inline_definition(i, _current_statement)
Parses a log path.
365,025
def join_left(self, right_table=None, fields=None, condition=None, join_type=, schema=None, left_table=None, extract_fields=True, prefix_fields=False, field_prefix=None, allow_duplicates=False): return self.join( right_table=right_table, field...
Wrapper for ``self.join`` with a default join of 'LEFT JOIN' :type right_table: str or dict or :class:`Table <querybuilder.tables.Table>` :param right_table: The table being joined with. This can be a string of the table name, a dict of {'alias': table}, or a ``Table`` instance :ty...
365,026
def create(self, cid, configData): configArgs = {: cid, : configData, : True} cid = self.server.call(, "/config/create", configArgs, forceText=True, headers=TextAcceptHeader) new_config = Config(cid, self.server) return new_config
Create a new named (cid) configuration from a parameter dictionary (config_data).
365,027
def configure(self, cnf=None, **kw): if cnf == : return , self._drag_cols elif cnf == : return , self._drag_rows elif cnf == : return , self._sortable if isinstance(cnf, dict): kwargs = cnf.copy() kwargs.update(kw) ...
Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Table.keys`. See :meth:`~Table.__init__` for a description of the widget specific option.
365,028
def apply_slippage_penalty(returns, txn_daily, simulate_starting_capital, backtest_starting_capital, impact=0.1): mult = simulate_starting_capital / backtest_starting_capital simulate_traded_shares = abs(mult * txn_daily.amount) simulate_traded_dollars = txn_daily.price * si...
Applies quadratic volumeshare slippage model to daily returns based on the proportion of the observed historical daily bar dollar volume consumed by the strategy's trades. Scales the size of trades based on the ratio of the starting capital we wish to test to the starting capital of the passed backtest ...
365,029
def _get_sorter(subpath=, **defaults): @restrict_access(scope=) def _sorted(self, *args, **kwargs): if not kwargs.get(): kwargs[] = {} for key, value in six.iteritems(defaults): kwargs[].setdefault(key, value) url = urljoin(self._url, subpath) ...
Return function to generate specific subreddit Submission listings.
365,030
def add_reporting_args(parser): g = parser.add_argument_group() g.add_argument(, , default=None, type = str_type, metavar = file_mv, help = textwrap.dedent()) g.add_argument(, , action=, help = ) g.add_argument(, , action=, help = ) return parser
Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created.
365,031
def list(self, teamId=None, rType=None, maxResults=C.MAX_RESULT_DEFAULT, limit=C.ALL): queryParams = {: teamId, : rType, : maxResults} queryParams = self.clean_query_Dict(queryParams) ret = self.send_request(C.GET, self.end, data=queryParams, limit=limit) return [Room(self.t...
rType can be DIRECT or GROUP
365,032
async def cancel_scheduled_messages(self, *sequence_numbers): if not self.running: await self.open() numbers = [types.AMQPLong(s) for s in sequence_numbers] request_body = {: types.AMQPArray(numbers)} return await self._mgmt_request_response( REQUEST_RESP...
Cancel one or more messages that have previsouly been scheduled and are still pending. :param sequence_numbers: The seqeuence numbers of the scheduled messages. :type sequence_numbers: int Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py ...
365,033
def patch(self, deviceId): try: device = self.recordingDevices.get(deviceId) if device.status == RecordingDeviceStatus.INITIALISED: errors = self._handlePatch(device) if len(errors) == 0: return device, 200 else...
Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometerSensitivity: 2 } A heartbeat is...
365,034
def zrevrank(self, name, value): with self.pipe as pipe: return pipe.zrevrank(self.redis_key(name), self.valueparse.encode(value))
Returns the ranking in reverse order for the member :param name: str the name of the redis key :param member: str
365,035
def dump_to_store(self, store, **kwargs): from ..backends.api import dump_to_store return dump_to_store(self, store, **kwargs)
Store dataset contents to a backends.*DataStore object.
365,036
def add_resource(self, format, resource, locale, domain=None): if domain is None: domain = self._assert_valid_locale(locale) self.resources[locale].append([format, resource, domain]) if locale in self.fallback_locales: self.catalogues = {} else:...
Adds a resource @type format: str @param format: Name of the loader (@see add_loader) @type resource: str @param resource: The resource name @type locale: str @type domain: str @raises: ValueError If the locale contains invalid characters @return:
365,037
def _kbstr_to_cimval(key, val): if val[0] == and val[-1] == : cimval = val[1:-1] cimval = r...
Convert a keybinding value string as found in a WBEM URI into a CIM object or CIM data type, and return it.
365,038
def tokhex(length=10, urlsafe=False): if urlsafe is True: return secrets.token_urlsafe(length) return secrets.token_hex(length)
Return a random string in hexadecimal
365,039
def absent(name, auth=None, **kwargs): rule_id = kwargs[] ret = {: rule_id, : {}, : True, : } __salt__[](auth) secgroup = __salt__[]( name=name, filters={: kwargs[]} ) return ret
Ensure a security group rule does not exist name name or id of the security group rule to delete rule_id uuid of the rule to delete project_id id of project to delete rule from
365,040
def to_signed_str(self, private, public, passphrase=None): from pyxmli import xmldsig try: from Crypto.PublicKey import RSA except ImportError: raise ImportError( \ \ ) if not isins...
Returns a signed version of the invoice. @param private:file Private key file-like object @param public:file Public key file-like object @param passphrase:str Private key passphrase if any. @return: str
365,041
def brkl2d(arr,interval): color1r1g1b1a1color2r2g2b2a2 lngth = arr.__len__() brkseqs = elel.init_range(0,lngth,interval) l = elel.broken_seqs(arr,brkseqs) d = elel.mapv(l,lambda ele:{ele[0]:ele[1:]}) return(d)
arr = ["color1","r1","g1","b1","a1","color2","r2","g2","b2","a2"] >>> brkl2d(arr,5) [{'color1': ['r1', 'g1', 'b1', 'a1']}, {'color2': ['r2', 'g2', 'b2', 'a2']}]
365,042
def preferred_ip(vm_, ips): ipv4ipv6 proto = config.get_cloud_config_value( , vm_, __opts__, default=, search_global=False ) family = socket.AF_INET if proto == : family = socket.AF_INET6 for ip in ips: try: socket.inet_pton(family, ip) return ip ...
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
365,043
def translate_update(blob): "converts JSON parse output to self-aware objects" return {translate_key(k):parse_serialdiff(v) for k,v in blob.items()}
converts JSON parse output to self-aware objects
365,044
def _path(self, key): hash_type, parts_count = self._HASHES[self._hash_type] h = hash_type(encode(key)).hexdigest() parts = [h[i:i+2] for i in range(0, len(h), 2)][:parts_count] return os.path.join(self._directory, os.path.sep.join(parts), h)
Get the full path for the given cache key. :param key: The cache key :type key: str :rtype: str
365,045
def update(self): functions.check_valid_bs_range(self) self.en_date = values.START_EN_DATE + \ ( self - NepDate( values.START_NP_YEAR, 1, 1 ) ) ...
Updates information about the NepDate
365,046
def send(self, msg): logger.debug("{}'s elector sending {}".format(self.name, msg)) self.outBox.append(msg)
Send a message to the node on which this replica resides. :param msg: the message to send
365,047
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): resources = [] if self.Events: for logical_id, event_dict in self.Events.items(): try: eventsource = self.event_resolver.resolve_resource_typ...
Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_role: generated Lambda execution role :param implicit_api: Global Implicit API resource where the implicit APIs...
365,048
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: return ( b + b"\n".join(js_embed) + b"\n//]]>\n</script>" )
Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output.
365,049
def get_configured_consensus_module(block_id, state_view): settings_view = SettingsView(state_view) default_consensus = \ if block_id == NULL_BLOCK_IDENTIFIER else consensus_module_name = settings_view.get_setting( , default_value=default_consensus) re...
Returns the consensus_module based on the consensus module set by the "sawtooth_settings" transaction family. Args: block_id (str): the block id associated with the current state_view state_view (:obj:`StateView`): the current state view to use for setting values...
365,050
def unregister_callback(self, type_, from_, *, wildcard_resource=True): if from_ is None or not from_.is_bare: wildcard_resource = False self._map.pop((type_, from_, wildcard_resource))
Unregister a callback function. :param type_: Stanza type to listen for, or :data:`None` for a wildcard match. :param from_: Sender to listen for, or :data:`None` for a full wildcard match. :type from_: :class:`aioxmpp.JID` or :data:`None` :pa...
365,051
def encode_kv_node(keypath, child_node_hash): if keypath is None or keypath == b: raise ValidationError("Key path can not be empty") validate_is_bytes(keypath) validate_is_bytes(child_node_hash) validate_length(child_node_hash, 32) return KV_TYPE_PREFIX + encode_from_bin_keypath(keypath...
Serializes a key/value node
365,052
def system_monitor_SFM_threshold_marginal_threshold(self, **kwargs): config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") SFM = ET.SubElement(system_monitor, "SFM") threshold = ET.SubElement(S...
Auto Generated Code
365,053
def read_cs_raw_symmetrized_tensors(self): header_pattern = r"\s+-{50,}\s+" \ r"\s+Absolute Chemical Shift tensors\s+" \ r"\s+-{50,}$" first_part_pattern = r"\s+UNSYMMETRIZED TENSORS\s+$" row_pattern = r"\s+".join([r"([-]?\d+\.\d+)"] * 3...
Parse the matrix form of NMR tensor before corrected to table. Returns: nsymmetrized tensors list in the order of atoms.
365,054
def start(self): assert not self.watching def selector(evt): if evt.is_directory: return False path = evt.path if path in self._last_fnames: return False for pattern in self.skip_pattern.split(";"): if fnmatch(path, pattern.strip()): return False ...
Starts watching the path and running the test jobs.
365,055
def f16(op): op = float(op) negative = op < 0 if negative: op = -op DE = int(op) HL = int((op - DE) * 2**16) & 0xFFFF DE &= 0xFFFF if negative: DE ^= 0xFFFF HL ^= 0xFFFF DEHL = ((DE << 16) | HL) + 1 HL = DEHL & 0xFFFF DE = (DEHL >> 1...
Returns a floating point operand converted to 32 bits unsigned int. Negative numbers are returned in 2 complement. The result is returned in a tuple (DE, HL) => High16 (Int part), Low16 (Decimal part)
365,056
def SetAttributes(self, urn, attributes, to_delete, add_child_index=True, mutation_pool=None): attributes[AFF4Object.SchemaCls.LAST] = [ rdfvalue.RDFDatetime.Now().SerializeToDataStore() ] to_de...
Sets the attributes in the data store.
365,057
def _untracked_custom_unit_found(name, root=None): system = _root(, root) unit_path = os.path.join(system, _canonical_unit_name(name)) return os.access(unit_path, os.R_OK) and not _check_available(name)
If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False.
365,058
def make_witness_input(outpoint, sequence): if in riemann.get_current_network_name(): return tx.DecredTxIn( outpoint=outpoint, sequence=utils.i2le_padded(sequence, 4)) return tx.TxIn(outpoint=outpoint, stack_script=b, redeem_script=b, ...
Outpoint, int -> TxIn
365,059
def _make_context_immutable(context): def make_immutable(val): if isinstance(val, Mapping): return MappingProxyType(val) else: return val if not isinstance(context, (str, Mapping)): try: return tuple([make_immutable(val) for val in context]) ...
Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType. Otherwise, return as-is.
365,060
def to_coords(self): data = self.native first_byte = data[0:1] if first_byte == b: remaining = data[1:] field_len = len(remaining) // 2 x = int_from_bytes(remaining[0:field_len]) y = int_from_bytes(remaining[field_len:]) ...
Returns the X and Y coordinates for this EC point, as native Python integers :return: A 2-element tuple containing integers (X, Y)
365,061
def xpath(C, node, path, namespaces=None, extensions=None, smart_strings=True, **args): return node.xpath( path, namespaces=namespaces or C.NS, extensions=extensions, smart_strings=smart_strings, **args )
shortcut to Element.xpath()
365,062
def get_repr(self, obj, referent=None): objtype = type(obj) typename = str(objtype.__module__) + "." + objtype.__name__ prettytype = typename.replace("__builtin__.", "") name = getattr(obj, "__name__", "") if name: prettytype = "%s %r" % (prettytype, name) ...
Return an HTML tree block describing the given object.
365,063
def one_hot_encoding(labels, num_classes, scope=None): with tf.name_scope(scope, , [labels]): batch_size = labels.get_shape()[0] indices = tf.expand_dims(tf.range(0, batch_size), 1) labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype) concated = tf.concat(axis=1, values=[indices, labels]) ...
Transform numeric labels into onehot_labels. Args: labels: [batch_size] target labels. num_classes: total number of classes. scope: Optional scope for name_scope. Returns: one hot encoding of the labels.
365,064
def compare_table_cols(a, b): return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in b.getElementsByTagName(ligolw.Column.tagName)))
Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise.
365,065
def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): tree = _FieldMaskTree(self) tree.MergeMessage( source, destination, replace_message_field, replace_repeated_field)
Merges fields specified in FieldMask from source to destination. Args: source: Source message. destination: The destination message to be merged into. replace_message_field: Replace message field if True. Merge message field if False. replace_repeated_field: Replace repeated field...
365,066
def print_evaluation(period=1, show_stdv=True): def _callback(env): if period > 0 and env.evaluation_result_list and (env.iteration + 1) % period == 0: result = .join([_format_eval_result(x, show_stdv) for x in env.evaluation_result_list]) print( % (env.iteration + 1, result)) ...
Create a callback that prints the evaluation results. Parameters ---------- period : int, optional (default=1) The period to print the evaluation results. show_stdv : bool, optional (default=True) Whether to show stdv (if provided). Returns ------- callback : function ...
365,067
def random_draw(self, size=None): draw_1 = self.p1.random_draw(size=size) draw_2 = self.p2.random_draw(size=size) if draw_1.ndim == 1: return scipy.hstack((draw_1, draw_2)) else: return scipy.vstack((draw_1, draw_2))
Draw random samples of the hyperparameters. The outputs of the two priors are stacked vertically. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is...
365,068
def clipping_params(ts, capacity=100): ts_sorted = ts.order(ascending=False) i, t0, t1, integral = 1, None, None, 0 while integral <= capacity and i+1 < len(ts): i += 1 t0_within_capacity = t0 t1_within_capacity = t1 t0 = min(ts_sorted.index[:i]) t1 = max(ts_sort...
Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacity (float): Total "funds" or "energy" available...
365,069
def _to_span(x, idx=0): if isinstance(x, Candidate): return x[idx].context elif isinstance(x, Mention): return x.context elif isinstance(x, TemporarySpanMention): return x else: raise ValueError(f"{type(x)} is an invalid argument type")
Convert a Candidate, Mention, or Span to a span.
365,070
def parse_host(entity, default_port=DEFAULT_PORT): host = entity port = default_port if entity[0] == : host, port = parse_ipv6_literal_host(entity, default_port) elif entity.endswith(".sock"): return entity, default_port elif entity.find() != -1: if entity.count() > 1: ...
Validates a host string Returns a 2-tuple of host followed by port where port is default_port if it wasn't specified in the string. :Parameters: - `entity`: A host or host:port string where host could be a hostname or IP address. - `default_port`: The port number to use...
365,071
def _fake_openqueryinstances(self, namespace, **params): self._validate_namespace(namespace) self._validate_open_params(**params) result = self._fake_execquery(namespace, **params) objects = [] if result is None else [x[2] for x in result[0][2]] ...
Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenQueryInstances` with data from the instance repository.
365,072
def init(app_id, app_key=None, master_key=None, hook_key=None): if (not app_key) and (not master_key): raise RuntimeError() global APP_ID, APP_KEY, MASTER_KEY, HOOK_KEY APP_ID = app_id APP_KEY = app_key MASTER_KEY = master_key if hook_key: HOOK_KEY = hook_key else: ...
初始化 LeanCloud 的 AppId / AppKey / MasterKey :type app_id: string_types :param app_id: 应用的 Application ID :type app_key: None or string_types :param app_key: 应用的 Application Key :type master_key: None or string_types :param master_key: 应用的 Master Key :param hook_key: application's hook key ...
365,073
def get_tower_results(iterator, optimizer, dropout_rates): rs batch we calculate and return the optimization gradients and the average loss across towers. tower_%ds labels (Y) of this tower avg_loss = calculate_mean_edit_distance_and_loss(iterator, dropout_rates, reuse=i > 0) ...
r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers.
365,074
def ct_bytes_compare(a, b): if not isinstance(a, bytes): a = a.decode() if not isinstance(b, bytes): b = b.decode() if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= x ^ y return (result == 0)
Constant-time string compare. http://codahale.com/a-lesson-in-timing-attacks/
365,075
def getBranch(self, name, **context): for keyLen in self._vars.getKeysLens(): subName = name[:keyLen] if subName in self._vars: return self._vars[subName] raise error.NoSuchObjectError(name=name, idx=context.get())
Return a branch of this tree where the 'name' OID may reside
365,076
def extract_named_group(text, named_group, matchers, return_presence=False): presence = False for matcher in matchers: if isinstance(matcher, str): v = re.search(matcher, text, flags=re.DOTALL) if v: dict_result = v.groupdict() try: ...
Return ``named_group`` match from ``text`` reached by using a matcher from ``matchers``. It also supports matching without a ``named_group`` in a matcher, which sets ``presence=True``. ``presence`` is only returned if ``return_presence=True``.
365,077
def entry_set(self, predicate=None): if predicate: predicate_data = self._to_data(predicate) return self._encode_invoke(map_entries_with_predicate_codec, predicate=predicate_data) else: return self._encode_invoke(map_entry_set_codec)
Returns a list clone of the mappings contained in this map. **Warning: The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param predicate: (Predicate), predicate for the map to filter entries (optional). :return: (Sequence), the l...
365,078
def vprjp(vin, plane): vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(3) libspice.vprjp_c(vin, ctypes.byref(plane), vout) return stypes.cVectorToPython(vout)
Project a vector onto a specified plane, orthogonally. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vprjp_c.html :param vin: The projected vector. :type vin: 3-Element Array of floats :param plane: Plane containing vin. :type plane: spiceypy.utils.support_types.Plane :return: Vect...
365,079
def _drawBackground(self, scene, painter, rect): rect = scene.sceneRect() if scene == self.uiChartVIEW.scene(): self.renderer().drawGrid(painter, rect, self.showGrid(), ...
Draws the backgroud for a particular scene within the charts. :param scene | <XChartScene> painter | <QPainter> rect | <QRectF>
365,080
def get_resource(self): if not bool(self._my_map[]): raise errors.IllegalState() mgr = self._get_provider_manager() if not mgr.supports_resource_lookup(): raise errors.OperationFailed() lookup_session = mgr.get_resource_lookup_session(proxy=getat...
Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
365,081
def score_hist(df, columns=None, groupby=None, threshold=0.7, stacked=True, bins=20, percent=True, alpha=0.33, show=True, block=False, save=False): df = df if columns is None else df[([] if groupby is None else [groupby]) + list(columns)].copy() if groupby is not None or threshold is not Non...
Plot multiple histograms on one plot, typically of "score" values between 0 and 1 Typically the groupby or columns of the dataframe are the classification categories (0, .5, 1) And the values are scores between 0 and 1.
365,082
def NonNegIntStringToInt(int_string, problems=None): match = re.match(r"^(?:0|[1-9]\d*)$", int_string) problems.InvalidNonNegativeIntegerValue(int_string) return parsed_value
Convert an non-negative integer string to an int or raise an exception
365,083
def get_status(address=None): address = address or (config.dbserver.host, DBSERVER_PORT) return if socket_ready(address) else
Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running'
365,084
def delete_network_postcommit(self, context): network = context.current log_context("delete_network_postcommit: network", network) segments = context.network_segments tenant_id = network[] self.delete_segments(segments) self.delete_network(network) self...
Delete the network from CVX
365,085
def likelihood_weighting(X, e, bn, N): W = dict((x, 0) for x in bn.variable_values(X)) for j in xrange(N): sample, weight = weighted_sample(bn, e) W[sample[X]] += weight return ProbDist(X, W)
Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298'
365,086
def setRoute(self, vehID, edgeList): if isinstance(edgeList, str): edgeList = [edgeList] self._connection._beginMessage(tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_ROUTE, vehID, 1 + 4 + sum(map(len, edgeList)) + 4 * len(edgeList)) self._connect...
setRoute(string, list) -> None changes the vehicle route to given edges list. The first edge in the list has to be the one that the vehicle is at at the moment. example usage: setRoute('1', ['1', '2', '4', '6', '7']) this changes route for vehicle id 1 to edges 1-2-4-6-7
365,087
def is_ascii_obfuscation(vm): for classe in vm.get_classes(): if is_ascii_problem(classe.get_name()): return True for method in classe.get_methods(): if is_ascii_problem(method.get_name()): return True return False
Tests if any class inside a DalvikVMObject uses ASCII Obfuscation (e.g. UTF-8 Chars in Classnames) :param vm: `DalvikVMObject` :return: True if ascii obfuscation otherwise False
365,088
def notifications_mark_read(input_params={}, always_retry=True, **kwargs): return DXHTTPRequest(, input_params, always_retry=always_retry, **kwargs)
Invokes the /notifications/markRead API method.
365,089
def append(self, position, array): if not Gauged.map_append(self.ptr, position, array.ptr): raise MemoryError
Append an array to the end of the map. The position must be greater than any positions in the map
365,090
def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req=): raise NotImplementedError()
Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) or DataDesc objects Typically is ``data_iter.provide_data``. Can also be a list of (data name,...
365,091
def ostree_path(self): if self._ostree_path is None: self._ostree_path = os.path.join(self.tmpdir, "ostree-repo") subprocess.check_call(["ostree", "init", "--mode", "bare-user-only", "--repo", self._ostree_path]) return self._ostree_pat...
ostree repository -- content
365,092
def setup(self, app): super().setup(app) if isinstance(self.cfg.template_folders, str): self.cfg.template_folders = [self.cfg.template_folders] else: self.cfg.template_folders = list(self.cfg.template_folders) self.ctx_provider(lambda: {: self.app}) ...
Setup the plugin from an application.
365,093
def ConsultarDomicilios(self, nro_doc, tipo_doc=80, cat_iva=None): "Busca los domicilios, devuelve la cantidad y establece la lista" self.cursor.execute("SELECT direccion FROM domicilio WHERE " " tipo_doc=? AND nro_doc=? ORDER BY id ", [tipo_doc, ...
Busca los domicilios, devuelve la cantidad y establece la lista
365,094
def get_taf_alt_ice_turb(wxdata: [str]) -> ([str], str, [str], [str]): altimeter = icing, turbulence = [], [] for i, item in reversed(list(enumerate(wxdata))): if len(item) > 6 and item.startswith() and item[3:7].isdigit(): altimeter = wxdata.pop(i)[3:7] elif item.isdigit...
Returns the report list and removed: Altimeter string, Icing list, Turbulance list
365,095
def as_report_request(self, rules, timer=datetime.utcnow): if not self.service_name: raise ValueError(u) op = super(Info, self).as_operation(timer=timer) if op.operationId and op.operationName: labels = {} for known_label in rules.l...
Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServ...
365,096
def overlay(self, feature, color=, opacity=0.6): result = self.copy() if type(feature) == Table: if in feature: feature = feature[] else: feature = Circle.map_table(feature) if type(feature) in [list, n...
Overlays ``feature`` on the map. Returns a new Map. Args: ``feature``: a ``Table`` of map features, a list of map features, a Map, a Region, or a circle marker map table. The features will be overlayed on the Map with specified ``color``. ``color`` (``st...
365,097
def grav_pot(self, x, y, rho0, gamma, center_x=0, center_y=0): x_ = x - center_x y_ = y - center_y r = np.sqrt(x_**2 + y_**2) mass_3d = self.mass_3d(r, rho0, gamma) pot = mass_3d/r return pot
gravitational potential (modulo 4 pi G and rho0 in appropriate units) :param x: :param y: :param rho0: :param a: :param s: :param center_x: :param center_y: :return:
365,098
def get_active_forms_state(self): for term in self._isolated_terms: act = term.find() if act is None: continue if act.text == : is_active = True elif act.text == : is_active = False else: ...
Extract ActiveForm INDRA Statements.
365,099
def _calculatePredictedCells(self, activeBasalSegments, activeApicalSegments): cellsForBasalSegments = self.basalConnections.mapSegmentsToCells( activeBasalSegments) cellsForApicalSegments = self.apicalConnections.mapSegmentsToCells( activeApicalSegments) fullyDepolarizedCells = np.inters...
Calculate the predicted cells, given the set of active segments. An active basal segment is enough to predict a cell. An active apical segment is *not* enough to predict a cell. When a cell has both types of segments active, other cells in its minicolumn must also have both types of segments to be con...