Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
353,500 | def get_or_create(cls, **kwargs):
q = cls._get_instance(**kwargs)
if q:
return q
q = cls(**kwargs)
_action_and_commit(q, session.add)
return q | If a record matching the instance already exists in the database, then
return it, otherwise create a new record. |
353,501 | def add_rule(self, rule):
parsed_rule = None
if rule.count() == 1 and rule.count() == 0:
parsed_rule = tuple(.join(part.split()) for part in rule.split()) + (0,)
elif rule.count() == 0 and rule.count() == 1:
parsed_rule = tuple(.join(part.split()) for part in ru... | Supported rules: `a -> b` and `a => b` (terminal rule). |
353,502 | async def check(self, *args):
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(result, dict):
data.update(result)
if not data:
return True
... | All filters must return a positive result
:param args:
:return: |
353,503 | def __remove_pyc_pyo(fname):
if osp.splitext(fname)[1] == :
for ending in (, ):
if osp.exists(fname+ending):
os.remove(fname+ending) | Eventually remove .pyc and .pyo files associated to a Python script |
353,504 | def get_num_names(include_expired=False, proxy=None, hostport=None):
assert proxy or hostport,
if proxy is None:
proxy = connect_hostport(hostport)
schema = {
: ,
: {
: {
: ,
: 0,
},
},
: [
,
... | Get the number of names, optionally counting the expired ones
Return {'error': ...} on failure |
353,505 | def recall_score(gold, pred, pos_label=1, ignore_in_gold=[], ignore_in_pred=[]):
gold, pred = _preprocess(gold, pred, ignore_in_gold, ignore_in_pred)
positives = np.where(pred == pos_label, 1, 0).astype(bool)
trues = np.where(gold == pos_label, 1, 0).astype(bool)
TP = np.sum(positives * trues)
... | Calculate recall for a single class.
Args:
gold: A 1d array-like of gold labels
pred: A 1d array-like of predicted labels (assuming abstain = 0)
ignore_in_gold: A list of labels for which elements having that gold
label will be ignored.
ignore_in_pred: A list of labels fo... |
353,506 | def on_abort(self, func):
if self._done.is_set():
if self._failure is not None:
backend.schedule(func, args=self._failure)
else:
self._errbacks.append(func) | Assign a callback function to be run when :meth:`abort`\ed
:param function func:
A callback to run when aborted. It will be given three arguments:
- ``klass``: the exception class
- ``exc``: the exception instance
- ``tb``: the traceback object assoc... |
353,507 | def module_add(self, ev, path=None):
log = self._params.get(, self._discard)
key = ev.get_key()
if key is None:
raise TaskError(name, "Attempt to register python module event with no key available")
log.debug("Adding path %r for task %r, action %s", path, ev.get_name... | Register for python module change events. If there is a module change, the
task will be notified with a call t.event(action). |
353,508 | def image_files_list(self, limit=-1, offset=-1):
return self.images.list_objects(limit=limit, offset=offset) | Retrieve list of all images in the data store.
Parameters
----------
limit : int
Limit number of results in returned object listing
offset : int
Set offset in list (order as defined by object store)
Returns
-------
ObjectListing
... |
353,509 | def vars_(self):
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var] | Returns symbol instances corresponding to variables
of the current scope. |
353,510 | def build(self, **kw):
global MkdirBuilder
if self.builder is not MkdirBuilder:
SCons.Node.Node.build(self, **kw) | A null "builder" for directories. |
353,511 | def _unsigned_add_overflow(state, a, b):
add = Operators.ZEXTEND(a, 512) + Operators.ZEXTEND(b, 512)
cond = Operators.UGE(add, 1 << 256)
return cond | Sign extend the value to 512 bits and check the result can be represented
in 256. Following there is a 32 bit excerpt of this condition:
a + b ffffffff bfffffff 80000001 00000000 00000001 3ffffffff 7fffffff
ffffffff True True True False True True True
bff... |
353,512 | def get_data_and_column_widths(self, data_kwargs, width_kwargs):
data_kwargs = data_kwargs.copy()
safe_str = data_kwargs.pop(, self._safe_str)
list_of_list = [[safe_str(col, _is_header=True, **data_kwargs)
for col in self.columns]]
list_of_list+= [[safe_... | :param data_kwargs: kwargs used for converting data to strings
:param width_kwargs: kwargs used for determining column widths
:return: tuple(list of list of strings, list of int) |
353,513 | def compile_graphql_to_sql(schema, graphql_string, compiler_metadata, type_equivalence_hints=None):
lowering_func = ir_lowering_sql.lower_ir
query_emitter_func = emit_sql.emit_code_from_ir
return _compile_graphql_generic(
SQL_LANGUAGE, lowering_func, query_emitter_func,
schema, graphql_... | Compile the GraphQL input using the schema into a SQL query and associated metadata.
Args:
schema: GraphQL schema object describing the schema of the graph to be queried
graphql_string: the GraphQL query to compile to SQL, as a string
compiler_metadata: SQLAlchemy metadata containing tables... |
353,514 | def apps_location_installations_reorder(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/app_location_installations
api_path = "/api/v2/apps/location_installations/reorder.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/app_location_installations#reorder-app-installations-for-location |
353,515 | def _parse_data(self):
data = self._cache
res = dict()
res[MI_HUMIDITY] = float(data[9:13])
res[MI_TEMPERATURE] = float(data[2:6])
return res | Parses the byte array returned by the sensor.
The sensor returns 14 bytes in total, a readable text with the
temperature and humidity. e.g.:
54 3d 32 35 2e 36 20 48 3d 32 33 2e 36 00 -> T=25.6 H=23.6 |
353,516 | def __send_retry_requests(self, last_send_failure_time):
with self.__send_retry_requests_lock:
with self.__requests:
retry_reqs = [req for req in self.__requests.values()
if req._sent_without_response(last_send_failure_... | Called via Timer from __send_ready to resend requests which might not have been sent due to transport
failure. This can happen since the current transport implementation does not received acknowledgements
for sent messages. |
353,517 | def run(self):
from zengine.wf_daemon import run_workers, Worker
worker_count = int(self.manager.args.workers or 1)
if not self.manager.args.daemonize:
print("Starting worker(s)")
if worker_count > 1 or self.manager.args.autoreload:
run_workers(worker_c... | Starts a development server for the zengine application |
353,518 | def print_start_command(self, command):
size = len(command)
if size > 20:
raise RuntimeError()
n1 = size/10
n2 = size%10
self.send(+chr(n1)+chr(n2)+command) | Set print command
Args:
command: the type of command you desire.
Returns:
None
Raises:
RuntimeError: Command too long. |
353,519 | def read_file(filename):
lines = []
with open(filename) as f:
for line in f:
if len(line.strip()) != 0:
lines.append(line.strip())
return lines | Reads the lines of a file into a list, and returns the list
:param filename: String - path and name of the file
:return: List - lines within the file |
353,520 | def run_false_positive_experiment_correlation(seed,
num_neurons = 1,
a = 32,
dim = 4000,
num_samples = 20000,
... | Run an experiment to test the false positive rate based on the correlation
between bits. Correlation is measured as the average pairwise correlation
between bits for each pattern in the data (across all of the data).
To generate the results shown in the false positive vs. correlation figure,
we used the param... |
353,521 | def _parse_float(value, default=None):
if value is None:
return default
try:
return float(value)
except ValueError:
print "Couldn't cast value to `float`."
return default | Attempt to cast *value* into a float, returning *default* if it fails. |
353,522 | def zero2d(self):
return type(self)(x=np.atleast_2d(np.zeros((self.shape[0],self.shape[1]))),
row_names=self.row_names,
col_names=self.col_names,
isdiagonal=False) | get an 2D instance of self with all zeros
Returns
-------
Matrix : Matrix |
353,523 | def get(self, query, *parameters, **kwparameters):
rows = self._query(query, parameters, kwparameters)
if not rows:
return None
elif not isinstance(rows, list):
raise MySQLError("Query is not a select query")
elif len(rows) > 1:
raise MySQLErr... | Returns the first row returned for the given query. |
353,524 | def parse_fields_whois(self, response):
try:
temp = response.split()
ret = {: temp[4].strip()}
if ret[] not in self.rir_whois.keys():
raise ASNRegistryError(
.format(
ret[])
... | The function for parsing ASN fields from a whois response.
Args:
response (:obj:`str`): The response from the ASN whois server.
Returns:
dict: The ASN lookup results
::
{
'asn' (str) - The Autonomous System Number
... |
353,525 | def default(self, ip_dest, next_hop, **kwargs):
kwargs.update({: True})
return self._set_route(ip_dest, next_hop, **kwargs) | Set a static route to default (i.e. delete the matching route)
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on... |
353,526 | def get_epoch_price_divisor( block_height, namespace_id, units ):
try:
assert units in [TOKEN_TYPE_STACKS, ], .format(units)
except AssertionError as ae:
log.exception(ae)
log.error("FATAL: No such units {}".format(units))
os.abort()
divisor = if units == else
e... | what's the name price divisor for this epoch?
Not all epochs have one---if this epoch does NOT have BLOCKSTACK_INT_DIVISION set,
use get_epoch_price_multiplier() instead. |
353,527 | def parse_field_path(field_path):
model_path, field_name = field_path.rsplit(".", 1)
app_name, model_name = model_path.split()
_, app_label = app_name.rsplit(, 1)
return (app_label, model_name.lower()), field_name | Take a path to a field like "yacms.pages.models.Page.feature_image"
and return a model key, which is a tuple of the form ('pages', 'page'),
and a field name, e.g. "feature_image". |
353,528 | def fmt_title(text):
text = text.strip()
if len(text) == 0:
return text
else:
text = text.lower()
chunks = [chunk for chunk in text.split(" ") if len(chunk) >= 1]
new_chunks = list()
for chunk in chunks:
if chunk not in _function_words:
... | Article title formatter.
Except functional words, first letter uppercase. Example:
"Google Killing Annoying Browsing Feature"
**中文文档**
文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。 |
353,529 | def _filter_by_range_schema(self, qs, lookup, sublookup, value, schema):
sublookup = sublookup or RANGE_INTERSECTION_LOOKUP
if not sublookup == RANGE_INTERSECTION_LOOKUP:
raise ValueError( %
RANGE_INT... | Filters given entity queryset by an attribute which is linked to given
range schema. Lookups `between` yields items that lie not completely
within given range but have intersection with it. For example, and item
with x=(2,5) will match q=(3,None) or q=(0,3). See tests for details.
q... |
353,530 | def _set_up_object_manager(self):
if self.path == :
cond = /\
else:
cond = %s/\ % self.path
self.AddMethod(OBJECT_MANAGER_IFACE,
, , ,
+
+ cond + )
self.object_manager = self | Set up this mock object as a D-Bus ObjectManager. |
353,531 | def delete(self, historics_id):
return self.request.post(, data=dict(id=historics_id)) | Delete one specified playback query. If the query is currently running, stop it.
status_code is set to 204 on success
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete
:param historics_id: playback id of the query to delete
:typ... |
353,532 | def send_rendered_mail(subject, template_name, context_dict, from_email, to, attachments=[], cc=[], bcc=[]):
rendered = render_to_string(u"{}.html".format(template_name), context_dict)
text_content = render_to_string(u"{}.txt".format(template_name), context_dict)
return send_mail(subject, text_content,... | It sends mail after rendering html content and normal text using two different template (.html, .txt) with
the same name.
:param subject:
:param template_name: without file extension
:param context_dict:
:param from_email:
:param to:
:param attachments: |
353,533 | def image_performance_query(self, uid_list):
if uid_list == []:
return {}
if not isinstance(uid_list, list):
uid_list = [uid_list]
smt_userid = zvmutils.get_smt_userid()
rd = .join((
"SMAPI %s API Image_Performance_Query" % smt_userid,
... | Call Image_Performance_Query to get guest current status.
:uid_list: A list of zvm userids to be queried |
353,534 | def pdist_sq_periodic(r, L):
d = csep_periodic(r, r, L)
d[np.identity(len(r), dtype=np.bool)] = np.inf
d_sq = np.sum(np.square(d), axis=-1)
return d_sq | Return the squared distance between all combinations of
a set of points, in periodic space.
Parameters
----------
r: shape (n, d) for n points in d dimensions.
Set of points
L: float array, shape (d,)
System lengths.
Returns
-------
d_sq: float array, shape (n, n, d)
... |
353,535 | def rename(self, new_name):
return self.get_data(
"images/%s" % self.id,
type=PUT,
params={"name": new_name}
) | Rename an image |
353,536 | def epochs_joint(ts, variability=None, threshold=0.0, minlength=1.0,
proportion=0.75, plot=True):
if ts.ndim <= 2:
return analyses1.epochs_joint(
ts, variability, threshold, minlength, plot)
else:
return distob.vectorize(analyses1.epochs_joint)(
... | Identify epochs within a multivariate time series where at least a
certain proportion of channels are "stationary", based on a previously
computed variability measure.
(Note: This requires an IPython cluster to be started first,
e.g. on a workstation type 'ipcluster start')
Args:
ts Tim... |
353,537 | def get_src_blocks(self, seed=None):
if seed:
self.state = seed
blockseed = self.state
d = self._sample_d()
have = 0
nums = set()
while have < d:
num = self._get_next() % self.K
if num not in nums:
nums.add(nu... | Returns the indices of a set of `d` source blocks
sampled from indices i = 1, ..., K-1 uniformly, where
`d` is sampled from the RSD described above. |
353,538 | def conditions(self, sp_entity_id):
return factory(saml.Conditions,
not_before=instant(),
not_on_or_after=self.not_on_or_after(sp_entity_id),
audience_restriction=[factory(
saml.Audie... | Return a saml.Condition instance
:param sp_entity_id: The SP entity ID
:return: A saml.Condition instance |
353,539 | def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None):
gvars = self.gvars()
lvars = self.lvars()
lvars[] = self
if executor:
lvars.update(executor.get_lvars())
return SCons.Subst.scons_subst_list(string, self, raw, target, so... | Calls through to SCons.Subst.scons_subst_list(). See
the documentation for that function. |
353,540 | def fit(self, X, y=None, input_type=):
X = self._validate_input(X, input_type)
self.fit_geometry(X, input_type)
random_state = check_random_state(self.random_state)
self.embedding_, self.eigenvalues_, self.eigenvectors_ = spectral_embedding(self.geom_,
... | Fit the model from data in X.
Parameters
----------
input_type : string, one of: 'data', 'distance' or 'affinity'.
The values of input data X. (default = 'data')
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples in the number of sampl... |
353,541 | def is_json(self, headers):
ret = False
ct = headers.get("content-type", "").lower()
if ct:
ret = ct.lower().rfind("json") >= 0
return ret | return true if content_type is a json content type |
353,542 | def create_indexes(cls, target=None, recreate=False):
results = []
collection = cls.get_collection(target)
if recreate:
collection.drop_indexes()
for index in cls.__indexes__.values():
results.append(index.create(collection))
return results | Iterate all known indexes and construct them.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes |
353,543 | def convert_path(cls, file):
if isinstance(file,str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
print("Incorrect path specified")
return -1 | Check to see if an extended path is given and convert appropriately |
353,544 | def send_and_receive(self, req):
rx_data = self._send_and_receive(target=req.target,
lun=req.lun,
netfn=req.netfn,
cmdid=req.cmdid,
payload... | Interface function to send and receive an IPMI message.
target: IPMI target
req: IPMI message request
Returns the IPMI message response. |
353,545 | def build(*onts, fail=False, n_jobs=9, write=True):
tail = lambda:tuple()
lonts = len(onts)
if lonts > 1:
for i, ont in enumerate(onts):
if ont.__name__ == :
onts = onts[:-1]
def tail(o=ont):
return o.setup(),
if i ... | Set n_jobs=1 for debug or embed() will crash. |
353,546 | def repack_dictlist(data,
strict=False,
recurse=False,
key_cb=None,
val_cb=None):
if isinstance(data, six.string_types):
try:
data = salt.utils.yaml.safe_load(data)
except salt.utils.yaml.parser.ParserEr... | Takes a list of one-element dicts (as found in many SLS schemas) and
repacks into a single dictionary. |
353,547 | def _read_http_data(self, size, kind, flag):
_plen = 0
_flag = dict(
END_STREAM=False,
PADDED=False,
)
for index, bit in enumerate(flag):
if index == 0 and bit:
_flag[] = True
elif index == 3 and bit:
... | Read HTTP/2 DATA frames.
Structure of HTTP/2 DATA frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
... |
353,548 | def create_instance(StackId=None, LayerIds=None, InstanceType=None, AutoScalingType=None, Hostname=None, Os=None, AmiId=None, SshKeyName=None, AvailabilityZone=None, VirtualizationType=None, SubnetId=None, Architecture=None, RootDeviceType=None, BlockDeviceMappings=None, InstallUpdatesOnBoot=None, EbsOptimized=None, Ag... | Creates an instance in a specified stack. For more information, see Adding an Instance to a Layer .
See also: AWS API Documentation
:example: response = client.create_instance(
StackId='string',
LayerIds=[
'string',
],
InstanceType='string',
AutoScal... |
353,549 | def restore_initializer(filename, name_fn=None,
collection=tf.GraphKeys.GLOBAL_VARIABLES):
def _restore_initializer(getter, name, *args, **kwargs):
collections = kwargs["collections"]
if collections is None:
collections = [tf.GraphKeys.GLOBAL_VARIABLES]
if (kw... | Custom getter to restore all variables with `snt.restore_initializer`.
Args:
filename: The filename of the checkpoint.
name_fn: A function which can map the name of the variable requested. This
allows restoring variables with values having different names in the
checkpoint.
collection: Only s... |
353,550 | def _inject_selenium(self, test):
from django.conf import settings
test_case = get_test_case_class(test)
test_case.selenium_plugin_started = True
sel = selenium(
getattr(settings, "SELENIUM_HOST", "localhost"),
int(getattr(settings, "SELENIUM_P... | Injects a selenium instance into the method. |
353,551 | def get_deps(cfg=None,deps=[]):
if not cfg is None:
if not in cfg:
cfg[]=deps
else:
deps=cfg[]
if not len(deps)==0:
for dep in deps:
if not dep in cfg:
runbashcmd(f,test=cfg[])
cfg[dep]=dep
logging.info(f"{len(... | Installs conda dependencies.
:param cfg: configuration dict |
353,552 | def marginal(repertoire, node_index):
index = tuple(i for i in range(repertoire.ndim) if i != node_index)
return repertoire.sum(index, keepdims=True) | Get the marginal distribution for a node. |
353,553 | def update_(self, sct_dict, conf_arg=True):
for opt, val in sct_dict.items():
if opt not in self.def_:
continue
if not conf_arg or self.def_[opt].conf_arg:
self[opt] = val | Update values of configuration section with dict.
Args:
sct_dict (dict): dict indexed with option names. Undefined
options are discarded.
conf_arg (bool): if True, only options that can be set in a config
file are updated. |
353,554 | def pprint(self):
items = sorted(self.items())
return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items) | Return tag key=value pairs in a human-readable format. |
353,555 | def sendRemoteImage(
self, image_url, message=None, thread_id=None, thread_type=ThreadType.USER
):
return self.sendRemoteFiles(
file_urls=[image_url],
message=message,
thread_id=thread_id,
thread_type=thread_type,
) | Deprecated. Use :func:`fbchat.Client.sendRemoteFiles` instead |
353,556 | def network_interface_absent(name, resource_group, connection_auth=None):
ret = {
: name,
: False,
: ,
: {}
}
if not isinstance(connection_auth, dict):
ret[] =
return ret
iface = __salt__[](
name,
resource_group,
azurearm_lo... | .. versionadded:: 2019.2.0
Ensure a network interface does not exist in the resource group.
:param name:
Name of the network interface.
:param resource_group:
The resource group assigned to the network interface.
:param connection_auth:
A dict with subscription and authentica... |
353,557 | async def fetch_widget(self, guild_id):
data = await self.http.get_widget(guild_id)
return Widget(state=self._connection, data=data) | |coro|
Gets a :class:`.Widget` from a guild ID.
.. note::
The guild must have the widget enabled to get this information.
Parameters
-----------
guild_id: :class:`int`
The ID of the guild.
Raises
-------
Forbidden
T... |
353,558 | def get_searches(self, quick=False, saved=True):
params = {}
if saved and not quick:
params[] =
elif quick:
params[] =
return self._get(self._url(),
body_type=models.Searches, params=params).get_body() | Get searches listing.
:param quick bool: Include quick searches (default False)
:param quick saved: Include saved searches (default True)
:returns: :py:class:`planet.api.models.Searches`
:raises planet.api.exceptions.APIException: On API error. |
353,559 | def get_template_sources(self, template_name):
if not in template_name:
self.reset(True)
return
app, template_path = template_name.split()
if app:
yield NamespaceOrigin(
app_name=app,
name= % (app, template_name),
... | Build a list of Origin to load 'template_name' splitted with ':'.
The first item is the name of the application and the last item
is the true value of 'template_name' provided by the specified
application. |
353,560 | def get_default_config(self):
config = super(CpuAcctCgroupCollector, self).get_default_config()
config.update({
:
})
return config | Returns the default collector settings |
353,561 | def on_timer(self, _signum, _unused_frame):
if self.is_shutting_down:
LOGGER.debug()
return
if not self.polled:
self.poll()
self.polled = True
self.set_timer(5)
else:
self.polled = False
self.poll_resu... | Invoked by the Poll timer signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted |
353,562 | def makeServoMinLimitPacket(ID, angle):
angle = int(angle/300.0*1023)
pkt = makeWritePacket(ID, xl320.XL320_CW_ANGLE_LIMIT, le(angle))
return pkt | Sets the minimum servo angle (in the CW direction) |
353,563 | def _uniquetwig(self, twig, force_levels=[]):
for_this_param = self.filter(twig, check_visible=False)
metawargs = {}
if not in force_levels:
metawargs[k] = None
if len(ps_for_this_search) != 1:
... | get the least unique twig for the parameter given by twig that
will return this single result for THIS PS
:parameter str twig: a twig that will return a single Parameter from
THIS PS
:parameter list force_levels: (optional) a list of "levels"
(eg. context) that shoul... |
353,564 | def get_log_lines(self, source_id, scan_id):
target_url = self.client.get_url(, , , {: source_id, : scan_id})
r = self.client.request(, target_url, headers={: }, stream=True)
return r.iter_lines(decode_unicode=True) | Get the log text for a scan object
:rtype: Iterator over log lines. |
353,565 | def get_port_channel_detail_output_lacp_aggregator_type(self, **kwargs):
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_detail, "output")
lacp = ET.Sub... | Auto Generated Code |
353,566 | def file_writer(self, in_frame):
self.update_config()
path = self.config[]
encoder = self.config[]
fps = self.config[]
bit16 = self.config[]
numpy_image = in_frame.as_numpy()
ylen, xlen, bpc = numpy_image.shape
if bpc == 3:
if in_frame... | Generator process to write file |
353,567 | def tag_instance(self, instance_id, tag_list):
title = % self.__class__.__name__
input_fields = {
: instance_id,
: tag_list
}
for key, value in input_fields.items():
object_title = % (title, key, str(value))
self.fields.v... | a method for adding or updating tags on an AWS instance
:param instance_id: string of instance id on AWS
:param tag_list: list of single key-value pairs
:return: dictionary with aws response info |
353,568 | def tokens(self, format_string):
if format_string not in self.format_string_cache:
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
tokens = list(re.finditer(self.reg_ex, format_string))
self.format_string_c... | Get the tokenized format_string.
Tokenizing is resource intensive so we only do it once and cache it |
353,569 | def add_widget(self, wid, index=0, canvas=None):
super().add_widget(wid, index, canvas)
if not hasattr(wid, ):
return
wid._no_use_canvas = True
mycanvas = (
self.canvas.before if canvas == else
self.canvas.after if canvas == else
... | Put the :class:`Pawn` at a point along my length proportionate to
how close it is to finishing its travel through me.
Only :class:`Pawn` should ever be added as a child of :class:`Arrow`. |
353,570 | def _file_exists_in_gcs(gcs_file_path, credentials=None):
gcs_service = _get_storage_service(credentials)
bucket_name, object_name = gcs_file_path[len():].split(, 1)
request = gcs_service.objects().get(
bucket=bucket_name, object=object_name, projection=)
try:
request.execute()
return True
e... | Check whether the file exists, in GCS.
Args:
gcs_file_path: The target file path; should have the 'gs://' prefix.
credentials: Optional credential to be used to load the file from gcs.
Returns:
True if the file's there. |
353,571 | def addTaxonToFeature(self, taxonid):
self.taxon = taxonid
self.graph.addTriple(self.fid, self.globaltt[], self.taxon)
return | Given the taxon id, this will add the following triple:
feature in_taxon taxonid
:param graph:
:param taxonid:
:return: |
353,572 | def _handle_join_dags(self, request):
if request.payload[] is None:
send_response = len(self._dags_running) <= 1
else:
send_response = all([name not in self._dags_running.keys()
for name in request.payload[]])
if send_response:
... | The handler for the join_dags request.
If dag names are given in the payload only return a valid Response if none of
the dags specified by the names are running anymore. If no dag names are given,
wait for all dags except one, which by design is the one that issued the request,
to be fi... |
353,573 | def array(a, context=None, axis=(0,), dtype=None, npartitions=None):
if dtype is None:
arry = asarray(a)
dtype = arry.dtype
else:
arry = asarray(a, dtype)
shape = arry.shape
ndim = len(shape)
axes = ConstructSpark._format_axe... | Create a spark bolt array from a local array.
Parameters
----------
a : array-like
An array, any object exposing the array interface, an
object whose __array__ method returns an array, or any
(nested) sequence.
context : SparkContext
A co... |
353,574 | def summary(x, rm_nan=False, debug=False):
if type(x) is np.ndarray:
xx = np.copy(x)
else:
if type(x) is list:
xx = np.array(x)
else:
raise ValueError( + str(x) + )
if xx.ndim is not 1:
raise ValueError( + str(xx.ndim) + )
return... | Compute basic statistical parameters.
Parameters
----------
x : 1d numpy array, float
Input array with values which statistical properties are
requested.
rm_nan : bool
If True, filter out NaN values before computing statistics.
debug : bool
If True prints computed v... |
353,575 | def publish(self, message_type, client_id, client_storage, *args, **kwargs):
p = self.pack(message_type, client_id, client_storage, args, kwargs)
self.client.publish(self.channel, p) | Publishes a message |
353,576 | def FindModuleIdDefiningFlag(self, flagname, default=None):
registered_flag = self.FlagDict().get(flagname)
if registered_flag is None:
return default
for module_id, flags in six.iteritems(self.FlagsByModuleIdDict()):
for flag in flags:
if (flag.name == re... | Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e... |
353,577 | def _add_data(self, plotter_cls, *args, **kwargs):
return super(DatasetPlotter, self)._add_data(plotter_cls, self._ds,
*args, **kwargs) | Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
Returns
-------
%(ProjectPlotter._add_data.returns)s |
353,578 | def ingest(self, co, classname=None, code_objects={}, show_asm=None):
if not show_asm:
show_asm = self.show_asm
bytecode = self.build_instructions(co)
if show_asm in (, ):
for instr in bytecode.get_instructions(co):
print(instr.disasse... | Pick out tokens from an uncompyle6 code object, and transform them,
returning a list of uncompyle6 'Token's.
The transformations are made to assist the deparsing grammar.
Specificially:
- various types of LOAD_CONST's are categorized in terms of what they load
- COME_FRO... |
353,579 | def has_gocomics_comic(name):
cname = "Gocomics/%s" % name
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname == cname.lower():
return True
return False | Test if comic name already exists. |
353,580 | def center_crop(im, min_sz=None):
r,c,*_ = im.shape
if min_sz is None: min_sz = min(r,c)
start_r = math.ceil((r-min_sz)/2)
start_c = math.ceil((c-min_sz)/2)
return crop(im, start_r, start_c, min_sz) | Return a center crop of an image |
353,581 | def _get_base_name(hostname, step_name, attempt_id, max_length):
max_length = int(max_length)
if len(hostname)+len(step_name)+MIN_TASK_ID_CHARS+2 > max_length:
hostname_chars = int(math.ceil(
(max_length-MIN_TASK_ID_CHARS-2)/float(2)))
step_name_chars = int(math.floor(
... | Create a base name for the worker instance that will run the specified
task run attempt, from this server. Since hostname and step name will be
duplicated across workers (reruns, etc.), ensure that at least
MIN_TASK_ID_CHARS are preserved in the instance name. Also, prevent names
from ending with dashes... |
353,582 | def initialize_ray():
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title() == "True":
from tempfile import gettempdir
plasma... | Initializes ray based on environment variables and internal defaults. |
353,583 | def doDailies(usr, dailyList):
dailies = []
for daily in Daily.__subclasses__():
dailies.append(daily.__name__)
for daily in dailyList:
if not daily in dailies:
raise invalidDaily
for daily i... | Does a list of dailies and yields each result
Takes a list of valid dailies, initiates each one, and then proceeds
to play each one and yield it's resulting message. Note that the names
given in the list must be the same as the daily's class file.
Parameters
... |
353,584 | def get_cache(app):
jobtastic_cache_setting = app.conf.get()
if isinstance(jobtastic_cache_setting, BaseCache):
return jobtastic_cache_setting
if in CACHES:
if jobtastic_cache_setting:
try:
return WrappedCache(get_django_cache(jobtastic_cache_setting))
... | Attempt to find a valid cache from the Celery configuration
If the setting is a valid cache, just use it.
Otherwise, if Django is installed, then:
If the setting is a valid Django cache entry, then use that.
If the setting is empty use the default cache
Otherwise, if Werkzeug is installed, ... |
353,585 | def is_multisig(privkey_info, blockchain=, **blockchain_opts):
if blockchain == :
return btc_is_multisig(privkey_info, **blockchain_opts)
else:
raise ValueError(.format(blockchain)) | Is the given private key bundle a multisig bundle? |
353,586 | def populateCsv(self):
workingDirPath = createDir(self._workingDir)
csvPath = os.path.join(workingDirPath, "data.csv")
self.writeCsv(csvPath)
return csvPath, workingDirPath | Writes data from streams into CSV in working directory.
:return: |
353,587 | def get_extra_vehicle_info(self, authentication_info):
import requests
base_url = "https://secure.ritassist.nl/GenericServiceJSONP.ashx"
query = "?f=CheckExtraVehicleInfo" \
"&token={token}" \
"&equipmentId={identifier}" \
"&lastHash=null... | Get extra data from the API. |
353,588 | def optimize(host=None, core_name=None):
hostsuccessdataerrorswarnings*
ret = _get_return_dict()
if _get_none_or_value(core_name) is None and _check_for_cores():
success = True
for name in __salt__[]():
url = _format_url(, host=host, core_name=name,
... | Search queries fast, but it is a very expensive operation. The ideal
process is to run this with a master/slave configuration. Then you
can optimize the master, and push the optimized index to the slaves.
If you are running a single solr instance, or if you are going to run
this on a slave be aware tha... |
353,589 | def _load_edflib(filename):
import edflib
e = edflib.EdfReader(filename, annotations_mode=)
if np.ptp(e.get_samples_per_signal()) != 0:
raise Error()
if np.ptp(e.get_signal_freqs()) != 0:
raise Error()
n = e.samples_in_file(0)
m = e.signals_in_file
channelnames = e.get_s... | load a multi-channel Timeseries from an EDF (European Data Format) file
or EDF+ file, using edflib.
Args:
filename: EDF+ file
Returns:
Timeseries |
353,590 | def utc_strftime(self, format):
tup = self._utc_tuple(_half_second)
year, month, day, hour, minute, second = tup
second = second.astype(int)
zero = zeros_like(year)
tup = (year, month, day, hour, minute, second, zero, zero, zero)
if self.shape:
return... | Format the UTC time using a Python date formatting string.
This internally calls the Python ``strftime()`` routine from the
Standard Library ``time()`` module, for which you can find a
quick reference at ``http://strftime.org/``. If this object is
an array of times, then a sequence of ... |
353,591 | def get_signin_vcode(cookie, codeString):
url = .join([
const.PASSPORT_BASE,
,
codeString,
])
headers={
: cookie.header_output(),
: const.REFERER,
}
req = net.urlopen(url, headers=headers)
if req:
return req.data
else:
return None | 获取登录时的验证码图片.
codeString - 调用check_login()时返回的codeString. |
353,592 | def _binary_arithemtic(self, left, binary, right):
if isinstance(right, (int, float)):
right = right
elif isinstance(right, Column):
right = right.execution_name
else:
raise AttributeError(
"{} can only be used ".format(binary)
... | Parameters
----------
operand: Column object, integer or float
Value on which to apply operator to this column
binary: char
binary arithmetic operator (-, +, *, /, ^, %)
Returns
-------
self
Notes
-----
Returning self will... |
353,593 | def round_to_quarter(start_time, end_time):
today = datetime.date.today()
start_date = datetime.datetime.combine(today, start_time)
end_date = datetime.datetime.combine(today, end_time)
difference_minutes = (end_date - start_date).seconds / 60
remainder = difference_minutes % 15
... | Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes. |
353,594 | def location_name(self, name):
response = self._request(
,
input=name)
return _get_node(response, , ) | location.name |
353,595 | def cc(filename: ,
output:
s suffix with ".py"name of languageunnamer.py'
lang.dump(output) | rbnf source code compiler. |
353,596 | def applyCut(self, cut):
return Catalog(self.config, data=self.data[cut]) | Return a new catalog which is a subset of objects selected
using the input cut array.
NOTE: This is really a *selection* (i.e., objects are retained if the value of 'cut' is True) |
353,597 | def write_crtf(regions, filename, coordsys=, fmt=, radunit=):
output = crtf_objects_to_string(regions, coordsys, fmt, radunit)
with open(filename, ) as fh:
fh.write(output) | Converts a `list` of `~regions.Region` to CRTF string and write to file.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
filename : `str`
Filename in which the string is to be written. Default is 'new.crtf'
coordsys : `str`, optional
Astropy Coordina... |
353,598 | def get_dpi(raise_error=True):
try:
user32.SetProcessDPIAware()
except AttributeError:
pass
dc = user32.GetDC(0)
h_size = gdi32.GetDeviceCaps(dc, HORZSIZE)
v_size = gdi32.GetDeviceCaps(dc, VERTSIZE)
h_res = gdi32.GetDeviceCaps(dc, HORZRES)
v_res = gdi32.GetDeviceCaps(d... | Get screen DPI from the OS
Parameters
----------
raise_error : bool
If True, raise an error if DPI could not be determined.
Returns
-------
dpi : float
Dots per inch of the primary screen. |
353,599 | def update_properties_cache(sender, instance, action, reverse, model, pk_set, **kwargs):
"Property cache actualization at POI save. It will not work yet after property removal."
if action == :
instance.save_properties_cache() | Property cache actualization at POI save. It will not work yet after property removal. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.