Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
359,000
def list_corpus_files(dotted_path): corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION) paths = [] if os.path.isdir(corpus_path): paths = glob.glob(corpus_path + + CORPUS_EXTENSION, recursive=True) else: paths.append(corpus_path) paths.sort() return paths
Return a list of file paths to each data file in the specified corpus.
359,001
def policy_and_value_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): cur_layers = [] if bottom_layers is not None: cur_layers.extend(bottom_layers) cur_layers.extend([layers.Branch(), layers.Pa...
A policy and value net function.
359,002
def transformToNative(obj): if obj.isNative: return obj obj.isNative = True obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value)))) return obj
Turn obj.value into an Address.
359,003
def count_tokens(tokens, to_lower=False, counter=None): r if to_lower: tokens = [t.lower() for t in tokens] if counter is None: return Counter(tokens) else: counter.update(tokens) return counter
r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may look like:: (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd) Parameters ---------- tokens : list of str A source list of tok...
359,004
def by_user(self): users = [i for i in self.__get_users()] user_groups = {} group_results = { tuple(value): key for (key, value) in self.by_group().items() } for user in users: user_groups[user] = [] for user_list, group ...
Display group membership sorted by group. Returns: Array with a dictionary of group membership. For example: {'test.user': ['testgroup', 'testgroup2']}
359,005
def period(self, value: float): if value < 0: raise ValueError("Period must be greater or equal than zero.") self._period = timedelta(seconds=value)
Set the period. Args: value (float): seconds
359,006
def Page_addScriptToEvaluateOnNewDocument(self, source): assert isinstance(source, (str,) ), "Argument must be of type str. Received type: " % type( source) subdom_funcs = self.synchronous_command( , source=source) return subdom_funcs
Function path: Page.addScriptToEvaluateOnNewDocument Domain: Page Method name: addScriptToEvaluateOnNewDocument WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'source' (type: string) -> No description Returns: 'identifier' (type: ScriptIdentifier) -> I...
359,007
def markdown(value, extensions=settings.MARKDOWN_EXTENSIONS, extension_configs=settings.MARKDOWN_EXTENSION_CONFIGS, safe=False): return mark_safe(markdown_module.markdown( force_text(value), extensions=extensions, extension_configs=extension_configs, safe_mode=safe))
Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. :returns: A rendered markdown
359,008
def alias_log_entry(self, log_entry_id, alias_id): self._alias_id(primary_id=log_entry_id, equivalent_id=alias_id)
Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility. The primary ``Id`` of the ``LogEntry`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another log entry, it is reassigned to the given log ...
359,009
def modify_dbinstance(self, id, param_group=None, security_groups=None, preferred_maintenance_window=None, master_password=None, allocated_storage=None, instance_class=None, backup_retention_period=None, ...
Modify an existing DBInstance. :type id: str :param id: Unique identifier for the new instance. :type security_groups: list of str or list of DBSecurityGroup objects :param security_groups: List of names of DBSecurityGroup to authorize on this DBInstance...
359,010
def to_zarr(dataset, store=None, mode=, synchronizer=None, group=None, encoding=None, compute=True, consolidated=False): if isinstance(store, Path): store = str(store) if encoding is None: encoding = {} _validate_dataset_names(dataset) _validate_attrs(dataset) ...
This function creates an appropriate datastore for writing a dataset to a zarr ztore See `Dataset.to_zarr` for full API docs.
359,011
def put(self, local_path, path, atomic=True): self._connect() if self.sftp: self._sftp_put(local_path, path, atomic) else: self._ftp_put(local_path, path, atomic) self._close()
Put file from local filesystem to (s)FTP.
359,012
def get_shard_map(self, force_refresh=False): now = datetime.utcnow() if force_refresh is True or \ self.shard_map is None or \ (now - self.last_refresh).total_seconds() > self.refresh_ttl: self.last_refresh = now self.refr...
You can change this function to get the shard-map from somewhere/somehow place else in conjuction with save_shard_map().
359,013
def node_theta(nodelist, node): assert len(nodelist) > 0, "nodelist must be a list of items." assert node in nodelist, "node must be inside nodelist." i = nodelist.index(node) theta = -np.pi + i * 2 * np.pi / len(nodelist) return theta
Maps node to Angle. :param nodelist: Nodelist from the graph. :type nodelist: list. :param node: The node of interest. Must be in the nodelist. :returns: theta -- the angle of the node in radians.
359,014
def rolling_sum(self, window_start, window_end, min_observations=None): min_observations = self.__check_min_observations(min_observations) agg_op = None if self.dtype is array.array: agg_op = else: agg_op = return SArray(_proxy=self.__proxy__.bu...
Calculate a new SArray of the sum of different subsets over this SArray. Also known as a "moving sum" or "running sum". The subset that the sum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `win...
359,015
def authenticate(self): if "username" in self.options and "password" in self.options: self.login_oauth2( self.options["username"], self.options["password"], self.options.get()) elif "access_token" in self.options: if "refre...
Authenticate using data in `options`
359,016
def cli(self, eauth): ret = {} if not eauth: print() return ret fstr = .format(eauth) if fstr not in self.auth: print(( ).format(eauth)) print("Available eauth types: {0}".format(", ".join(self.auth.file_mapping....
Execute the CLI options to fill in the extra data needed for the defined eauth system
359,017
def removeidfobject(self, idfobject): key = idfobject.key.upper() self.idfobjects[key].remove(idfobject)
Remove an IDF object from the IDF. Parameters ---------- idfobject : EpBunch object The IDF object to remove.
359,018
def _cursor(self, name=None): if name: cursor = super(DatabaseWrapper, self)._cursor(name=name) else: cursor = super(DatabaseWrapper, self)._cursor() if (not get_limit_set_calls()) or not self.search_path_set: ...
Here it happens. We hope every Django db operation using PostgreSQL must go through this to get the cursor handle. We change the path.
359,019
def delete_org(self): if not self.created: self.logger.info( "Skipping org deletion: the scratch org has not been created" ) return command = sarge.shell_format("sfdx force:org:delete -p -u {0}", self.username) self.logger.info("Delet...
Uses sfdx force:org:delete to delete the org
359,020
def chunk(self, size): chunks = self._chunk(size) return self.__class__(list(map(self.__class__, chunks)))
Chunk the underlying collection. :param size: The chunk size :type size: int :rtype: Collection
359,021
def cell_nodes_x(self): decoder = self.decoder xcoord = self.xcoord data = self.data xbounds = decoder.get_cell_node_coord( data, coords=data.coords, axis=) if self.plotter.convert_radian: xbounds = convert_radian(xbounds, xcoord, xbounds) ...
The unstructured x-boundaries with shape (N, m) where m > 2
359,022
def read32(self, offset): if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") offset = self._adjust_offset(offset) self._validate_offset(offset, 4) return struct.unpack("=L", self.mapping[offset:offset + 4])[0]
Read 32-bits from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. Returns: int: 32-bit value read. Raises: TypeError: if `offset` type ...
359,023
def decode_body(cls, header, f): assert header.packet_type == MqttControlPacketType.unsubscribe decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len)) packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID) topics = [] while header.remaining_len > dec...
Generates a `MqttUnsubscribe` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `unsubscribe`. Parameters ---------- header: MqttFixedHeader f: file Object with a read method. Raises ------ DecodeError ...
359,024
def init(directory=None, multidb=False): if directory is None: directory = current_app.extensions[].directory config = Config() config.set_main_option(, directory) config.config_file_name = os.path.join(directory, ) config = current_app.extensions[].\ migrate.call_configure_call...
Creates a new migration repository
359,025
def getAttribute(self, attr: str) -> _AttrValueType: if attr == : if self.classList: return self.classList.toString() return None attr_node = self.getAttributeNode(attr) if attr_node is None: return None return attr_node.value
Get attribute of this node as string format. If this node does not have ``attr``, return None.
359,026
def _get_candidate_swap(resources, location, l2v, vertices_resources, fixed_vertices, machine): chip_resources = machine[location] vertices = l2v[location] to_move = [] i += 1 continue else: ver...
Given a chip location, select a set of vertices which would have to be moved elsewhere to accommodate the arrival of the specified set of resources. Parameters ---------- resources : {resource: value, ...} The amount of resources which are required at the specified location. location : ...
359,027
def serialize(point: Mapping, measurement=None, **extra_tags) -> bytes: tags = _serialize_tags(point, extra_tags) return ( f f f f ).encode()
Converts dictionary-like data into a single line protocol line (point)
359,028
def is_periodically_contiguous( self ): edges = self.sites_at_edges() is_contiguous = [ False, False, False ] along_x = any( [ s2 in s1.p_neighbours for s1 in edges[0] for s2 in edges[1] ] ) along_y = any( [ s2 in s1.p_neighbours for s1 in edges[2] for s2 in edges[3] ] ) ...
logical check whether a cluster connects with itself across the simulation periodic boundary conditions. Args: none Returns ( Bool, Bool, Bool ): Contiguity along the x, y, and z coordinate axes
359,029
def rpc_request(self, frame_out, connection_adapter=None): with self.rpc.lock: uuid = self.rpc.register_request(frame_out.valid_responses) self._connection.write_frame(self.channel_id, frame_out) return self.rpc.get_request( uuid, connection_adapter=c...
Perform a RPC Request. :param specification.Frame frame_out: Amqp frame. :rtype: dict
359,030
def iterate(self, image, feature_extractor, feature_vector): for scale, scaled_image_shape in self.scales(image): feature_extractor.prepare(image, scale) for bb in self.sample_scaled(scaled_image_shape): feature_extractor.extract_indexed(bb, feature_vector) yield bb....
iterate(image, feature_extractor, feature_vector) -> bounding_box Scales the given image, and extracts features from all possible bounding boxes. For each of the sampled bounding boxes, this function fills the given pre-allocated feature vector and yields the current bounding box. **Parameters:** ``...
359,031
def byteswap(s): assert len(s) % 2 == 0 parts = [] for i in range(0, len(s), 2): chunk = s[i:i + 2] newchunk = struct.pack(, *struct.unpack(, chunk)) parts.append(newchunk) return b.join(parts)
Swaps the endianness of the bytesting s, which must be an array of shorts (16-bit signed integers). This is probably less efficient than it should be.
359,032
def secondary_spin(mass1, mass2, spin1, spin2): mass1, mass2, spin1, spin2, input_is_array = ensurearray( mass1, mass2, spin1, spin2) ss = copy.copy(spin2) mask = mass1 < mass2 ss[mask] = spin1[mask] return formatreturn(ss, input_is_array)
Returns the dimensionless spin of the secondary mass.
359,033
def _handle_packed_metadata(self, node, scope, ctxt, stream): keyvals = node.metadata.keyvals if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals): raise errors.PfpError("Packed fields require a packer function to be set or pack and unpack functions to b...
Handle packed metadata
359,034
def __process_by_ccore(self): if isinstance(self.__initializer, kmeans_plusplus_initializer): initializer = wrapper.elbow_center_initializer.KMEANS_PLUS_PLUS else: initializer = wrapper.elbow_center_initializer.RANDOM result = wrapper.elbow(self.__data, s...
! @brief Performs processing using C++ implementation.
359,035
def push(self, key, value, priority=0): ckeys, cvals, use_str_keys = _ctype_key_value(key, value) if use_str_keys: check_call(_LIB.MXKVStorePushEx( self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority))) else: check_call(_LIB.MXKV...
Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an operator to the engine. The actual operation is executed asynchronously. If there are consecutive pushes to the same key, there is no guarantee on the serialization of pushes. ...
359,036
def get_slot_bindings(self): slot_bindings = yield from self._hypervisor.send(.format(self._name)) return slot_bindings
Returns slot bindings. :returns: slot bindings (adapter names) list
359,037
def _match_excluded(self, filename, patterns): return _wcparse._match_real( filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks )
Call match real directly to skip unnecessary `exists` check.
359,038
def _traverse_relationship_rev_objs(self, rel2dst2srcs, goobj_parent, goids_seen): parent_id = goobj_parent.id goids_seen.add(parent_id) for goid_altid in goobj_parent.alt_ids: goids_seen.add(goid_altid) for reltype, recs in go...
Traverse from source GO down children.
359,039
def bounding_ellipsoid(points, pointvol=0.): npoints, ndim = points.shape if pointvol < 0.: raise ValueError("You must specify a non-negative value " "for `pointvol`.") if npoints == 1: if pointvol > 0.: ctr = points[0] ...
Calculate the bounding ellipsoid containing a collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional The minimum volume occupied by a single point. When provided, used to set a minimum bo...
359,040
def sphere_triangle_cdf(dr, a, alpha): p0 = (dr+alpha)**2/(2*alpha**2)*(0 > dr)*(dr>-alpha) p1 = 1*(dr>0)-(alpha-dr)**2/(2*alpha**2)*(0<dr)*(dr<alpha) return (1-np.clip(p0+p1, 0, 1))
Cumulative distribution function for the traingle distribution
359,041
def get_default_config(self): config = super(UserScriptsCollector, self).get_default_config() config.update({ : , : , : 4, }) return config
Returns the default collector settings
359,042
def patch_match_hostname(): _old_match_hostname = ssl.match_hostname def _new_match_hostname(cert, hostname): if hostname.endswith(): pos = hostname.find() hostname = hostname[:pos].replace(, ) + hostname[pos:] return _old_match_hostname(cert, hostname) ssl.m...
Fixes https://github.com/boto/boto/issues/2836
359,043
def average_spectrogram(timeseries, method_func, stride, *args, **kwargs): try: timeseries, other = timeseries except ValueError: timeseries = timeseries other = None from ...spectrogram import Spectrogram nproc = kwargs.pop(, 1) epoch = timeseries.t0.value ...
Generate an average spectrogram using a method function Each time bin of the resulting spectrogram is a PSD generated using the method_func
359,044
def get(self, addr, count): addr -= self._start_addr data = self._data[addr:addr + count] if len(data) != count: addr += self._start_addr raise IndexError("Invalid address range [{: .format(addr, addr + count)) return data
Read list of ``count`` values at ``addr`` memory location in DataBank. :param addr: Address to read from :param count: Number of entries to retrieve :return: list of entry values :except IndexError: Raised if address range falls outside valid range
359,045
def common_install_python_env(self): sudo() sudo() run(.format(self.python_env_dir)) print(green()) print(green()) print()
Install python virtualenv
359,046
def on_init(app): docs_path = os.path.abspath(os.path.dirname(__file__)) root_path = os.path.abspath(os.path.join(docs_path, )) apidoc_path = if hasattr(sys, ): bin_path = os.path.abspath(os.path.join(sys.prefix, )) apidoc_path = os.path.join(bin_path, apidoc_path) ...
Run sphinx-apidoc after Sphinx initialization. Read the Docs won't run tox or custom shell commands, so we need this to avoid checking in the generated reStructuredText files.
359,047
def send_command_timing(self, *args, **kwargs): output = super(CiscoAsaSSH, self).send_command_timing(*args, **kwargs) if len(args) >= 1: command_string = args[0] else: command_string = kwargs["command_string"] if "changeto" in command_string: ...
If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change.
359,048
def get_label_items(self, label_id, top=None, skip=None): route_values = {} if label_id is not None: route_values[] = self._serialize.url(, label_id, ) query_parameters = {} if top is not None: query_parameters[] = self._serialize.query(, top, ) i...
GetLabelItems. Get items under a label. :param str label_id: Unique identifier of label :param int top: Max number of items to return :param int skip: Number of items to skip :rtype: [TfvcItem]
359,049
def updateLanguages(self, languages): url = self._url = "/languages/update" params = { "f" : "json", "languages" : languages } return self._post(url=url, param_dict=params, proxy_url=self._proxy_url, ...
You can use this operation to change which languages will have content displayed in portal search results. Parameters: languages - The JSON object containing all of the possible portal languages and their corresponding status (true or false).
359,050
def apply_path(self, repo): try: if repo.endswith(): repo = repo.split()[0] org, name = repo.split()[-2:] path = join(self.plugins_dir, org, name) cwd = getcwd() self.ensur...
Set path to where the repo is and return original path
359,051
def get_ligands(pdb_id): out = get_info(pdb_id, url_root = ) out = to_dict(out) return remove_at_sign(out[])
Return ligands of given PDB ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest Returns ------- out : dict A dictionary containing a list of ligands associated with the entry Examples -------- >>> ligand_dict = get_ligand...
359,052
def highlight(string, fg=None, bg=None, indices=[], end=, target=sys.stdout): if not string or not indices or (fg is bg is None): return p = 0 for k, g in itertools.groupby(enumerate(sorted(indices)), lambda x: x[0]-x[1]): tmp = lis...
Highlight characters using indices and print it to the target handle. fg and bg specify foreground- and background colors, respectively. The remaining keyword arguments are the same as for Python's built-in print function.
359,053
def transformer(self): ttype = self.embedding.lower() if ttype == : return MDS(n_components=2, random_state=self.random_state) if ttype == : return TSNE(n_components=2, random_state=self.random_state) raise YellowbrickValueError("unknown embedding ".f...
Creates the internal transformer that maps the cluster center's high dimensional space to its two dimensional space.
359,054
def parse_JSON(self, JSON_string): if JSON_string is None: raise parse_response_error.ParseResponseError() d = json.loads(JSON_string) current_time = round(time.time()) return stationhistory.StationHistory(None, None, current_time, ...
Parses a *StationHistory* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: a *StationHistory* instance or...
359,055
def _subperiod_tick(self, current_interval, intervals): self.refresh_from_db() for key, value in self.group_decisions.items(): self.subperiod_group_decisions[key] = value self.send(, self.subperiod_group_decisions) self.save(update_fields=[])
Tick each sub-period, copying group_decisions to subperiod_group_decisions.
359,056
def on_deleted(self, event): key = data = { : event.src_path, : event.is_directory, : os.path.dirname(event.src_path) } bmsg = BroadcastMessage(key=key, data=data) BroadcastManager.broadcast(bmsg)
Event Handler when a file is deleted
359,057
def dates(self, desc=None): c = self.dateinverse for key in self.keys(desc=desc): yield c(key)
Returns an iterable over ``datetime.date`` instances in the timeseries.
359,058
def notify_state_name_change(self, model, prop_name, info): if is_execution_status_update_notification_from_state_machine_model(prop_name, info): return overview = NotificationOverview(info, False, self.__class__.__name__) changed_model = overview[][-1] met...
Checks whether the name of a state was changed and change the tab label accordingly
359,059
def valid_url(url): regex = re.compile( r r r r, re.IGNORECASE) if not regex.match(url): raise argparse.ArgumentTypeError(.format(url)) return url
Validate url. :rtype: str :return: url :param str url: package homepage url.
359,060
def renormalize(self, modelparams): norm = modelparams[:, 0] * np.sqrt(self._dim) assert not np.sum(norm == 0) return modelparams / norm[:, None]
Renormalizes one or more states represented as model parameter vectors, such that each state has trace 1. :param np.ndarray modelparams: Array of shape ``(n_states, dim ** 2)`` representing one or more states as model parameter vectors. :return: The same state, normaliz...
359,061
def cons(self, i): if (self.b[i] == or self.b[i] == or self.b[i] == or self.b[i] == or self.b[i] == ): return 0 if self.b[i] == : if i == self.k0: return 1 else: return (not self.cons(i - 1)) r...
cons(i) is TRUE <=> b[i] is a consonant.
359,062
def init_realms(self, realms): self.realms = tuple(realm for realm in realms if isinstance(realm, realm_abcs.AuthorizingRealm)) self.register_cache_clear_listener()
:type realms: tuple
359,063
def delete_datasource(datasourceid, orgname=None, profile=): grafana* if isinstance(profile, string_types): profile = __salt__[](profile) response = requests.delete( .format(profile[], datasourceid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=prof...
Delete a datasource. datasourceid Id of the datasource. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. CLI Example: .. code-block:: bash salt '*' grafana4.delete_datasource <datasource_id>
359,064
def answer_inline_query( self, inline_query_id: str, results: List[InlineQueryResult], cache_time: int = 300, is_personal: bool = None, next_offset: str = "", switch_pm_text: str = "", switch_pm_parameter: str = "" ): return self.send(...
Use this method to send answers to an inline query. No more than 50 results per query are allowed. Args: inline_query_id (``str``): Unique identifier for the answered query. results (List of :obj:`InlineQueryResult <pyrogram.InlineQueryResult>`): ...
359,065
def wait_for_update(self, trigger_update=False): if trigger_update: self.update_now() from gi.repository import Gtk from gi.repository import GLib from threading import Event event = Event() def priority_handled(event): ...
Update canvas and handle all events in the gtk queue :param bool trigger_update: Whether to call update_now() or not
359,066
def infer_dtype_from_scalar(val, pandas_dtype=False): dtype = np.object_ if isinstance(val, np.ndarray): msg = "invalid ndarray passed to infer_dtype_from_scalar" if val.ndim != 0: raise ValueError(msg) dtype = val.dtype val = val.item() elif isinsta...
interpret the dtype from a scalar Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar belongs to pandas extension types is inferred as object
359,067
def merged_packages(env_packages, names): combined_packages = sorted(itertools.chain.from_iterable( env_packages[name].items() for name in names )) result = {} errors = set() for name, version in combined_packages: if name in result: if result[name] != versio...
Return union set of environment packages with given names >>> sorted(merged_packages( ... { ... 'a': {'x': 1, 'y': 2}, ... 'b': {'y': 2, 'z': 3}, ... 'c': {'z': 3, 'w': 4} ... }, ... ['a', 'b'] ... ).items()) [('x', 1), ('y', 2), ('z', 3)]
359,068
def execFontDialog(self): currentFont = self.getData() newFont, ok = QtGui.QFontDialog.getFont(currentFont, self) if ok: self.setData(newFont) else: self.setData(currentFont) self.commitAndClose()
Opens a QColorDialog for the user
359,069
def get_dataset(self, key, info): if self.channel not in key.name: return logger.debug(, key.name) if key.calibration == : variable = self.nc[.format(self.channel, self.stripe, self.view)] else: variable = self.nc[.format(self.channel, self....
Load a dataset.
359,070
def __update_upgrades_table(self, delta): query = .format( self.upgrades_table, delta.get_version(), delta.get_name(), delta.get_type(), delta.get_file(), delta.get_checksum(), self.__get_dbuser()) self.cursor.execute(query) self.connection.commit()
Add a new record into the upgrades information table about the applied delta Parameters ---------- delta: Delta the applied delta file
359,071
def get_querystring_for_page( request, page_number, querystring_key, default_number=1): querydict = request.GET.copy() querydict[querystring_key] = page_number if page_number == default_number: del querydict[querystring_key] if in querydict: del querydict[] if quer...
Return a querystring pointing to *page_number*.
359,072
def hash_bytes(buf): sha256 = hashlib.sha256() sha256.update(buf) return + sha256.hexdigest()
Hash bytes using the same method the registry uses (currently SHA-256). :param buf: Bytes to hash :type buf: binary str :rtype: str :returns: Hex-encoded hash of file's content (prefixed by ``sha256:``)
359,073
def get_kbs(custom_kbs_files=None, cache={}): cache_key = make_cache_key(custom_kbs_files) if cache_key not in cache: kbs_files = CFG_REFEXTRACT_KBS.copy() if custom_kbs_files: for key, path in custom_kbs_files.items(): if path: kb...
Load kbs (with caching). This function stores the loaded kbs into the cache variable For the caching to work, it needs to receive an empty dictionary as "cache" paramater.
359,074
def usgs_eros(self, scene, path): if self.usgs_user and self.usgs_pass: try: api_key = api.login(self.usgs_user, self.usgs_pass) except USGSError as e: error_tree = ElementTree.fromstring(str(e.message)) error_text = erro...
Downloads the image from USGS
359,075
def mark_day(self, day, month=None, year=None): self._remark_date(day, month, year, highlight=True)
Marks the specified month day with a visual marker (typically by making the number bold). If only day is specified and the calendar month and year are changed, the marked day remain marked. You can be more specific setting month and year parameters.
359,076
def play(state): filename = None if state == SoundService.State.welcome: filename = "pad_glow_welcome1.wav" elif state == SoundService.State.goodbye: filename = "pad_glow_power_off.wav" elif state == SoundService.State.hotword_detected: filena...
Play sound for a given state. :param state: a State value.
359,077
def __load_omitted_predictions(self): if self.predictions is None: raise Exception("ErrVar.__load_omitted_predictions(): " + "no predictions is None") if self.omitted_predictions_arg is None and \ self.omitted_par_arg is ...
private: set the omitted_predictions attribute
359,078
def enable(self, ids): data = dict() data["ids"] = ids uri = "api/pools/enable/" return self.post(uri, data)
Enable Pool Members Running Script :param ids: List of ids :return: None on success :raise PoolMemberDoesNotExistException :raise InvalidIdPoolMemberException :raise ScriptEnablePoolException :raise NetworkAPIException
359,079
def _setup_transport(self): if in self.error_whitelist: log.info(, self._transport_type, self.pub_id) if in self.error_whitelist: log.info(, self._transport_type, self.pub_id) transport_class = get_transport(self._transport_type) log.debug(, ...
Setup the transport.
359,080
def from_sec(class_, sec): public_pair = sec_to_public_pair(sec, class_._generator) return class_(public_pair=public_pair, is_compressed=is_sec_compressed(sec))
Create a key from an sec bytestream (which is an encoding of a public pair).
359,081
def clean(feed: "Feed") -> "Feed": feed = feed.copy() ops = [ "clean_ids", "clean_times", "clean_route_short_names", "drop_zombies", ] for op in ops: feed = globals()[op](feed) return feed
Apply #. :func:`drop_zombies` #. :func:`clean_ids` #. :func:`clean_times` #. :func:`clean_route_short_names` to the given "Feed" in that order. Return the resulting "Feed".
359,082
def is_variable(value): if isinstance(value, string_types): return (value.startswith() or value.startswith()) elif isinstance(value, tuple): value = .join(value) return (value.startswith() or value.startswith()) return False
Check if string is LESS variable args: value (str): string returns: bool
359,083
def mfccInitFilterBanks(fs, nfft): lowfreq = 133.33 linsc = 200/3. logsc = 1.0711703 numLinFiltTotal = 13 numLogFilt = 27 if fs < 8000: nlogfil = 5 nFiltTotal = numLinFiltTotal + numLogFilt freqs = numpy.zeros(nFiltTotal+2) freqs[:numLinFiltTotal] = lo...
Computes the triangular filterbank for MFCC computation (used in the stFeatureExtraction function before the stMFCC function call) This function is taken from the scikits.talkbox library (MIT Licence): https://pypi.python.org/pypi/scikits.talkbox
359,084
def dump(values): root = {} def _dump(_values, container): for name,value in _values._values.items(): if isinstance(value, ValueTree): container[name] = _dump(value, {}) elif isinstance(value, list): items = [] for item in valu...
Dump a ValueTree instance, returning its dict representation. :param values: :type values: ValueTree :return: :rtype: dict
359,085
def pretty_version_text(): version_lines = ["dtool, version {}".format(dtool_version)] version_lines.append("\nBase:") version_lines.append("dtoolcore, version {}".format(dtoolcore.__version__)) version_lines.append("dtool-cli, version {}".format(__version__)) version_lines.append("\nStor...
Return pretty version text listing all plugins.
359,086
def _json_safe_float(number): if number is None: return None if isinstance(number, float): return None if np.isinf(number) or np.isnan(number) else number return float(number)
JSON serialization for infinity can be problematic. See https://docs.python.org/2/library/json.html#basic-usage This function returns None if `number` is infinity or negative infinity. If the `number` cannot be converted to float, this will raise an exception.
359,087
def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None, allow_redirects=False): raise TwilioException()
Make an HTTP request.
359,088
def add_multizone(self, group_cast): self._groups[str(group_cast.uuid)] = { : group_cast, : Listener(group_cast, self._casts), : set()}
Start managing a group
359,089
def get_day_end(config): day_start_datetime = datetime.datetime.combine(datetime.date.today(), config[]) day_end_datetime = day_start_datetime - datetime.timedelta(seconds=1) return day_end_datetime.time()
Get the day end time given the day start. This assumes full 24h day. Args: config (dict): Configdict. Needed to extract ``day_start``. Note: This is merely a convinience funtion so we do not have to deduct this from ``day_start`` by hand all the time.
359,090
def blobs(self): return BlobsDataFrame(self._engine_dataframe.getBlobs(), self._session, self._implicits)
Returns this DataFrame joined with the blobs DataSource. >>> blobs_df = refs_df.blobs :rtype: BlobsDataFrame
359,091
def get_session_key(self, username, password_hash): params = {"username": username, "authToken": md5(username + password_hash)} request = _Request(self.network, "auth.getMobileSession", params) request.sign_it() doc = request.execute() return _extra...
Retrieve a session key with a username and a md5 hash of the user's password.
359,092
def Update(self, env, args=None): values = {} for option in self.options: if not option.default is None: values[option.key] = option.default for filename in self.files: if os.path.exists(filename): dir = os.pat...
Update an environment with the option variables. env - the environment to update.
359,093
def replace(self, child, replacement): for i in range(len(self.chunks)): if self.chunks[i] == child: self.chunks[i] = replacement
Replace a child chunk with something else.
359,094
def _init(): if (hasattr(_local_context, ) and _local_context._initialized == os.environ.get()): return _local_context.registry = [] _local_context._executing_async_context = None _local_context._executing_async = [] _local_context._initialized = ...
Initialize the furious context and registry. NOTE: Do not directly run this method.
359,095
def make_set_name(idx): GROUPSIZE = 1000 set_idx = idx // GROUPSIZE if set_idx >= 0: return pypetconstants.FORMATTED_SET_NAME % set_idx else: return pypetconstants.SET_NAME_DUMMY
Creates a run set name based on ``idx``
359,096
def _detach_childs(self, idx_from=None, idx_to=None): idx_from = idx_from or 0 idx_to = idx_to or len(self.childs) removed = self.childs[idx_from:idx_to] for child in removed: if issubclass(child.__class__, DOMElement): child.parent = None sel...
Moves all the childs to a new father
359,097
def report( vulnerabilities, fileobj, print_sanitised, ): n_vulnerabilities = len(vulnerabilities) unsanitised_vulnerabilities = [v for v in vulnerabilities if not isinstance(v, SanitisedVulnerability)] n_unsanitised = len(unsanitised_vulnerabilities) n_sanitised = n_vulnerabilities - n...
Prints issues in color-coded text format. Args: vulnerabilities: list of vulnerabilities to report fileobj: The output file object, which may be sys.stdout
359,098
def mixedcase(path): words = path.split() return words[0] + .join(word.title() for word in words[1:])
Removes underscores and capitalizes the neighbouring character
359,099
def stop_filter(self, post_processing): from matplotlib._image import fromarray width, height = int(self.width), int(self.height) buffer, bounds = self._renderer.tostring_rgba_minimized() l, b, w, h = bounds self._renderer = self._filter...
Save the plot in the current canvas as a image and apply the *post_processing* function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy ar...