Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
372,900 | def _unknown_args(self, args):
for u in args:
self.tcex.log.warning(u.format(u)) | Log argparser unknown arguments.
Args:
args (list): List of unknown arguments |
372,901 | def lookup_camera_by_id(self, device_id):
camera = list(filter(
lambda cam: cam.device_id == device_id, self.cameras))[0]
if camera:
return camera
return None | Return camera object by device_id. |
372,902 | def _check_pillar_minions(self, expr, delimiter, greedy):
return self._check_cache_minions(expr, delimiter, greedy, ) | Return the minions found by looking via pillar |
372,903 | def wait_for_binary_interface(self, **kwargs):
if self.cluster.version() >= :
self.watch_log_for("Starting listening for CQL clients", **kwargs)
binary_itf = self.network_interfaces[]
if not common.check_socket_listening(binary_itf, timeout=30):
warnings.warn("B... | Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds. |
372,904 | def _fullqualname_method_py3(obj):
if inspect.isclass(obj.__self__):
cls = obj.__self__.__qualname__
else:
cls = obj.__self__.__class__.__qualname__
return obj.__self__.__module__ + + cls + + obj.__name__ | Fully qualified name for 'method' objects in Python 3. |
372,905 | def for_user(self, user):
qs = SharedMemberQuerySet(model=self.model, using=self._db, user=user)
qs = qs.filter(Q(author=user) | Q(foldershareduser__user=user))
return qs.distinct() & self.distinct() | All folders the given user can do something with. |
372,906 | def get_work_item_by_id(self, wi_id):
work_items = self.get_work_items(id=wi_id)
if work_items is not None:
return work_items[0]
return None | Retrieves a single work item based off of the supplied ID
:param wi_id: The work item ID number
:return: Workitem or None |
372,907 | def remove(self, label):
if label.id in self._labels:
self._labels[label.id] = None
self._dirty = True | Remove a label.
Args:
label (gkeepapi.node.Label): The Label object. |
372,908 | def get_range(self, ignore_blank_lines=True):
ref_lvl = self.trigger_level
first_line = self._trigger.blockNumber()
block = self._trigger.next()
last_line = block.blockNumber()
lvl = self.scope_level
if ref_lvl == lvl:
r... | Gets the fold region range (start and end line).
.. note:: Start line do no encompass the trigger line.
:param ignore_blank_lines: True to ignore blank lines at the end of the
scope (the method will rewind to find that last meaningful block
that is part of the fold scope).
... |
372,909 | def add_sender(self, partition=None, operation=None, send_timeout=60, keep_alive=30, auto_reconnect=True):
target = "amqps://{}{}".format(self.address.hostname, self.address.path)
if operation:
target = target + operation
handler = Sender(
self, target, partition... | Add a sender to the client to EventData object to an EventHub.
:param partition: Optionally specify a particular partition to send to.
If omitted, the events will be distributed to available partitions via
round-robin.
:type parition: str
:operation: An optional operation to b... |
372,910 | def event_params(segments, params, band=None, n_fft=None, slopes=None,
prep=None, parent=None):
if parent is not None:
progress = QProgressDialog(, ,
0, len(segments) - 1, parent)
progress.setWindowModality(Qt.ApplicationModal)
param_key... | Compute event parameters.
Parameters
----------
segments : instance of wonambi.trans.select.Segments
list of segments, with time series and metadata
params : dict of bool, or str
'dur', 'minamp', 'maxamp', 'ptp', 'rms', 'power', 'peakf', 'energy',
'peakef'. If 'all', a dict... |
372,911 | def remove_builder(cls, builder_name: str):
cls.builders.pop(builder_name, None)
for hook_spec in cls.hooks.values():
hook_spec.pop(builder_name, None) | Remove a registered builder `builder_name`.
No reason to use this except for tests. |
372,912 | def return_hdr(self):
orig = {}
for xml_file in self.filename.glob():
if xml_file.stem[0] != :
orig[xml_file.stem] = parse_xml(str(xml_file))
signals = sorted(self.filename.glob())
for signal in signals:
block_hdr, i_data = read_all_bloc... | Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
list of all the channels... |
372,913 | def makeDigraph(automaton, inputAsString=repr,
outputAsString=repr,
stateAsString=repr):
digraph = graphviz.Digraph(graph_attr={: ,
: },
node_attr={: },
edge_attr={: })
... | Produce a L{graphviz.Digraph} object from an automaton. |
372,914 | def transpose_note(note, transpose, scale="C"):
val = note_to_val(note)
val += transpose
return val_to_note(val, scale) | Transpose a note
:param str note: note to transpose
:type transpose: int
:param str scale: key scale
:rtype: str
:return: transposed note |
372,915 | def app_routes(app):
_routes = []
for rule in app.url_map.iter_rules():
_routes.append({
: rule.rule,
: rule.endpoint,
: list(rule.methods)
})
return jsonify({: _routes}) | list of route of an app |
372,916 | def forward_ad(node, wrt, preserve_result=False, check_dims=True):
if not isinstance(node, gast.FunctionDef):
raise TypeError
cfg_obj = cfg.CFG.build_cfg(node)
cfg.Active(range(len(node.args.args))).visit(cfg_obj.entry)
fad = ForwardAD(wrt, preserve_result, check_dims)
node = fad.visit(node)
... | Perform forward-mode AD on an AST.
This function analyses the AST to determine which variables are active and
proceeds by taking the naive derivative. Before returning the primal and
adjoint it annotates push and pop statements as such.
Args:
node: A `FunctionDef` AST node.
wrt: A tuple of argument in... |
372,917 | def parse(self, target):
if isinstance(target, ContentNode):
if target.name:
self.parent = target
self.name.parse(self)
self.name += target.name
target.ruleset.append(self)
self.root.cache[][str(self.name).split()[0]].add(s... | Parse nested rulesets
and save it in cache. |
372,918 | def delete_category(category_id):
try:
res = _pybossa_req(, , category_id)
if type(res).__name__ == :
return True
else:
return res
except:
raise | Delete a Category with id = category_id.
:param category_id: PYBOSSA Category ID
:type category_id: integer
:returns: True -- the response status code |
372,919 | def update_virtual_meta(self):
import astropy.units
try:
path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml")
if os.path.exists(path):
meta_info = vaex.utils.read_json_or_yaml(path)
if not in meta_info:
... | Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame. |
372,920 | def install_handler(self, event_type, handler, user_handle=None):
return self.visalib.install_visa_handler(self.session, event_type, handler, user_handle) | Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying ha... |
372,921 | def linewidth(self, linewidth=None):
if linewidth is None:
return self._linewidth
else:
if not is_numeric(linewidth):
raise TypeError(
"linewidth must be number, not " % str(linewidth)
)
self._linewidth = line... | Returns or sets (if a value is provided) the width of the series'
line.
:param Number linewidth: If given, the series' linewidth will be set to\
this.
:rtype: ``Number`` |
372,922 | def declare(self, queue=, virtual_host=, passive=False, durable=False,
auto_delete=False, arguments=None):
if passive:
return self.get(queue, virtual_host=virtual_host)
queue_payload = json.dumps(
{
: durable,
: auto_delet... | Declare a Queue.
:param str queue: Queue name
:param str virtual_host: Virtual host name
:param bool passive: Do not create
:param bool durable: Durable queue
:param bool auto_delete: Automatically delete when not in use
:param dict|None arguments: Queue key/value argume... |
372,923 | def run(self):
old_inplace, self.inplace = self.inplace, 0
_build_ext.run(self)
self.inplace = old_inplace
if old_inplace:
self.copy_extensions_to_source() | Build extensions in build directory, then copy if --inplace |
372,924 | def updateData(self, state_data, action_data, reward_data):
self.state_data[:, self.updates] = state_data
self.action_data[:, self.updates] = action_data
self.reward_data[0, self.updates] = reward_data
self.updates += 1
self._render() | Updates the data used by the renderer. |
372,925 | def file_key_retire( blockchain_id, file_key, config_path=CONFIG_PATH, wallet_keys=None ):
config_dir = os.path.dirname(config_path)
url = file_url_expired_keys( blockchain_id )
proxy = blockstack_client.get_default_proxy( config_path=config_path )
old_key_bundle_res = blockstack_client.d... | Retire the given key. Move it to the head of the old key bundle list
@file_key should be data returned by file_key_lookup
Return {'status': True} on success
Return {'error': ...} on error |
372,926 | def sum_sp_values(self):
if self.values is None:
ret = IdValues()
else:
ret = IdValues({: sum(int(x) for x in self.values.values())})
return ret | return system level values (spa + spb)
input:
"values": {
"spa": 385,
"spb": 505
},
return:
"values": {
"0": 890
}, |
372,927 | def prepare_data(data_dir, fileroot, block_pct_tokens_thresh=0.1):
if not 0.0 <= block_pct_tokens_thresh <= 1.0:
raise ValueError()
html = read_html_file(data_dir, fileroot)
blocks = read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True)
content_blocks = []
comments_blo... | Prepare data for a single HTML + gold standard blocks example, uniquely
identified by ``fileroot``.
Args:
data_dir (str)
fileroot (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
Tuple[str, Tuple[np.array[int], np.array[int], List[str]], Tuple[np.array[... |
372,928 | def req_withdraw(self, address, amount, currency, fee=0, addr_tag="", _async=False):
params = {
: address,
: amount,
: currency,
: fee,
: addr_tag
}
path =
return api_key_post(params, path, _async=_async) | 申请提现虚拟币
:param address:
:param amount:
:param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种)
:param fee:
:param addr_tag:
:return: {
"status": "ok",
"data": 700
} |
372,929 | def Liu(Tb, Tc, Pc):
rs critical temperature, pressure
and boiling point.
The enthalpy of vaporization is given by:
.. math::
\Delta H_{vap} = RT_b \left[ \frac{T_b}{220}\right]^{0.0627} \frac{
(1-T_{br})^{0.38} \ln(P_c/P_A)}{1-T_{br} + 0.38 T_{br} \ln T_{br}}
Parameters
-----... | r'''Calculates enthalpy of vaporization at the normal boiling point using
the Liu [1]_ correlation, and a chemical's critical temperature, pressure
and boiling point.
The enthalpy of vaporization is given by:
.. math::
\Delta H_{vap} = RT_b \left[ \frac{T_b}{220}\right]^{0.0627} \frac{
... |
372,930 | def get_argument_starttime(self):
try:
starttime = self.get_argument(constants.PARAM_STARTTIME)
return starttime
except tornado.web.MissingArgumentError as e:
raise Exception(e.log_message) | Helper function to get starttime argument.
Raises exception if argument is missing.
Returns the starttime argument. |
372,931 | def _parse_q2r(self, f):
natom, dim, epsilon, borns = self._parse_parameters(f)
fc_dct = {: self._parse_fc(f, natom, dim),
: dim,
: epsilon,
: borns}
return fc_dct | Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613... |
372,932 | def remove_namespace(self, ns_uri):
if not self.contains_namespace(ns_uri):
return
ni = self.__ns_uri_map.pop(ns_uri)
for prefix in ni.prefixes:
del self.__prefix_map[prefix] | Removes the indicated namespace from this set. |
372,933 | def add_arguments(parser, default_level=logging.INFO):
adder = (
getattr(parser, , None)
or getattr(parser, )
)
adder(
, , default=default_level, type=log_level,
help="Set log level (DEBUG, INFO, WARNING, ERROR)") | Add arguments to an ArgumentParser or OptionParser for purposes of
grabbing a logging level. |
372,934 | def _parse_arguments():
parser = argparse.ArgumentParser(description="CMake AST Dumper")
parser.add_argument("filename", nargs=1, metavar=("FILE"),
help="read FILE")
return parser.parse_args() | Return a parser context result. |
372,935 | def score_x_of_a_kind_yatzy(dice: List[int], min_same_faces: int) -> int:
for die, count in Counter(dice).most_common(1):
if count >= min_same_faces:
return die * min_same_faces
return 0 | Similar to yahtzee, but only return the sum of the dice that satisfy min_same_faces |
372,936 | def do_mkdir(self, line):
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
if not mkdir(filename):
print_err( % filename) | mkdir DIRECTORY...
Creates one or more directories. |
372,937 | def handle_http_error(self, response, custom_messages=None,
raise_for_status=False):
if not custom_messages:
custom_messages = {}
if response.status_code in custom_messages.keys():
raise errors.HTTPError(custom_messages[response.status_code])
... | Converts service errors to Python exceptions
Parameters
----------
response : requests.Response
A service response.
custom_messages : dict, optional
A mapping of custom exception messages to HTTP status codes.
raise_for_status : bool, optional
... |
372,938 | def from_point(cls, point, network=BitcoinMainNet, **kwargs):
verifying_key = VerifyingKey.from_public_point(point, curve=SECP256k1)
return cls.from_verifying_key(verifying_key, network=network, **kwargs) | Create a PublicKey from a point on the SECP256k1 curve.
:param point: A point on the SECP256k1 curve.
:type point: SECP256k1.point |
372,939 | def _split_index(self, key):
if not isinstance(key, tuple):
key = (key,)
elif key == ():
return (), ()
if key[0] is Ellipsis:
num_pad = self.ndims - len(key) + 1
key = (slice(None),) * num_pad + key[1:]
elif len(key) < self.ndims:... | Partitions key into key and deep dimension groups. If only key
indices are supplied, the data is indexed with an empty tuple.
Keys with indices than there are dimensions will be padded. |
372,940 | def is_bday(date, bday=None):
_date = Timestamp(date)
if bday is None:
bday = CustomBusinessDay(calendar=USFederalHolidayCalendar())
return _date == (_date + bday) - bday | Return true iff the given date is a business day.
Parameters
----------
date : :class:`pandas.Timestamp`
Any value that can be converted to a pandas Timestamp--e.g.,
'2012-05-01', dt.datetime(2012, 5, 1, 3)
bday : :class:`pandas.tseries.offsets.CustomBusinessDay`
Defaults to `C... |
372,941 | def delete(self, *args, **kwargs):
api = Api()
api.authenticate()
api.delete_video(self.video_id)
return super(Video, self).delete(*args, **kwargs) | Deletes the video from youtube
Raises:
OperationError |
372,942 | def mount(nbd, root=None):
*
__salt__[](
.format(nbd),
python_shell=False,
)
ret = {}
if root is None:
root = os.path.join(
tempfile.gettempdir(),
,
os.path.basename(nbd)
)
for part in glob.glob(.format(nbd)):
... | Pass in the nbd connection device location, mount all partitions and return
a dict of mount points
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.mount /dev/nbd0 |
372,943 | def where(self, inplace=False, **kwargs):
masks = {k: np.ones(v, dtype=) for k,v in self.dimensions.items()}
def index_to_mask(index, n):
val = np.zeros(n, dtype=)
val[index] = True
return val
def masks_and(dict1, dict2):
... | Return indices over every dimension that met the conditions.
Condition syntax:
*attribute* = value
Return indices that satisfy the condition where the attribute is equal
to the value
e.g. type_array = 'H'
*attribute* = list(va... |
372,944 | def parse(cls, expression):
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
... | Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict |
372,945 | def generate(self, id_or_uri):
uri = self._client.build_uri(id_or_uri) + "/generate"
return self._client.get(uri) | Generates and returns a random range.
Args:
id_or_uri:
ID or URI of range.
Returns:
dict: A dict containing a list with IDs. |
372,946 | def parser(key = "default"):
if key not in _parsers:
if key == "ssh":
_parsers["ssh"] = CodeParser(True, False)
else:
key = "default"
return _parsers[key] | Returns the parser for the given key, (e.g. 'ssh') |
372,947 | def _reads_per_position(bam_in, loci_file, out_dir):
data = Counter()
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(loci_file)
c = a.intersect(b, s=True, bed=True, wo=True)
for line in c:
end = int(line[1]) + 1 + int(line[2]) if line[5] == "+" else int(line[1]) + 1
start... | Create input for compute entropy |
372,948 | def _parse_sentencetree(self, tree, parent_node_id=None, ignore_traces=True):
def get_nodelabel(node):
if isinstance(node, nltk.tree.Tree):
return node.label()
elif isinstance(node, unicode):
return node.encode()
else:
... | parse a sentence Tree into this document graph |
372,949 | def add_annotation(
self,
subj: URIRef,
pred: URIRef,
obj: Union[Literal, URIRef],
a_p: URIRef ,
a_o: Union[Literal, URIRef],
) -> BNode:
bnode: BNode = self.triple2annotation_bnode.get( (subj, pred, obj) )
if not b... | Adds annotation to rdflib graph.
The annotation axiom will filled in if this is a new annotation for the triple.
Args:
subj: Entity subject to be annotated
pref: Entities Predicate Anchor to be annotated
obj: Entities Object Anchor to be annotated
a_p: A... |
372,950 | def current_changed(self, index):
editor = self.get_current_editor()
if editor.lsp_ready and not editor.document_opened:
editor.document_did_open()
if index != -1:
editor.setFocus()
logger.debug("Set focus to: %s" % editor.filename)
... | Stack index has changed |
372,951 | def calibrate_signal(signal, resp, fs, frange):
dc = np.mean(resp)
resp = resp - dc
npts = len(signal)
f0 = np.ceil(frange[0] / (float(fs) / npts))
f1 = np.floor(frange[1] / (float(fs) / npts))
y = resp
Y = np.fft.rfft(y)
x = signal
X = np.fft.rfft(x)
H = ... | Given original signal and recording, spits out a calibrated signal |
372,952 | def set_latency(self, latency):
self._client[][] = latency
yield from self._server.client_latency(self.identifier, latency) | Set client latency. |
372,953 | def backup(file_name, jail=None, chroot=None, root=None):
***
ret = __salt__[](
_pkg(jail, chroot, root) + [, , file_name],
output_loglevel=,
python_shell=False
)
return ret.split()[1] | Export installed packages into yaml+mtree file
CLI Example:
.. code-block:: bash
salt '*' pkg.backup /tmp/pkg
jail
Backup packages from the specified jail. Note that this will run the
command within the jail, and so the path to the backup file will be
relative to the root... |
372,954 | def has_role(item):
def predicate(ctx):
if not isinstance(ctx.channel, discord.abc.GuildChannel):
raise NoPrivateMessage()
if isinstance(item, int):
role = discord.utils.get(ctx.author.roles, id=item)
else:
role = discord.utils.get(ctx.author.roles,... | A :func:`.check` that is added that checks if the member invoking the
command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including
caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the ro... |
372,955 | def certify_date(value, required=True):
if certify_required(
value=value,
required=required,
):
return
if not isinstance(value, date):
raise CertifierTypeError(
message="expected timestamp (date∂), but value is of type {cls!r}".format(
cls=va... | Certifier for datetime.date values.
:param value:
The value to be certified.
:param bool required:
Whether the value can be `None` Defaults to True.
:raises CertifierTypeError:
The type is invalid |
372,956 | def _header_string(basis_dict):
tw = textwrap.TextWrapper(initial_indent=, subsequent_indent= * 20)
header = * 70 +
header +=
header += + version() +
header += + _main_url +
header += * 70 +
header += + basis_dict[] +
header += tw.fill( + basis_dict[]) +
header += ... | Creates a header with information about a basis set
Information includes description, revision, etc, but not references |
372,957 | def dumps(self, obj, salt=None):
payload = want_bytes(self.dump_payload(obj))
rv = self.make_signer(salt).sign(payload)
if self.is_text_serializer:
rv = rv.decode()
return rv | Returns a signed string serialized with the internal serializer.
The return value can be either a byte or unicode string depending
on the format of the internal serializer. |
372,958 | def prepare_request_body(self,
private_key=None,
subject=None,
issuer=None,
audience=None,
expires_at=None,
issued_at=None,
... | Create and add a JWT assertion to the request body.
:param private_key: Private key used for signing and encrypting.
Must be given as a string.
:param subject: (sub) The principal that is the subject of the JWT,
i.e. which user is the token requeste... |
372,959 | def _cache_key_select_daterange(method, self, field_id, field_title, style=None):
key = update_timer(), field_id, field_title, style
return key | This function returns the key used to decide if method select_daterange has to be recomputed |
372,960 | def get_plugin_conf(self, phase, name):
match = [x for x in self.template[phase] if x.get() == name]
return match[0] | Return the configuration for a plugin.
Raises KeyError if there are no plugins of that type.
Raises IndexError if the named plugin is not listed. |
372,961 | def filter_exclude_downhole(self, threshold, filt=True):
f = self.filt.grab_filt(filt)
if self.n == 1:
nfilt = filters.exclude_downhole(f, threshold)
else:
nfilt = []
for i in range(self.n):
nf = self.ns == i + 1
nfil... | Exclude all points down-hole (after) the first excluded data.
Parameters
----------
threhold : int
The minimum number of contiguous excluded data points
that must exist before downhole exclusion occurs.
file : valid filter string or bool
Which filter ... |
372,962 | def populate_observable(self, time, kind, dataset, **kwargs):
if kind in [, ]:
return
if time==self.time and dataset in self.populated_at_time and not in kind:
self.populated_at_time.append(dataset) | TODO: add documentation |
372,963 | def _find_valid_index(self, how):
assert how in [, ]
if len(self) == 0:
return None
is_valid = ~self.isna()
if self.ndim == 2:
is_valid = is_valid.any(1)
if how == :
idxpos = is_valid.values[::].argmax()
if how == :
... | Retrieves the index of the first valid value.
Parameters
----------
how : {'first', 'last'}
Use this parameter to change between the first or last valid index.
Returns
-------
idx_first_valid : type of index |
372,964 | def load_neurons(neurons,
neuron_loader=load_neuron,
name=None,
population_class=Population,
ignored_exceptions=()):
Population
if isinstance(neurons, (list, tuple)):
files = neurons
name = name if name is not None else
eli... | Create a population object from all morphologies in a directory\
of from morphologies in a list of file names
Parameters:
neurons: directory path or list of neuron file paths
neuron_loader: function taking a filename and returning a neuron
population_class: class representing popula... |
372,965 | def potential_cloud_pixels(self):
eq1 = self.basic_test()
eq2 = self.whiteness_test()
eq3 = self.hot_test()
eq4 = self.nirswir_test()
if self.sat == :
cir = self.cirrus_test()
return (eq1 & eq2 & eq3 & eq4) | cir
else:
return e... | Determine potential cloud pixels (PCPs)
Combine basic spectral testsr to get a premliminary cloud mask
First pass, section 3.1.1 in Zhu and Woodcock 2012
Equation 6 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
blue: ndarray
... |
372,966 | def parse_fn(fn):
try:
parts = os.path.splitext(os.path.split(fn)[-1])[0].replace(, )\
.split()[:2]
coords = [float(crds)
for crds in re.split(, parts[0] + parts[1])[1:]]
except:
coords = [np.nan] * 4
return coords | This parses the file name and returns the coordinates of the tile
Parameters
-----------
fn : str
Filename of a GEOTIFF
Returns
--------
coords = [LLC.lat, LLC.lon, URC.lat, URC.lon] |
372,967 | def select_valid_methods_P(self, T, P):
r
if self.forced_P:
considered_methods = list(self.user_methods_P)
else:
considered_methods = list(self.all_methods_P)
if self.user_methods_P:
[considered_methods.remove(i) for i in self.user_methods_P]... | r'''Method to obtain a sorted list methods which are valid at `T`
according to `test_method_validity`. Considers either only user methods
if forced is True, or all methods. User methods are first tested
according to their listed order, and unless forced is True, then all
methods are test... |
372,968 | def ResetConsoleColor() -> bool:
if sys.stdout:
sys.stdout.flush()
bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor)) | Reset to the default text color on console window.
Return bool, True if succeed otherwise False. |
372,969 | def random(key: str, index: Index, index_map: IndexMap=None) -> pd.Series:
if len(index) > 0:
random_state = np.random.RandomState(seed=get_hash(key))
sample_size = index_map.map_size if index_map is not None else index.ma... | Produces an indexed `pandas.Series` of uniformly distributed random numbers.
The index passed in typically corresponds to a subset of rows in a
`pandas.DataFrame` for which a probabilistic draw needs to be made.
Parameters
----------
key :
A string used to create a seed for the random numb... |
372,970 | def instance(self, counter=None, pipeline_counter=None):
pipeline_counter = pipeline_counter or self.pipeline_counter
pipeline_instance = None
if not pipeline_counter:
pipeline_instance = self.server.pipeline(self.pipeline_name).instance()
self.pipeline_counter ... | Returns all the information regarding a specific stage run
See the `Go stage instance documentation`__ for examples.
.. __: http://api.go.cd/current/#get-stage-instance
Args:
counter (int): The stage instance to fetch.
If falsey returns the latest stage instance from :me... |
372,971 | def raw_search(self, *args, **kwargs):
limit = 50
try:
limit = kwargs[]
except KeyError:
pass
self._mail.select("inbox")
try:
date = kwargs[]
date_str = date.strftime("%d-%b-%Y")
_, email_ids... | Find the a set of emails matching each regular expression passed in against the (RFC822) content.
Args:
*args: list of regular expressions.
Kwargs:
limit (int) - Limit to how many of the most resent emails to search through.
date (datetime) - If specified, it will f... |
372,972 | def scheme_chunker(text, getreffs):
level = len(text.citation)
types = [citation.name for citation in text.citation]
if types == ["book", "poem", "line"]:
level = 2
elif types == ["book", "line"]:
return line_chunker(text, getreffs)
return [tuple([reff.split(":")[-1]]*2) for ref... | This is the scheme chunker which will resolve the reference giving a callback (getreffs) and a text object with its metadata
:param text: Text Object representing either an edition or a translation
:type text: MyCapytains.resources.inventory.Text
:param getreffs: callback function which retrieves a list of... |
372,973 | def xml_replace(filename, **replacements):
keywords = set(replacements.keys())
templatename = f
targetname = f
print(f)
print(f)
print()
with open(templatename) as templatefile:
templatebody = templatefile.read()
parts = templatebody.replace(, ).split()
defaults = {}
... | Read the content of an XML template file (XMLT), apply the given
`replacements` to its substitution markers, and write the result into
an XML file with the same name but ending with `xml` instead of `xmlt`.
First, we write an XMLT file, containing a regular HTML comment, a
readily defined element `e1`... |
372,974 | def _check_repo_sign_utils_support(name):
if salt.utils.path.which(name):
return True
else:
raise CommandExecutionError(
{0}\.format(name)
) | Check for specified command name in search path |
372,975 | def geturl(environ, query=True, path=True, use_server_name=False):
url = [environ[] + ]
if use_server_name:
url.append(environ[])
if environ[] == :
if environ[] != :
url.append( + environ[])
else:
if environ[] != :
url.append( ... | Rebuilds a request URL (from PEP 333).
You may want to chose to use the environment variables
server_name and server_port instead of http_host in some case.
The parameter use_server_name allows you to chose.
:param query: Is QUERY_STRING included in URI (default: True)
:param path: Is path included... |
372,976 | def _load(self):
try:
get = requests.get(self._ref,
verify=self.http_verify,
auth=self.auth,
timeout=self.timeout)
except requests.exceptions.RequestException as err:
raise NotFo... | Function load.
:return: Response content
:raises: NotFoundError |
372,977 | def store_magic_envelope_doc(self, payload):
try:
json_payload = json.loads(decode_if_bytes(payload))
except ValueError:
xml = unquote(decode_if_bytes(payload))
xml = xml.lstrip().encode("utf-8")
logger.debug("diaspora.protocol.store_... | Get the Magic Envelope, trying JSON first. |
372,978 | def all_subclasses(cls):
for subcls in cls.__subclasses__():
yield subcls
for subsubcls in all_subclasses(subcls):
yield subsubcls | Generator yielding all subclasses of `cls` recursively |
372,979 | def get_interfaces(self):
result = {}
interfaces = junos_views.junos_iface_table(self.device)
interfaces.get()
interfaces_logical = junos_views.junos_logical_iface_table(self.device)
interfaces_logical.get()
def _convert_to_dict(interfaces):
... | Return interfaces details. |
372,980 | def _prm_store_from_dict(self, fullname, store_dict, hdf5_group, store_flags, kwargs):
for key, data_to_store in store_dict.items():
original_hdf5_group = None
flag = store_flags[key]
if in key:
original_hdf5_group = hdf5_group
... | Stores a `store_dict` |
372,981 | def cart_to_polar(arr_c):
if arr_c.shape[-1] == 1:
arr_p = arr_c.copy()
elif arr_c.shape[-1] == 2:
arr_p = np.empty_like(arr_c)
arr_p[..., 0] = vector_mag(arr_c)
arr_p[..., 1] = np.arctan2(arr_c[..., 1], arr_c[..., 0])
elif arr_c.shape[-1] == 3:
arr_p = np.empty_... | Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radius, inclination, azimuth) conventi... |
372,982 | def add_property(self, name, value):
with self.__properties_lock:
if name in self.__properties:
return False
self.__properties[name] = value
return True | Adds a property to the framework **if it is not yet set**.
If the property already exists (same name), then nothing is done.
Properties can't be updated.
:param name: The property name
:param value: The value to set
:return: True if the property was stored, else False |
372,983 | def delete_connection(self, name, reason=None):
headers = {: reason} if reason else {}
self._api_delete(
.format(
urllib.parse.quote_plus(name)
),
headers=headers,
) | Closes an individual connection. Give an optional reason
:param name: The connection name
:type name: str
:param reason: An option reason why the connection was deleted
:type reason: str |
372,984 | def _update_mean_in_window(self):
self._mean_x_in_window = numpy.mean(self._x_in_window)
self._mean_y_in_window = numpy.mean(self._y_in_window) | Compute mean in window the slow way. useful for first step.
Considers all values in window
See Also
--------
_add_observation_to_means : fast update of mean for single observation addition
_remove_observation_from_means : fast update of mean for single observation removal |
372,985 | def delete(self, *args):
cache = get_cache()
key = self.get_cache_key(*args)
if key in cache:
del cache[key] | Remove the key from the request cache and from memcache. |
372,986 | def R_op(self, inputs, eval_points):
try:
dom_weight = self.operator.domain.weighting.const
except AttributeError:
dom_weight = 1.0
try:
ran_weight = self.operator.range.weighting.const
except AttributeError:
ran_weight =... | Apply the adjoint of the Jacobian at ``inputs`` to ``eval_points``.
This is the symbolic counterpart of ODL's ::
op.derivative(x).adjoint(v)
See `grad` for its usage.
Parameters
----------
inputs : 1-element list of `theano.tensor.var.TensorVariable`
S... |
372,987 | def convert_surrogate_pair(match):
pair = match.group(0)
codept = 0x10000 + (ord(pair[0]) - 0xd800) * 0x400 + (ord(pair[1]) - 0xdc00)
return chr(codept) | Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates |
372,988 | def parse(args):
from tzlocal import get_localzone
try:
timezone = get_localzone()
if isinstance(timezone, pytz.BaseTzInfo):
timezone = timezone.zone
except Exception:
timezone =
if timezone == :
timezone =
parser = argparse.ArgumentParser(descri... | Define the available arguments |
372,989 | def uintersect1d(arr1, arr2, assume_unique=False):
v = np.intersect1d(arr1, arr2, assume_unique=assume_unique)
v = _validate_numpy_wrapper_units(v, [arr1, arr2])
return v | Find the sorted unique elements of the two input arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>>... |
372,990 | def is_blackout(self) -> bool:
if not current_app.config[]:
if self.severity in current_app.config[]:
return False
return db.is_blackout_period(self) | Does this alert match a blackout period? |
372,991 | def file_ops(staticfied, args):
destination = args.o or args.output
if destination:
with open(destination, ) as file:
file.write(staticfied)
else:
print(staticfied) | Write to stdout or a file |
372,992 | def to_dict(self):
checks = {
key: HealthResult.evaluate(func, self.graph)
for key, func in self.checks.items()
}
dct = dict(
name=self.name,
ok=all(checks.values()),
)
if checks:
dct["chec... | Encode the name, the status of all checks, and the current overall status. |
372,993 | def __restrictIndex(self, i):
if self.numRecords:
rmax = self.numRecords - 1
if abs(i) > rmax:
raise IndexError("Shape or Record index out of range.")
if i < 0: i = range(self.numRecords)[i]
return i | Provides list-like handling of a record index with a clearer
error message if the index is out of bounds. |
372,994 | def _removecleaner(self, cleaner):
oldlen = len(self._old_cleaners)
self._old_cleaners = [
oldc for oldc in self._old_cleaners
if not oldc.issame(cleaner)
]
return len(self._old_cleaners) != oldlen | Remove the cleaner from the list if it already exists. Returns True if
the cleaner was removed. |
372,995 | def insert_from_segwizard(self, fileobj, instruments, name, version = None, comment = None):
self.add(LigolwSegmentList(active = segmentsUtils.fromsegwizard(fileobj, coltype = LIGOTimeGPS), instruments = instruments, name = name, version = version, comment = comment)) | Parse the contents of the file object fileobj as a
segwizard-format segment list, and insert the result as a
new list of "active" segments into this LigolwSegments
object. A new entry will be created in the segment_definer
table for the segment list, and instruments, name and
comment are used to populate the... |
372,996 | def share(self, base=None, keys=None, by=None, **kwargs):
if by is not None:
if base is not None:
if hasattr(base, ) or isinstance(base, Plotter):
base = [base]
if by.lower() in [, ]:
bases = {ax: p[0] for ax, p in six.... | Share the formatoptions of one plotter with all the others
This method shares specified formatoptions from `base` with all the
plotters in this instance.
Parameters
----------
base: None, Plotter, xarray.DataArray, InteractiveList, or list of them
The source of the ... |
372,997 | def childgroup(self, field):
grid = getattr(self, "grid", None)
named_grid = getattr(self, "named_grid", None)
if grid is not None:
childgroup = self._childgroup(field.children, grid)
elif named_grid is not None:
childgroup = self._childgroup_by_name(fie... | Return a list of fields stored by row regarding the configured grid
:param field: The original field this widget is attached to |
372,998 | def md_to_pdf(input_name, output_name):
if output_name[-4:] == :
os.system("pandoc " + input_name + " -o " + output_name)
else:
os.system("pandoc " + input_name + " -o " + output_name + ".pdf" ) | Converts an input MarkDown file to a PDF of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of the output file to where this function is being called. N... |
372,999 | def search_seqs(self, seqrec, in_seq, locus, run=0, partial_ann=None):
start = seq_search[1] if feat_name != else 0
si = seq_search[1]+1 if seq_search[1] != 0 and \
... | search_seqs - method for annotating a BioPython sequence without alignment
:param seqrec: The reference sequence
:type seqrec: SeqRecord
:param locus: The gene locus associated with the sequence.
:type locus: str
:param in_seq: The input sequence
:type in_seq: SeqRecord
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.