Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
359,700 | def acosh(wave):
r
pexdoc.exh.addex(ValueError, "Math domain error", bool(min(wave._dep_vector) < 1))
return _operation(wave, "acosh", "", np.arccosh) | r"""
Return the hyperbolic arc cosine of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. p... |
359,701 | def QA_fetch_stock_min_adv(
code,
start, end=None,
frequence=,
if_drop_index=True,
collections=DATABASE.stock_min):
获取股票分钟线
if frequence in [, ]:
frequence =
elif frequence in [, ]:
frequence =
elif frequence in [, ]:
frequence =... | '获取股票分钟线'
:param code: 字符串str eg 600085
:param start: 字符串str 开始日期 eg 2011-01-01
:param end: 字符串str 结束日期 eg 2011-05-01
:param frequence: 字符串str 分钟线的类型 支持 1min 1m 5min 5m 15min 15m 30min 30m 60min 60m 类型
:param if_drop_index: Ture False , dataframe drop index or not
:param collections: mongodb ... |
359,702 | def set_principal_credit_string(self, credit_string=None):
if credit_string is None:
raise NullArgument()
metadata = Metadata(**settings.METADATA[])
if metadata.is_read_only():
raise NoAccess()
if self._is_valid_input(credit_string, metadata, array=False)... | Sets the principal credit string.
:param credit_string: the new credit string
:type credit_string: ``string``
:raise: ``InvalidArgument`` -- ``credit_string`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NullArgument`` -- ``credit_string`` i... |
359,703 | def getGameHighScores(self, user_id, game_message_identifier):
p = _strip(locals(), more=[])
p.update(_dismantle_message_identifier(game_message_identifier))
return self._api_request(, _rectify(p)) | See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText` |
359,704 | def p_propertyDeclaration_5(p):
quals = OrderedDict([(x.name, x) for x in p[1]])
p[0] = CIMProperty(p[3], None, type=p[2], qualifiers=quals) | propertyDeclaration_5 : qualifierList dataType propertyName '; |
359,705 | def svevent_reader(in_file):
with open(in_file) as in_handle:
while 1:
line = next(in_handle)
if line.startswith(">"):
break
header = line[1:].rstrip().split("\t")
reader = csv.reader(in_handle, dialect="excel-tab")
for parts in reader:
... | Lazy generator of SV events, returned as dictionary of parts. |
359,706 | def cluster(dupes, threshold=.5, max_components=30000):
distance_threshold = 1 - threshold
dupe_sub_graphs = connected_components(dupes, max_components)
for sub_graph in dupe_sub_graphs:
if len(sub_graph) > 1:
i_to_id, condensed_distances, N = condensedDistance(sub_graph)
... | Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments:
threshold -- number betweent 0 and 1 (default is .5). lowering the
number will increase precision, raising it will increase
... |
359,707 | def cache_control(self):
def on_update(cache_control):
if not cache_control and in self.headers:
del self.headers[]
elif cache_control:
self.headers[] = cache_control.to_header()
return parse_cache_control_header(self.headers.get(),
... | The Cache-Control general-header field is used to specify
directives that MUST be obeyed by all caching mechanisms along the
request/response chain. |
359,708 | def scatter(self, x, y, xerr=[], yerr=[], mark=, markstyle=None):
self.plot(x, y, xerr=xerr, yerr=yerr, mark=mark, linestyle=None,
markstyle=markstyle) | Plot a series of points.
Plot a series of points (marks) that are not connected by a
line. Shortcut for plot with linestyle=None.
:param x: array containing x-values.
:param y: array containing y-values.
:param xerr: array containing errors on the x-values.
:param yerr:... |
359,709 | def _expected_condition_find_element_containing_text(self, element_text_pair):
element, text = element_text_pair
web_element = self._expected_condition_find_element(element)
try:
return web_element if web_element and text in web_element.text else False
except StaleEl... | Tries to find the element and checks that it contains the specified text, but does not thrown an exception if the element is
not found
:param element_text_pair: Tuple with 2 items where:
[0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
... |
359,710 | def prepare_mac_header(token, uri, key, http_method,
nonce=None,
headers=None,
body=None,
ext=,
hash_algorithm=,
issue_time=None,
draft=0):
http_metho... | Add an `MAC Access Authentication`_ signature to headers.
Unlike OAuth 1, this HMAC signature does not require inclusion of the
request payload/body, neither does it use a combination of client_secret
and token_secret but rather a mac_key provided together with the access
token.
Currently two algo... |
359,711 | def write_xml(self, outfile, encoding="UTF-8"):
if any([key for item in self.items for key in vars(item) if
key.startswith() and getattr(item, key)]):
self.rss_attrs["xmlns:media"] = "http://search.yahoo.com/mrss/"
self.generator = _generator_name
su... | Write the Media RSS Feed's XML representation to the given file. |
359,712 | def code_events(self):
if self._resulting_events:
return self._resulting_events
for i, (lineno, mem, func, fname) in enumerate(self._events_list):
mem_in_mb = float(mem - self.mem_overhead) / _BYTES_IN_MB
if (self._resulting_events and
sel... | Returns processed memory usage. |
359,713 | def verify_ticket_signature(self, data, sig):
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
print("%s" % e)
... | Verify ticket signature. |
359,714 | def sqs_delete_queue(queue_url, client=None):
if not client:
client = boto3.client()
try:
client.delete_queue(QueueUrl=queue_url)
return True
except Exception as e:
LOGEXCEPTION(
% (queue_url,))
return False | This deletes an SQS queue given its URL
Parameters
----------
queue_url : str
The SQS URL of the queue to delete.
client : boto3.Client or None
If None, this function will instantiate a new `boto3.Client` object to
use in its operations. Alternatively, pass in an existing `bot... |
359,715 | def cycle_data(self, repository, cycle_interval, chunk_size, sleep_time):
jobs_max_timestamp = datetime.datetime.now() - cycle_interval
jobs_cycled = 0
while True:
jobs_chunk = list(self.filter(repository=repository, submit_time__lt=jobs_max_timestamp)
... | Delete data older than cycle_interval, splitting the target data into
chunks of chunk_size size. Returns the number of result sets deleted |
359,716 | def _load(self, slug):
self._slug = slug
page_dir = os.path.join(self.site.dirs[], self._slug)
page_file_name = os.path.join(page_dir, self._slug + )
self._dirs[] = page_dir
self._dirs[] = page_file_name
self._dirs[] = os.path.join(self.site.dirs[], slug... | Load the page. The _file_name param is known, because this
method is only called after having checked that the page exists. |
359,717 | def totalNumberOfTiles(self, minZoom=None, maxZoom=None):
"Return the total number of tiles for this instance extent"
nbTiles = 0
minZoom = minZoom or 0
if maxZoom:
maxZoom = maxZoom + 1
else:
maxZoom = len(self.RESOLUTIONS)
for zoom in xrange(minZ... | Return the total number of tiles for this instance extent |
359,718 | def _checkNumerical(inputvalue, minvalue=None, maxvalue=None, description=):
if not isinstance(description, str):
raise TypeError(.format(description))
if not isinstance(inputvalue, (int, long, float)):
raise TypeError(.format(description, inputvalue))
if not isinstance(minvalue,... | Check that the given numerical value is valid.
Args:
* inputvalue (numerical): The value to be checked.
* minvalue (numerical): Minimum value Use None to skip this part of the test.
* maxvalue (numerical): Maximum value. Use None to skip this part of the test.
* description (string... |
359,719 | def save(f, arr, vocab):
f.write(( % (arr.shape[0], arr.shape[1])).encode())
for word, idx in vocab:
_write_line(f, arr[idx], word) | Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API. |
359,720 | def _add_or_remove_flag(self, flag, add):
meth = self.add_flag if add else self.remove_flag
meth(flag) | Add the given `flag` if `add` is True, remove it otherwise. |
359,721 | def fail_tmp(item, max_tries=None, ttl=None):
try:
max_tries = item.max_tries if max_tries is None else max_tries
ttl = item.ttl if ttl is None else ttl
check_ttl_max_tries(item.tries+1, item.enqueued_at, max_tries, ttl)
item.tries += 1
new_name = cons... | Try to fail a work-item temporarily (up recount and keep in queue),
if max tries or ttl is exhausted, escalate to permanant failure. |
359,722 | def find(self, keys, _index=0):
if isinstance(keys, six.string_types):
keys = re.split(r, keys)
if _index >= len(keys):
return self
key = keys[_index]
if key in self.components:
component = self.components[key]
if isinstance(comp... | :param keys: key path. ``'a.b'`` is equivalent to ``['a', 'b']``
:type keys: :class:`str` or :class:`list`
Find a nested :class:`Component` by a "`.`" separated list of names.
for example::
>>> motor.find('bearing.outer_ring')
would return the Part instance of the motor be... |
359,723 | def _CreateOutputFileHandles(self, output_type):
gzip_filehandle_parent = tempfile.NamedTemporaryFile(suffix=output_type)
gzip_filehandle = gzip.GzipFile(gzip_filehandle_parent.name, "wb",
self.GZIP_COMPRESSION_LEVEL,
gzip_filehandle_p... | Creates a new gzipped output tempfile for the output type.
We write to JSON data to gzip_filehandle to get compressed data. We hold a
reference to the original filehandle (gzip_filehandle_parent) so we can pass
the gzip data to bigquery.
Args:
output_type: string of export type to be used in fil... |
359,724 | def waiver2mef(sciname, newname=None, convert_dq=True, writefits=True):
if isinstance(sciname, fits.HDUList):
filename = sciname.filename()
else:
filename = sciname
try:
clobber = True
fimg = convertwaiveredfits.convertwaiveredfits(filename)
_dqname =... | Converts a GEIS science file and its corresponding
data quality file (if present) to MEF format
Writes out both files to disk.
Returns the new name of the science image. |
359,725 | def intensity(image):
if len(image.shape) > 2:
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) / 255
elif issubclass(image.dtype.type, np.integer):
image /= 255
return float(np.sum(image) / np.prod(image.shape)) | Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float |
359,726 | def encodeIntoArray(self, inputData, output):
altitude = None
if len(inputData) == 4:
(speed, longitude, latitude, altitude) = inputData
else:
(speed, longitude, latitude) = inputData
coordinate = self.coordinateForPosition(longitude, latitude, altitude)
radius = self.radiusForSpeed... | See `nupic.encoders.base.Encoder` for more information.
:param: inputData (tuple) Contains speed (float), longitude (float),
latitude (float), altitude (float)
:param: output (numpy.array) Stores encoded SDR in this numpy array |
359,727 | def of(self, *indented_blocks) -> "CodeBlock":
if self.closed_by is None:
self.expects_body_or_pass = True
for block in indented_blocks:
if block is not None:
self._blocks.append((1, block))
self.finalise()
return self | By default, marks the block as expecting an indented "body" blocks of which are then supplied
as arguments to this method.
Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones,
this will generate a "pass" statement as the body. If there is a "closed_by"... |
359,728 | def direct_dispatch(self, arg, callback):
try:
self._current_callbacks.appendleft(callback)
exc_info = None
retval = None
retval = self._routine(arg)
except:
exc_info = sys.exc_info()
finally:
self._current_cal... | Directly dispatch a work item.
This method MUST only be called from inside of another work item and
will synchronously invoke the work item as if it was passed to
dispatch(). Calling this method from any other thread has undefined
consequences since it will be unsynchronized with respe... |
359,729 | def duration_minutes(duration):
if isinstance(duration, list):
res = dt.timedelta()
for entry in duration:
res += entry
return duration_minutes(res)
elif isinstance(duration, dt.timedelta):
return duration.total_seconds() / 60
else:
return duration | returns minutes from duration, otherwise we keep bashing in same math |
359,730 | def queryFilter(self, function=None):
if function is not None:
self.__query_filter = function
return function
def wrapper(func):
self.__query_filter = func
return func
return wrapper | Defines a decorator that can be used to filter
queries. It will assume the function being associated
with the decorator will take a query as an input and
return a modified query to use.
:usage
class MyModel(orb.Model):
objects = orb.ReverseLookup('Object')
... |
359,731 | async def get_or_create(self, model_, defaults=None, **kwargs):
try:
return (await self.get(model_, **kwargs)), False
except model_.DoesNotExist:
data = defaults or {}
data.update({k: v for k, v in kwargs.items() if not in k})
return (await self.... | Try to get an object or create it with the specified defaults.
Return 2-tuple containing the model instance and a boolean
indicating whether the instance was created. |
359,732 | def get_cidr_name(cidr, ip_ranges_files, ip_ranges_name_key):
for filename in ip_ranges_files:
ip_ranges = read_ip_ranges(filename, local_file=True)
for ip_range in ip_ranges:
ip_prefix = netaddr.IPNetwork(ip_range[])
cidr = netaddr.IPNetwork(cidr)
if cidr in... | Read display name for CIDRs from ip-ranges files
:param cidr:
:param ip_ranges_files:
:param ip_ranges_name_key:
:return: |
359,733 | def _set_fru(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=fru.fru, is_container=, presence=False, yang_name="fru", rest_name="fru", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u}}... | Setter method for fru, mapped from YANG variable /system_monitor_mail/fru (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fru is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_fru() directly. |
359,734 | def radiansBetween(self, other):
a = Point.unit(self.A, self.B)
b = Point.unit(other.A, other.B)
return math.acos(a.dot(b)) | :param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi]. |
359,735 | def create_cell_volumes(self):
self.cell_volumes = numpy.array(
[
abs(
self.node_coords[cell["nodes"]][1]
- self.node_coords[cell["nodes"]][0]
)
for cell in self.cells
]
)
ret... | Computes the volumes of the "cells" in the mesh. |
359,736 | def slots(self):
if self.implied:
return ()
data = clips.data.DataObject(self._env)
lib.EnvDeftemplateSlotNames(self._env, self._tpl, data.byref)
return tuple(
TemplateSlot(self._env, self._tpl, n.encode()) for n in data.value) | Iterate over the Slots of the Template. |
359,737 | def search(query, stats):
log.debug("Search query: {0}".format(query))
issues = []
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(
"{0}/rest/api/latest/search?{1}".format(
stats.parent.url, urllib.urlencode({... | Perform issue search for given stats instance |
359,738 | def make_zip_archive(self,
dst=None,
filters=all_true,
compress=True,
overwrite=False,
makedirs=False,
verbose=False):
self.assert_exists()
if... | Make a zip archive.
:param dst: output file path. if not given, will be automatically assigned.
:param filters: custom path filter. By default it allows any file.
:param compress: compress or not.
:param overwrite: overwrite exists or not.
:param verbose: display log or not.
... |
359,739 | def can_process(self, statement):
response = self.process(statement)
self.cache[statement.text] = response
return response.confidence == 1 | Determines whether it is appropriate for this
adapter to respond to the user input. |
359,740 | def GuinierPorodMulti(q, G, *Rgsalphas):
scalefactor = G
funcs = [lambda q: Guinier(q, G, Rgsalphas[0])]
indices = np.ones_like(q, dtype=np.bool)
constraints = []
for i in range(1, len(Rgsalphas)):
if i % 2:
qsep = _PGgen_qsep(Rgsalphas[i], Rgsalphas[i - 1], 3)
... | Empirical multi-part Guinier-Porod scattering
Inputs:
-------
``q``: independent variable
``G``: factor for the first Guinier-branch
other arguments: [Rg1, alpha1, Rg2, alpha2, Rg3 ...] the radii of
gyration and power-law exponents of the consecutive parts
Formula:
----... |
359,741 | def to_monthly(series, method=, how=):
return series.asfreq_actual(, method=method, how=how) | Convenience method that wraps asfreq_actual
with 'M' param (method='ffill', how='end'). |
359,742 | def timestamp(_, dt):
dt = util.to_utc(dt)
unix_timestamp = calendar.timegm(dt.timetuple())
| get microseconds since 2000-01-01 00:00 |
359,743 | def delay_service(self, t=None):
if len(self._departures) > 1:
agent = heappop(self._departures)
if t is None:
agent._time = self.service_f(agent._time)
else:
agent._time = t
heappush(self._departures, agent)
... | Adds an extra service time to the next departing
:class:`Agent's<.Agent>` service time.
Parameters
----------
t : float (optional)
Specifies the departing time for the agent scheduled
to depart next. If ``t`` is not given, then an additional
service t... |
359,744 | def rm_arrow(self, orig, dest, *args):
if (
orig not in self.arrow or
dest not in self.arrow[orig]
):
raise KeyError("No Arrow from {} to {}".format(orig, dest))
arr = self.arrow[orig].pop(dest)
if arr in self.selection_candidates:
... | Remove the :class:`Arrow` that goes from ``orig`` to ``dest``. |
359,745 | def word_error_rate(raw_predictions,
labels,
lookup=None,
weights_fn=common_layers.weights_nonzero):
def from_tokens(raw, lookup_):
gathered = tf.gather(lookup_, tf.cast(raw, tf.int32))
joined = tf.regex_replace(tf.reduce_join(gathered, axis=1), ... | Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to output tokens.
weights_fn: Weighting function.
Returns:
The word error rate. |
359,746 | def PrintVmInfo(vm, depth=1):
maxdepth = 10
if hasattr(vm, ):
if depth > maxdepth:
return
vmList = vm.childEntity
for c in vmList:
PrintVmInfo(c, depth+1)
return
if isinstance(vm, vim.VirtualApp):
vmList = vm.vm
for c in vmList:
... | Print information for a particular virtual machine or recurse into a folder
or vApp with depth protection |
359,747 | def user_parse(data):
yield , data.get()
yield , data.get()
yield , data.get()
yield , data.get()
yield , data.get()
yield , data.get()
yield , data.get()
yield , data.get() | Parse information from provider. |
359,748 | def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None):
creation_args = {
: self,
: self._autoload_embedded,
: lazy,
: db_loader
}
if collection_or_class in self.classe... | Creates an instance of a `Document` class corresponding to the given collection name or class.
:param collection_or_class: The name of the collection or a reference to the class for which to create an instance.
:param attributes: The attributes of the instance to be created
:param lazy: Whether... |
359,749 | def solve_T(self, P, V, quick=True):
rs namespace.
Parameters
----------
P : float
Pressure, [Pa]
V : float
Molar volume, [m^3/mol]
quick : bool, optional
Whether to use a SymPy cse-derived expression (3x faster) or
indivi... | r'''Method to calculate `T` from a specified `P` and `V` for the RK
EOS. Uses `a`, and `b`, obtained from the class's namespace.
Parameters
----------
P : float
Pressure, [Pa]
V : float
Molar volume, [m^3/mol]
quick : bool, optional
Wh... |
359,750 | def _relay_message(self, message):
info("relaying message: {message}")
if not message.was_sent_by(self._id_factory):
self.pipe.send(message)
self.pipe.deliver() | Relay messages from the forum on the server to the client represented
by this actor. |
359,751 | def get(cls, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._get_with_http_info(**kwargs)
else:
(data) = cls._get_with_http_info(**kwargs)
return data | Get cart.
Retrieve the shopping cart of the current session.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get(async=True)
>>> result = thread.get()
:param async bool
:retur... |
359,752 | def retrieve_all_pages(api_endpoint, **kwargs):
page_size = getattr(settings, , 20)
loaded_results = []
offset = 0
while True:
response = api_endpoint(limit=page_size, offset=offset,
**kwargs)
count = response.get(, 0)
loaded_results += respo... | Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwargs: additional arguments to pass into api callable |
359,753 | def connect_pull(self, timeout=1):
if self.cpush:
return True
if self._run_io_loop_sync:
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if self.pusher is None:
self.pusher = salt.transport.ipc.IPCMessageClient(
... | Establish a connection with the event pull socket
Default timeout is 1 s |
359,754 | def _data_format_resolver(data_format, resolver_dict):
try:
data_format = DataFormat(data_format)
except ValueError:
supported_formats = .join(
["".format(f.value) for f in DataFormat])
raise ValueError((" must be one of {formats}. Given "
".").... | Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
... |
359,755 | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
mean = (self._compute_magnitude_term(C, rup.mag) +
self._compute_distance_term(C, dists.rhypo, rup.mag))
stddevs = self._get_stddevs(C, dists.rhypo, stddev_types)
return m... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
359,756 | def density(self):
h = self.histogram.astype(np.float)
bindifs = np.array(np.diff(self.bin_edges), float)
return h / (bindifs * self.n) | Gives emprical PDF, like np.histogram(...., density=True) |
359,757 | def add_commit_variables(traj, commit):
git_time_value = time.strftime(, time.localtime(commit.committed_date))
git_short_name = str(commit.hexsha[0:7])
git_commit_name = % git_short_name
git_commit_name = + git_commit_name + git_time_value
if not traj.f_contains(+git_commit_name, shortcut... | Adds commit information to the trajectory. |
359,758 | def _get_countdown_for_next_slice(self, spec):
countdown = 0
if self._processing_limit(spec) != -1:
countdown = max(
int(parameters.config._SLICE_DURATION_SEC -
(self._time() - self._start_time)), 0)
return countdown | Get countdown for next slice's task.
When user sets processing rate, we set countdown to delay task execution.
Args:
spec: model.MapreduceSpec
Returns:
countdown in int. |
359,759 | def address(lat, lng, *, raw=False):
try:
lat, lng = wgs_to_gk4(lat, lng)
r = requests.get(
url=,
params={
: lat,
: lng,
},
)
if r.status_code == 200:
response = json.loads(r.content.decode())
... | DVB Map Address
(GET https://www.dvb.de/apps/map/address)
:param lat: Latitude
:param lng: Longitude
:param raw: Return raw response
:return: Dict of address |
359,760 | def kill(self, exit_code: Any = None):
self._force_kill.set()
if exit_code is not None:
self._exit_code = exit_code
logger.info("Killing behavior {0} with exit code: {1}".format(self, exit_code)) | Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None) |
359,761 | def start_scan(self, timeout_sec=TIMEOUT_SEC):
get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)
self._is_scanning = True | Start scanning for BLE devices. |
359,762 | def giflogo(self,id,title=None,scale=0.8,info_str=):
return giflogo(self,id,title,scale) | m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo |
359,763 | async def get_frozen(self, *args, **kwargs):
super().validate(*args, **kwargs)
if kwargs.get("message"):
kwargs = json.loads(kwargs.get("message"))
coinids = kwargs.get("coinids")
uid = kwargs.get("uid")
address = kwargs.get("address")
try:
coinid = coinid.replace("TEST", "")
except:
... | Get frozen users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
} |
359,764 | def __assert_false(returned):
result = "Pass"
if isinstance(returned, str):
try:
returned = bool(returned)
except ValueError:
raise
try:
assert (returned is False), "{0} not False".format(returned)
except Assert... | Test if an boolean is False |
359,765 | def ValidateDate(date, column_name=None, problems=None):
if IsEmpty(date) or IsValidDate(date):
return True
else:
if problems:
problems.InvalidValue(column_name, date)
return False | Validates a non-required date string value using IsValidDate():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty date string is regarded as valid! Otherwise we might end up
with many duplicate errors because of the required field checks. |
359,766 | def _validate_input_para(self, para, column_names):
lower_case_valid_class = [et.lower() for et in self.valid_class]
alt_valid_names = {
: [, , , ],
: [, , ],
: [, ],
: [],
}
for item in alt_valid_names.items():
i... | Convert the input classificaton para to the correct df column name
Parameters
----------
para : string
column_names : list of strings
Returns
-------
validated_para : string
Converted to the case used in the country file |
359,767 | def is_subdomains_enabled(blockstack_opts):
if not is_atlas_enabled(blockstack_opts):
log.debug("Subdomains are disabled")
return False
if not in blockstack_opts:
log.debug("Subdomains are disabled: no path set")
return False
return True | Can we do subdomain operations? |
359,768 | def _initialize_integrity_checkers(self, options):
if self._ase.is_encrypted:
if blobxfer.util.is_none_or_empty(
self._ase.encryption_metadata.symmetric_key):
raise RuntimeError(
(
).format(
... | Initialize file integrity checkers
:param Descriptor self: this
:param blobxfer.models.options.Upload options: upload options |
359,769 | def debug_sql(sql: str, *args: Any) -> None:
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | Writes SQL and arguments to the log. |
359,770 | def put_path(self, path):
if self.is_package(path):
logger.debug(.format(path))
self.python_paths.append(path.parent)
site.addsitedir(str(path.parent))
xbmdirs = self.get_directories_with_extensions(
path,
self.icon... | Given path identify in which environment the path belong to and
append it. |
359,771 | def show_slug_with_level(context, page, lang=None, fallback=True):
if not lang:
lang = context.get(, pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if not page:
return
return {: page.slug_with_level(lang)} | Display slug with level by language. |
359,772 | def add_option(self, opts, dest, action=None, nargs=1, const=None,
obj=None):
if obj is None:
obj = dest
opts = [normalize_opt(opt, self.ctx) for opt in opts]
option = Option(opts, dest, action=action, nargs=nargs,
const=const, obj=... | Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
``append``, ``appnd_const`` or ``count``.
The `obj` can be used to identify the option in the orde... |
359,773 | def on(self,
*qubits: raw_types.Qid) -> :
if len(qubits) != 1:
raise ValueError(
.format(qubits))
from cirq.ops.pauli_string import SingleQubitPauliStringGateOperation
return SingleQubitPauliStringGateOperation(self, qubits[0]) | Returns an application of this gate to the given qubits.
Args:
*qubits: The collection of qubits to potentially apply the gate to. |
359,774 | def _bucket_time(self, event_time):
event_time = kronos_time_to_epoch_time(event_time)
return event_time - (event_time % self._bucket_width) | The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12:00, 12:10, ... on each day. |
359,775 | def register_logger(self, logger):
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if output.is_debug():
level = logging... | Register a new logger. |
359,776 | def _transfer_data(self, remote_path, data):
if isinstance(data, dict):
data = jsonify(data)
if not isinstance(data, bytes):
data = to_bytes(data, errors=)
LOG.debug(,
remote_path, type(data), len(data))
self._connection.put_data(remote... | Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others. |
359,777 | def getquerydict(self, sep=, encoding=, errors=):
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict | Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name. |
359,778 | def on_resize(self, width, height):
width, height = self._update_perspective(width, height)
self.scene.camera.resolution = (width, height)
self.view[].resize(self.scene.camera.resolution)
self.scene.camera.transform = self.view[].pose | Handle resized windows. |
359,779 | def get_results(self, gene_list):
ADDLIST_URL = %self._organism
job_id = self.send_genes(gene_list, ADDLIST_URL)
user_list_id = job_id[]
RESULTS_URL = %self._organism
query_string =
s = retry(num=5)
filename = "%s.%s.reports" % (self._gs, self.... | Enrichr API |
359,780 | def make_datastore_query(self, cursor=None):
filters = {}
filters[] = _key_for_namespace(
self.namespace_start, self.app)
filters[] = _key_for_namespace(
self.namespace_end, self.app)
return datastore.Query(,
filters=filters,
ke... | Returns a datastore.Query that generates all namespaces in the range.
Args:
cursor: start cursor for the query.
Returns:
A datastore.Query instance that generates db.Keys for each namespace in
the NamespaceRange. |
359,781 | def trace_grpc(tracer=None):
make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL)
make_secure_channel_wrapped = wrap_make_secure_channel(
make_secure_channel_func, tracer)
setattr(
_helpers,
MAKE_SECURE_CHANNEL,
make_secure_channel_wrapped)
in... | Integrate with gRPC. |
359,782 | def abi_splitext(filename):
filename = os.path.basename(filename)
is_ncfile = False
if filename.endswith(".nc"):
is_ncfile = True
filename = filename[:-3]
known_extensions = abi_extensions()
for i in range(len(filename)-1, -1, -1):
ext = filename[i:]
... | Split the ABINIT extension from a filename.
"Extension" are found by searching in an internal database.
Returns "(root, ext)" where ext is the registered ABINIT extension
The final ".nc" is included (if any)
>>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK')
>>> assert abi_splitext("/home/guido... |
359,783 | def load(self, filename):
LOGGER.info("Loading result from .", filename)
if filename.endswith(".gz"):
with gzip.open(filename, "rb") as file_handle:
result = MemoteResult(
json.loads(file_handle.read().decode("utf-8"))
)
el... | Load a result from the given JSON file. |
359,784 | def acquire_metadata(self):
publisher = self.article.publisher
if self.collection:
pass
else:
self.pub_id = publisher.package_identifier()
self.title = publisher.package_title()
for date in publisher.package_date():
... | Handles the acquisition of metadata for both collection mode and single
mode, uses the metadata methods belonging to the article's publisher
attribute. |
359,785 | def get(self, counter):
return self._pipeline.get(name=self.data.name, counter=counter) | Gets pipeline instance object.
:param counter pipeline counter:
:return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: yagocd.resources.pipeline.PipelineInstance |
359,786 | def __execute(model, iteration_number):
iterations = model.iteration_bunch(iteration_number, False)
trends = model.build_trends(iterations)[0]
del iterations
del model
return trends | Execute a simulation model
:param model: a configured diffusion model
:param iteration_number: number of iterations
:return: computed trends |
359,787 | def in_(self, value):
newq = self.copy()
newq.setOp(Query.Op.IsIn)
if isinstance(value, orb.Collection):
newq.setValue(value)
elif not isinstance(value, (set, list, tuple)):
newq.setValue((value,))
else:
newq.setValue(tuple(value))
... | Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('test').isIn([1,2])
|>>> p... |
359,788 | def get_relationships_by_genus_type_for_source_on_date(self, source_id, relationship_genus_type, from_, to):
relationship_list = []
for relationship in self.get_relationships_by_genus_type_for_source():
if overlap(from_, to, relationship.start_date, relationship.en... | Gets a ``RelationshipList`` corresponding to the given peer ``Id`` and relationship genus ``Type`` and effective during the entire given date range inclusive but not confined to the date range.
arg: source_id (osid.id.Id): a peer ``Id``
arg: relationship_genus_type (osid.type.Type): a relationshi... |
359,789 | def write_points(self,
points,
time_precision=None,
database=None,
retention_policy=None,
tags=None,
batch_size=None,
protocol=,
consistency=None
... | Write to multiple time series names.
:param points: the list of points to be written in the database
:type points: list of dictionaries, each dictionary represents a point
:type points: (if protocol is 'json') list of dicts, where each dict
represents... |
359,790 | def follow(self, login):
resp = False
if login:
url = self._build_url(, , login)
resp = self._boolean(self._put(url), 204, 404)
return resp | Make the authenticated user follow login.
:param str login: (required), user to follow
:returns: bool |
359,791 | def _pluck_provider_state(raw_provider_state: Dict) -> ProviderState:
return ProviderState(
descriptor=raw_provider_state[],
params=raw_provider_state.get()
) | >>> _pluck_provider_state({'name': 'there is an egg'})
ProviderState(descriptor='there is an egg', params=None)
>>> _pluck_provider_state({'name': 'there is an egg called', 'params': {'name': 'humpty'}})
ProviderState(descriptor='there is an egg called', params={'name': 'humpty'}) |
359,792 | def job_details(job_id, connection=None):
if connection is None:
connection = r
data = connection.hgetall(job_key(job_id))
job_data = {: job_id, : int(connection.zscore(REDIS_KEY,
job_id))}
for key, value in data.items():
... | Returns the job data with its scheduled timestamp.
:param job_id: the ID of the job to retrieve. |
359,793 | def urls(self, key, value):
def _is_preprint(value):
return value.get(, ).lower() ==
def _is_fulltext(value):
return value[].endswith() and value[].startswith()
def _is_local_copy(value):
return in value.get(, )
def _is_ignored_domain(value):
ignored_domains = [... | Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects. |
359,794 | def add_broadcast_message(self, rawtx, message, sender_wif,
dust_limit=common.DUST_LIMIT):
tx = deserialize.tx(rawtx)
message = deserialize.unicode_str(message)
sender_key = deserialize.key(self.testnet, sender_wif)
tx = control.add_broadcast_messag... | TODO add docstring |
359,795 | def effect_associated_with_protein_coding_gene(effect):
return apply_to_gene_if_exists(
effect=effect,
fn=lambda g: g.biotype == "protein_coding",
default=False) | Parameters
----------
effect : subclass of MutationEffect
Returns True if effect is associated with a gene and that gene
has a protein_coding biotype. |
359,796 | def clipandmerge_alignment_plot (self):
keys = OrderedDict()
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : }
keys[] = { : }
config = {
: ,
: ,
: ,
: ,
: False
... | Make the HighCharts HTML to plot the duplication rates |
359,797 | def makeblastdb(self):
for sample in self.runmetadata.samples:
if sample.general.bestassemblyfile != :
db = os.path.splitext(sample[self.analysistype].baitfile)[0]
nhr = .format(db)
i... | Makes blast database files from targets as necessary |
359,798 | def compute_merkle_tree(items: Iterable[bytes]) -> MerkleTree:
if not all(isinstance(l, bytes) and len(l) == 32 for l in items):
raise ValueError()
leaves = sorted(items)
if len(leaves) == 0:
return MerkleTree(layers=[[EMPTY_MERKLE_ROOT]])
if not len(leaves) == len(set(leaves)):
... | Calculates the merkle root for a given list of items |
359,799 | def update_settings(self, integration_id, settings):
(integration, created) = self.get_or_create(integration_id=integration_id)
try:
current_settings = json.loads(integration.settings)
except ValueError:
current_settings = {}
current_settings.update(se... | Updates settings for given integration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.