Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
11,400 | def people_findByEmail(email):
method =
data = _doget(method, find_email=email)
user = User(data.rsp.user.id, username=data.rsp.user.username.text)
return user | Returns User object. |
11,401 | def _init_groups(self):
for group_id, conf in self.group_conf.items():
self.parent_input_dict[group_id] = Queue(conf.get(, 0))
self.parent_output_dict[group_id] = Queue(conf.get(, 0)) | 初始化group数据
:return: |
11,402 | def notch(self, frequency, type=, filtfilt=True, **kwargs):
zpk = filter_design.notch(frequency, self.sample_rate.value,
type=type, **kwargs)
return self.filter(*zpk, filtfilt=filtfilt) | Notch out a frequency in this `TimeSeries`.
Parameters
----------
frequency : `float`, `~astropy.units.Quantity`
frequency (default in Hertz) at which to apply the notch
type : `str`, optional
type of filter to apply, currently only 'iir' is supported
*... |
11,403 | def start(self, *_):
try:
box_configurations = self.bc_dao.run_query(QUERY_PROCESSES_FOR_BOX_ID(self.box_id))
for box_config in box_configurations:
handler = RepeatTimer(TRIGGER_INTERVAL, self.manage_process, args=[box_config.process_name])
self.... | reading box configurations and starting timers to start/monitor/kill processes |
11,404 | def isemptyfile(filepath):
exists = os.path.exists(safepath(filepath))
if exists:
filesize = os.path.getsize(safepath(filepath))
return filesize == 0
else:
return False | Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool |
11,405 | def ensure(self, connection, func, *args, **kwargs):
channel = None
while 1:
try:
if channel is None:
channel = connection.channel()
return func(channel, *args, **kwargs), channel
except (connection.connection_errors, I... | Perform an operation until success
Repeats in the face of connection errors, pursuant to retry policy. |
11,406 | def nn(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf):
self.n, self.m = np.shape(self.get_data_x())
x = np.asarray(x)
if np.shape(x)[-1] != self.m:
raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x)))
if p < 1:
... | Query the tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : integer
The number of nearest neighbors to return.
eps : nonnegative float
Return approximate nearest neighbors; ... |
11,407 | def compute_depth(self):
left_depth = self.left_node.compute_depth() if self.left_node else 0
right_depth = self.right_node.compute_depth() if self.right_node else 0
return 1 + max(left_depth, right_depth) | Recursively computes true depth of the subtree. Should only
be needed for debugging. Unless something is wrong, the
depth field should reflect the correct depth of the subtree. |
11,408 | def __geomToPointList(self, geom):
if arcpyFound and isinstance(geom, arcpy.Polyline):
feature_geom = []
fPart = []
wkt = None
wkid = None
for part in geom:
fPart = []
for pnt in part:
if geo... | converts a geometry object to a common.Geometry object |
11,409 | def load_step_specifications(self, file_name, short=False,
dataset_number=None):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
... | Load a table that contains step-type definitions.
This function loads a file containing a specification for each step or
for each (cycle_number, step_number) combinations if short==False. The
step_cycle specifications that are allowed are stored in the variable
cellreader.list_of_step_t... |
11,410 | def configure(self, cnf={}, **kw):
kw.update(cnf)
reinit = False
if in kw:
if kw[] == :
self._style_name = self._style_name.replace(, )
if not in kw:
self._tickpos =
else:
self._style_name = s... | Configure resources of the widget.
To get the list of options for this widget, call the method :meth:`~TickScale.keys`.
See :meth:`~TickScale.__init__` for a description of the widget specific option. |
11,411 | def last_valid_index(self):
def last_valid_index_builder(df):
df.index = pandas.RangeIndex(len(df.index))
return df.apply(lambda df: df.last_valid_index())
func = self._build_mapreduce_func(last_valid_index_builder)
first_result = sel... | Returns index of last non-NaN/NULL value.
Return:
Scalar of index name. |
11,412 | def open(self, verbose):
if verbose:
print( % self.port_id)
try:
self.arduino.close()
time.sleep(1)
self.arduino.open()
time.sleep(1)
return self.arduino
except Exception:
... | open the serial port using the configuration data
returns a reference to this instance |
11,413 | def get_organisations(self, service_desk_id=None, start=0, limit=50):
url_without_sd_id =
url_with_sd_id = .format(service_desk_id)
params = {}
if start is not None:
params[] = int(start)
if limit is not None:
params[] = int(limit)
if se... | Returns a list of organizations in the Jira instance. If the user is not an agent,
the resource returns a list of organizations the user is a member of.
:param service_desk_id: OPTIONAL: str Get organizations from single Service Desk
:param start: OPTIONAL: int The starting index of the returne... |
11,414 | def _build_likelihood(self):
fmean, fvar = self._build_predict(self.X, full_cov=False)
return tf.reduce_sum(self.likelihood.variational_expectations(fmean, fvar, self.Y)) | This function computes the optimal density for v, q*(v), up to a constant |
11,415 | def from_desmond(cls, path, **kwargs):
dms = DesmondDMSFile(path)
pos = kwargs.pop(, dms.getPositions())
return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path,
**kwargs) | Loads a topology from a Desmond DMS file located at `path`.
Arguments
---------
path : str
Path to a Desmond DMS file |
11,416 | def from_packages(cls, parse_context, rev=, packages=None, **kwargs):
for pkg in packages or (,):
cls.from_package(parse_context, pkg=pkg, rev=rev, **kwargs) | :param list packages: The package import paths within the remote library; by default just the
root package will be available (equivalent to passing `packages=['']`).
:param string rev: Identifies which version of the remote library to download. This could be a
commit... |
11,417 | def _should_really_index(self, instance):
if self._should_index_is_method:
is_method = inspect.ismethod(self.should_index)
try:
count_args = len(inspect.signature(self.should_index).parameters)
except AttributeError:
c... | Return True if according to should_index the object should be indexed. |
11,418 | def get_metrics(self, from_time=None, to_time=None, metrics=None,
ifs=[], storageIds=[], view=None):
params = { }
if ifs:
params[] = ifs
elif ifs is None:
params[] =
if storageIds:
params[] = storageIds
elif storageIds is None:
params[] =
return self._get_res... | This endpoint is not supported as of v6. Use the timeseries API
instead. To get all metrics for a host with the timeseries API use
the query:
'select * where hostId = $HOST_ID'.
To get specific metrics for a host use a comma-separated list of
the metric names as follows:
'select $METRIC_NAME1... |
11,419 | def interleaved_filename(file_path):
if not isinstance(file_path, tuple):
raise OneCodexException("Cannot get the interleaved filename without a tuple.")
if re.match(".*[._][Rr][12][_.].*", file_path[0]):
return re.sub("[._][Rr][12]", "", file_path[0])
else:
warnings.warn("Paire... | Return filename used to represent a set of paired-end files. Assumes Illumina-style naming
conventions where each file has _R1_ or _R2_ in its name. |
11,420 | def _which(executable, flags=os.X_OK, abspath_only=False, disallow_symlinks=False):
def _can_allow(p):
if not os.access(p, flags):
return False
if abspath_only and not os.path.abspath(p):
log.warn(, p)
return False
if disallow_symlinks and os.path.isl... | Borrowed from Twisted's :mod:twisted.python.proutils .
Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be
set to the list of file extensions for files considered executable. This
will normally include things like ".EXE". This... |
11,421 | def start_commit(self, repo_name, branch=None, parent=None, description=None):
req = proto.StartCommitRequest(parent=proto.Commit(repo=proto.Repo(name=repo_name), id=parent), branch=branch,
description=description)
res = self.stub.StartCommit(req, metadata... | Begins the process of committing data to a Repo. Once started you can
write to the Commit with PutFile and when all the data has been
written you must finish the Commit with FinishCommit. NOTE, data is
not persisted until FinishCommit is called. A Commit object is
returned.
Para... |
11,422 | def get_windzone(conn, geometry):
if geometry.geom_type in [, ]:
coords = geometry.centroid
else:
coords = geometry
sql = .format(wkt=coords.wkt)
zone = conn.execute(sql).fetchone()
if zone is not None:
zone = zone[0]
else:
zone = 0
return zone | Find windzone from map. |
11,423 | def res_block(nf, dense:bool=False, norm_type:Optional[NormType]=NormType.Batch, bottle:bool=False, **conv_kwargs):
"Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`."
norm2 = norm_type
if not dense and (norm_type==NormType.Batch): norm2 = NormType.BatchZero
nf_inner = nf//2 if bo... | Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`. |
11,424 | def get_tour_list(self):
resp = json.loads(urlopen(self.tour_list_url.format(1)).read().decode())
total_count = resp[][][]
resp = json.loads(urlopen(self.tour_list_url.format(total_count)).read().decode())
data = resp[][][][]
keychain = {
... | Inquire all tour list
:rtype: list |
11,425 | def fill_tree(self, tree, input_dict):
def add_element(item, key, value):
child_name = QtGui.QStandardItem(key)
child_name.setDragEnabled(False)
child_name.setSelectable(False)
child_name.setEditable(False)
if isinstance(value, dict):
... | fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns: |
11,426 | def from_string(cls, cl_function, dependencies=()):
return_type, function_name, parameter_list, body = split_cl_function(cl_function)
return SimpleCLFunction(return_type, function_name, parameter_list, body, dependencies=dependencies) | Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
Returns:
SimpleCLFunction: the CL data type ... |
11,427 | def setStimRisefall(self):
rf = self.ui.risefallSpnbx.value()
self.tone.setRisefall(rf) | Sets the Risefall of the StimulusModel's tone from values pulled from
this widget |
11,428 | def log_level(self, subsystem, level, **kwargs):
r
args = (subsystem, level)
return self._client.request(, args,
decoder=, **kwargs) | r"""Changes the logging output of a running daemon.
.. code-block:: python
>>> c.log_level("path", "info")
{'Message': "Changed log level of 'path' to 'info'\n"}
Parameters
----------
subsystem : str
The subsystem logging identifier (Use ``"all"`` f... |
11,429 | def process_view(self, request, view_func, view_args, view_kwargs):
profiler = getattr(request, , None)
if profiler:
try:
return profiler.runcall(
view_func, request, *view_args, **view_kwargs
)
finally:
... | Run the profiler on _view_func_. |
11,430 | def _wrapped_method_with_watch_fn(self, f, *args, **kwargs):
bound_args = signature(f).bind(*args, **kwargs)
orig_watch = bound_args.arguments.get("watch")
if orig_watch is not None:
wrapped_watch = partial(self._call_in_reactor_thread, orig_watch)
wrapped_watch... | A wrapped method with a watch function.
When this method is called, it will call the underlying method with
the same arguments, *except* that if the ``watch`` argument isn't
:data:`None`, it will be replaced with a wrapper around that watch
function, so that the watch function will be c... |
11,431 | def get_updates(self, offset=None, limit=None, timeout=20, allowed_updates=None):
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
ret = []
for ju in json_updates:
ret.append(types.Update.de_json(ju))
return ret | Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
:param allowed_updates: Array of string. List the types of updates you want your bot to receive.
:param offset: Integer. Identifier of the first update to be returned.
:param limit: Int... |
11,432 | def maybe_start_recording(tokens, index):
if tokens[index].type == TokenType.BeginRSTComment:
return _RSTCommentBlockRecorder(index, tokens[index].line)
return None | Return a new _RSTCommentBlockRecorder when its time to record. |
11,433 | def _set_lim_and_transforms(self):
LambertAxes._set_lim_and_transforms(self)
yaxis_stretch = Affine2D().scale(4 * self.horizon, 1.0)
yaxis_stretch = yaxis_stretch.translate(-self.horizon, 0.0)
yaxis_space = Affine2D().scale(1.0, 1.1... | Setup the key transforms for the axes. |
11,434 | def main(args=None):
if args is None:
args = sys.argv[1:]
parser = create_parser()
args = parser.parse_args(args)
if args.verbose >= 2:
level = logging.DEBUG
elif args.verbose >= 1:
level = logging.INFO
else:
level = logging.WARNING
logging.basicConfig... | Main command-line interface entrypoint.
Runs the given subcommand or argument that were specified. If not given a
``args`` parameter, assumes the arguments are passed on the command-line.
Args:
args (list): list of command-line arguments
Returns:
Zero on success, non-zero otherwise. |
11,435 | def disable_beacons(self):
self.opts[][] = False
evt = salt.utils.event.get_event(, opts=self.opts)
evt.fire_event({: True, : self.opts[]},
tag=)
return True | Enable beacons |
11,436 | def check(text):
err = "uncomparables.misc"
msg = "Comparison of an uncomparable: is not comparable."
comparators = [
"most",
"more",
"less",
"least",
"very",
"quite",
"largely",
"extremely",
"increasingly",
"kind of",
... | Check the text. |
11,437 | def _get_command(classes):
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), )),
)
for line in open(setup_file, ):
for cl in classes:
if cl in line:
commands[cl] = line.split()[0].strip().replace(, )
... | Associates each command class with command depending on setup.cfg |
11,438 | def groups_remove_owner(self, room_id, user_id, **kwargs):
return self.__call_api_post(, roomId=room_id, userId=user_id, kwargs=kwargs) | Removes the role of owner from a user in the current Group. |
11,439 | def _create_input_transactions(self, addy):
self._transactions.append(ProposedTransaction(
address=addy,
tag=self.tag,
value=-addy.balance,
))
for _ in range(addy.security_level - 1):
... | Creates transactions for the specified input address. |
11,440 | def update_one(self, filter_, document, **kwargs):
self._valide_update_document(document)
return self.__collect.update_one(filter_, document, **kwargs) | update method |
11,441 | def get_pret_embs(self, word_dims=None):
assert (self._pret_embeddings is not None), "No pretrained file provided."
pret_embeddings = gluonnlp.embedding.create(self._pret_embeddings[0], source=self._pret_embeddings[1])
embs = [None] * len(self._id2word)
for idx, vec in enumerate... | Read pre-trained embedding file
Parameters
----------
word_dims : int or None
vector size. Use `None` for auto-infer
Returns
-------
numpy.ndarray
T x C numpy NDArray |
11,442 | def select_limit(self, table, cols=, offset=0, limit=MAX_ROWS_PER_QUERY):
return self.fetch(self._select_limit_statement(table, cols, offset, limit)) | Run a select query with an offset and limit parameter. |
11,443 | def calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1)):
r
d = np.sqrt(6. / (np.prod(kernel) * inmaps + outmaps))
return -d, d | r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al.
.. math::
b &= \sqrt{\frac{6}{NK + M}}\\
a &= -b
Args:
inmaps (int): Map size of an input Variable, :math:`N`.
outmaps (int): Map size of an output Variable, :math:`M`.
... |
11,444 | def get_types(self):
content_types = set()
for name in self.translators:
content_types |= type_names[name]
return content_types | Retrieve a set of all recognized content types for this
translator object. |
11,445 | def coerce_value(type, value):
if isinstance(type, GraphQLNonNull):
return coerce_value(type.of_type, value)
if value is None:
return None
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, string_types) ... | Given a type and any value, return a runtime value coerced to match the type. |
11,446 | def _converged(self):
prior = self.global_prior_[0:self.prior_size]
posterior = self.global_posterior_[0:self.prior_size]
diff = prior - posterior
max_diff = np.max(np.fabs(diff))
if self.verbose:
_, mse = self._mse_converged()
diff_ratio = np.su... | Check convergence based on maximum absolute difference
Returns
-------
converged : boolean
Whether the parameter estimation converged.
max_diff : float
Maximum absolute difference between prior and posterior. |
11,447 | def getKwCtrlConf(self, kw, fmt=):
try:
confd = self.ctrlconf_dict[kw]
if fmt == :
retval = confd
else:
retval = json.dumps(confd)
except KeyError:
self.getKw(kw)
if self.confstr_epics != ... | return keyword's control configuration, followed after '!epics' notation
:param kw: keyword name
:param fmt: return format, 'raw', 'dict', 'json', default is 'dict' |
11,448 | def set_delegate(address=None, pubkey=None, secret=None):
c.DELEGATE[] = address
c.DELEGATE[] = pubkey
c.DELEGATE[] = secret | Set delegate parameters. Call set_delegate with no arguments to clear. |
11,449 | def save(self, data, xparent=None):
if xparent is not None:
elem = ElementTree.SubElement(xparent, )
else:
elem = ElementTree.Element()
for key, value in sorted(data.items()):
xitem = ElementTree.SubElement(elem, )
xitem.set(, nstr(key))
... | Parses the element from XML to Python.
:param data | <variant>
xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element> |
11,450 | def add_data(self, address, data):
while len(data):
region = self._map.get_region_for_address(address)
if region is None:
raise ValueError("no memory region defined for address 0x%08x" % address)
if not region.is_flash:
ra... | ! @brief Add a chunk of data to be programmed.
The data may cross flash memory region boundaries, as long as the regions are contiguous.
@param self
@param address Integer address for where the first byte of _data_ should be written.
@param data A list of byte values to... |
11,451 | def add_graph(self, graph):
event = event_pb2.Event(graph_def=graph.SerializeToString())
self._add_event(event, None) | Adds a `Graph` protocol buffer to the event file. |
11,452 | def tryload(self, cfgstr=None, on_error=):
cfgstr = self._rectify_cfgstr(cfgstr)
if self.enabled:
try:
if self.verbose > 1:
self.log(.format(self.fname))
return self.load(cfgstr)
except IOError:
if self.... | Like load, but returns None if the load fails due to a cache miss.
Args:
on_error (str): How to handle non-io errors errors. Either raise,
which re-raises the exception, or clear which deletes the cache
and returns None. |
11,453 | def delete_namespaced_endpoints(self, name, namespace, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_namespaced_endpoints_with_http_info(name, namespace, **kwargs)
else:
(data) = self.delete_namespaced_endpoints_with_http_info(name, namespace... | delete_namespaced_endpoints # noqa: E501
delete Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_endpoints(name, namespace, async_req=True)
>>> re... |
11,454 | def add_line(self, line, source, *lineno):
self.result.append(line, source, *lineno) | Add a line to the result |
11,455 | def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup,
dtype, index_dtype):
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
data, row, col = subword_lookup(centers)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.cs... | Create a batch for SG training objective with subwords. |
11,456 | def Nu_vertical_cylinder_Eigenson_Morgan(Pr, Gr, turbulent=None):
r
Ra = Pr*Gr
if turbulent or (Ra > 1.69E10 and turbulent is None):
return 0.148*Ra**(1/3.) - 127.6
elif 1E9 < Ra < 1.69E10 and turbulent is not False:
return 51.5 + 0.0000726*Ra**0.63
else:
return 0.48*Ra**0.25 | r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ correlated by [2]_,
presented in [3]_ and in more detail in [4]_.
.. math::
Nu_H = 0.48 Ra_H^{0.25},\; 10^{9} < Ra
Nu_H = 51.5 + 0.0000726 Ra_H^{0.63},\; 10^{9} < Ra ... |
11,457 | def from_table(table, engine, limit=None):
sql = select([table])
if limit is not None:
sql = sql.limit(limit)
result_proxy = engine.execute(sql)
return from_db_cursor(result_proxy.cursor) | Select data in a database table and put into prettytable.
Create a :class:`prettytable.PrettyTable` from :class:`sqlalchemy.Table`.
**中文文档**
将数据表中的数据放入prettytable中. |
11,458 | def _get_converter(self, convert_to=None):
t call it. We do this
so that in the case of convert, we do the conversion and return
a string. In the case of save, we save the recipe to file for the
user.
Parameters
==========
convert_to: a string ... | see convert and save. This is a helper function that returns
the proper conversion function, but doesn't call it. We do this
so that in the case of convert, we do the conversion and return
a string. In the case of save, we save the recipe to file for the
user.
P... |
11,459 | def get_object(self):
obj = super(DeleteView, self).get_object()
if not obj:
raise http.Http404
return obj | Get the object for previewing.
Raises a http404 error if the object is not found. |
11,460 | def partition(self):
step = int(math.ceil(self.num_tasks / float(self.partitions)))
if self.indices == None:
slice_ind = list(range(0, self.num_tasks, step))
for start in slice_ind:
yield self.__class__(self.partitions,
... | Partitions all tasks into groups of tasks. A group is
represented by a task_store object that indexes a sub-
set of tasks. |
11,461 | async def _connect_polling(self, url, headers, engineio_path):
if aiohttp is None:
self.logger.error(
)
return
self.base_url = self._get_engineio_url(url, engineio_path, )
self.logger.info( + self.base_url)
r = await self._... | Establish a long-polling connection to the Engine.IO server. |
11,462 | async def handle_client_ping(self, client_addr, _: Ping):
await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong()) | Handle an Ping message. Pong the client |
11,463 | def get_help_datapacks(module_name, server_prefix):
_dir = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
module_dir = "{}/../{}".format(_dir, module_name, "_help.json")
if os.path.isdir(module_dir):
module_help_path = "{}/{}".format(module_dir, "_help.json")
... | Get the help datapacks for a module
Args:
module_name (str): The module to get help data for
server_prefix (str): The command prefix for this server
Returns:
datapacks (list): The help datapacks for the module |
11,464 | def walk(self, dispatcher, node):
deferrable_handlers = {
Declare: self.declare,
Resolve: self.register_reference,
}
layout_handlers = {
PushScope: self.push_scope,
PopScope: self.pop_scope,
PushCatch: self.push_catch,
... | Walk through the node with a custom dispatcher for extraction of
details that are required. |
11,465 | def getLipdNames(D=None):
_names = []
try:
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
_names = D.keys()
except Exception:
pass
return _names | Get a list of all LiPD names in the library
| Example
| names = lipd.getLipdNames(D)
:return list f_list: File list |
11,466 | def _get_distance_scaling(self, C, mag, rhypo):
return (C["a3"] * np.log(rhypo)) + (C["a4"] + C["a5"] * mag) * rhypo | Returns the distance scalig term |
11,467 | def from_rgb(r, g=None, b=None):
c = r if isinstance(r, list) else [r, g, b]
best = {}
for index, item in enumerate(colors):
d = __distance(item, c)
if(not best or d <= best[]):
best = {: d, : index}
if in best:
return best[]
else:
return 1 | Return the nearest xterm 256 color code from rgb input. |
11,468 | def draw_address(canvas):
business_details = (
u,
u,
u,
U,
U,
U,
u,
u,
u,
u,
u,
u
)
canvas.setFont(, 9)
textobject = canvas.beginText(13 * cm, -2.5 * cm)
for line in business_details:
textobj... | Draws the business address |
11,469 | def list_objects(self, query=None, limit=-1, offset=-1):
result = []
doc = { : True}
if not query is None:
for key in query:
doc[key] = query[key]
coll = self.collection.find(doc).sort([(, pymongo.DESCENDING)])
count... | List of all objects in the database. Optinal parameter limit and
offset for pagination. A dictionary of key,value-pairs can be given as
addictional query condition for document properties.
Parameters
----------
query : Dictionary
Filter objects by property-value pair... |
11,470 | def get_info(pyfile):
info = {}
info_re = re.compile(r"^__(\w+)__ = [\"]")
with open(pyfile, ) as f:
for line in f.readlines():
match = info_re.search(line)
if match:
info[match.group(1)] = match.group(2)
return info | Retrieve dunder values from a pyfile |
11,471 | def render_html(root, options=0, extensions=None):
if extensions is None:
extensions = _cmark.ffi.NULL
raw_result = _cmark.lib.cmark_render_html(
root, options, extensions)
return _cmark.ffi.string(raw_result).decode() | Render a given syntax tree as HTML.
Args:
root (Any): The reference to the root node of the syntax tree.
options (int): The cmark options.
extensions (Any): The reference to the syntax extensions, generally
from :func:`parser_get_syntax_extensions`
Returns:
... |
11,472 | def view(self, rec):
kwd = {
: ,
}
self.render(,
postinfo=rec,
kwd=kwd,
author=rec.user_name,
format_date=tools.format_date,
userinfo=self.userinfo,
cfg=C... | View the page. |
11,473 | def set_env_info(self, env_state=None, env_id=None, episode_id=None, bump_past=None, fps=None):
with self.cv:
if env_id is None:
env_id = self._env_id
if env_state is None:
env_state = self._env_state
if fps is None:
fp... | Atomically set the environment state tracking variables. |
11,474 | def __build_config_block(self, config_block_node):
node_lists = []
for line_node in config_block_node:
if isinstance(line_node, pegnode.ConfigLine):
node_lists.append(self.__build_config(line_node))
elif isinstance(line_node, pegnode.OptionLine):
... | parse `config_block` in each section
Args:
config_block_node (TreeNode): Description
Returns:
[line_node1, line_node2, ...] |
11,475 | def save(self, items):
rows = []
indx = self.indx
size = 0
tick = s_common.now()
for item in items:
byts = s_msgpack.en(item)
size += len(byts)
lkey = s_common.int64en(indx)
indx += 1
rows.append((lkey, by... | Save a series of items to a sequence.
Args:
items (tuple): The series of items to save into the sequence.
Returns:
The index of the first item |
11,476 | def get_mesh_dict(self):
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
retdict = {: self._mesh.qpoints,
: self._mesh.weights,
: self._mesh.frequencies,
: self._mesh.eigenvectors... | Returns calculated mesh sampling phonons
Returns
-------
dict
keys: qpoints, weights, frequencies, eigenvectors, and
group_velocities
Each value for the corresponding key is explained as below.
qpoints: ndarray
q-points in ... |
11,477 | def logsumexp(arr, axis=0):
if axis == 0:
pass
elif axis == 1:
arr = arr.T
else:
raise NotImplementedError
vmax = arr.max(axis=0)
out = da.log(da.sum(da.exp(arr - vmax), axis=0))
out += vmax
return out | Computes the sum of arr assuming arr is in the log domain.
Returns log(sum(exp(arr))) while minimizing the possibility of
over/underflow.
Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import logsumexp
>>> a = np.arange(10)
>>> np.log(np.sum(np.exp(a)))
9.458... |
11,478 | def execute(self, input_data):
raw_bytes = input_data[][]
self.meta[] = hashlib.md5(raw_bytes).hexdigest()
self.meta[] = input_data[][]
self.meta[] = input_data[][]
with magic.Magic() as mag:
self.meta[] = mag.id_buffer(raw_bytes[:1024])
with magic.Ma... | This worker computes meta data for any file type. |
11,479 | def start_session_if_none(self):
if not (self._screen_id and self._session):
self.update_screen_id()
self._session = YouTubeSession(screen_id=self._screen_id) | Starts a session it is not yet initialized. |
11,480 | def s3_write(self, log, remote_log_location, append=True):
if append and self.s3_log_exists(remote_log_location):
old_log = self.s3_read(remote_log_location)
log = .join([old_log, log]) if old_log else log
try:
self.hook.load_string(
log,
... | Writes the log to the remote_log_location. Fails silently if no hook
was created.
:param log: the log to write to the remote_log_location
:type log: str
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path)
:param append: i... |
11,481 | def recommend_delete(self, num_iid, session):
request = TOPRequest()
request[] = num_iid
self.create(self.execute(request, session)[])
return self | taobao.item.recommend.delete 取消橱窗推荐一个商品
取消当前用户指定商品的橱窗推荐状态 这个Item所属卖家从传入的session中获取,需要session绑定 |
11,482 | def config(name=, default=):
conf = {}
s = env(name, default)
if s:
conf = parse_email_url(s)
return conf | Returns a dictionary with EMAIL_* settings from EMAIL_URL. |
11,483 | def from_char(
cls, char, name=None, width=None, fill_char=None,
bounce=False, reverse=False, back_char=None, wrapper=None):
return cls(
cls._generate_move(
char,
width=width or cls.default_width,
fill_char=str(fill_cha... | Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty space (`fill_char`).
Arguments:
char : Character to move across the bar.
name : Name for the new ... |
11,484 | def _wkt(eivals, timescales, normalization, normalized_laplacian):
nv = eivals.shape[0]
wkt = np.zeros(timescales.shape)
for idx, t in enumerate(timescales):
wkt[idx] = np.sum(np.exp(-1j * t * eivals))
if isinstance(normalization, np.ndarray):
return hkt / normalization
if norma... | Computes wave kernel trace from given eigenvalues, timescales, and normalization.
For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published at KDD'18.
Parameters
----------
eivals : numpy.ndarray
... |
11,485 | def normalize_locale(loc):
comps = split_locale(loc)
comps[] = comps[].upper()
comps[] = comps[].lower().replace(, )
comps[] =
return join_locale(comps) | Format a locale specifier according to the format returned by `locale -a`. |
11,486 | def _GetStatus(self):
if self._parser_mediator:
number_of_produced_events = (
self._parser_mediator.number_of_produced_events)
number_of_produced_sources = (
self._parser_mediator.number_of_produced_event_sources)
number_of_produced_warnings = (
self._parser_medi... | Retrieves status information.
Returns:
dict[str, object]: status attributes, indexed by name. |
11,487 | def _spectrogram(y=None, S=None, n_fft=2048, hop_length=512, power=1,
win_length=None, window=, center=True, pad_mode=):
if S is not None:
n_fft = 2 * (S.shape[0] - 1)
else:
S = np.abs(stft(y, n_fft=n_fft, hop_length=hop_length,
wi... | Helper function to retrieve a magnitude spectrogram.
This is primarily used in feature extraction functions that can operate on
either audio time-series or spectrogram input.
Parameters
----------
y : None or np.ndarray [ndim=1]
If provided, an audio time series
S : None or np.ndarra... |
11,488 | def checkKey(self, credentials):
filename = self._keyfile
if not os.path.exists(filename):
return 0
lines = open(filename).xreadlines()
for l in lines:
l2 = l.split()
if len(l2) < 2:
continue
try:
if... | Retrieve the keys of the user specified by the credentials, and check
if one matches the blob in the credentials. |
11,489 | def perp(weights):
r
w = _np.asarray(weights) / _np.sum(weights)
w = _np.ma.MaskedArray(w, copy=False, mask=(w == 0))
entr = - _np.sum( w * _np.log(w.filled(1.0)))
return _np.exp(entr) / len(w) | r"""Calculate the normalized perplexity :math:`\mathcal{P}` of samples
with ``weights`` :math:`\omega_i`. :math:`\mathcal{P}=0` is
terrible and :math:`\mathcal{P}=1` is perfect.
.. math::
\mathcal{P} = exp(H) / N
where
.. math::
H = - \sum_{i=1}^N \bar{\omega}_i log ~ \bar{\omeg... |
11,490 | def print_splits(cliques, next_cliques):
splits = 0
for i, clique in enumerate(cliques):
parent, _ = clique
if parent in next_cliques:
if len(next_cliques[parent]) > 1:
print_split(i + splits, len(cliques) + splits)
splits +... | Print shifts for new forks. |
11,491 | def read_ipx(self, length):
if length is None:
length = len(self)
_csum = self._read_fileng(2)
_tlen = self._read_unpack(2)
_ctrl = self._read_unpack(1)
_type = self._read_unpack(1)
_dsta = self._read_ipx_address()
_srca = self._read_ipx_addr... | Read Internetwork Packet Exchange.
Structure of IPX header [RFC 1132]:
Octets Bits Name Description
0 0 ipx.cksum Checksum
2 16 ipx.len Packet Length (header includes)
4... |
11,492 | def maintenance_center(self, storage_disk_xml=None):
disk_in_maintenance = 0
for filer_disk in storage_disk_xml:
disk_status = filer_disk.find()
if disk_status.text == :
disk_in_maintenance += 1
self.push(, , disk_in_maintenance) | Collector for how many disk(s) are in NetApp maintenance center
For more information on maintenance center please see:
bit.ly/19G4ptr |
11,493 | def build_template(
initial_template=None,
image_list=None,
iterations = 3,
gradient_step = 0.2,
**kwargs ):
wt = 1.0 / len( image_list )
if initial_template is None:
initial_template = image_list[ 0 ] * 0
for i in range( len( image_list ) ):
initial_template... | Estimate an optimal template from an input image_list
ANTsR function: N/A
Arguments
---------
initial_template : ANTsImage
initialization for the template building
image_list : ANTsImages
images from which to estimate template
iterations : integer
number of template b... |
11,494 | def create_server_app(provider, password=None, cache=True, cache_timeout=3600,
debug=False):
app = Flask(__name__, static_folder=None)
app.debug = debug
if cache:
if type(cache) == bool:
cache = SimpleCache()
else:
p... | Create a DAAP server, based around a Flask application. The server requires
a content provider, server name and optionally, a password. The content
provider should return raw object data.
Object responses can be cached. This may dramatically speed up connections
for multiple clients. However, this is o... |
11,495 | def drive_rotational_speed_rpm(self):
drv_rot_speed_rpm = set()
for member in self._drives_list():
if member.rotation_speed_rpm is not None:
drv_rot_speed_rpm.add(member.rotation_speed_rpm)
return drv_rot_speed_rpm | Gets set of rotational speed of the disks |
11,496 | def start(self):
self._lc = LoopingCall(self._download)
self._lc.start(30, now=True) | Start the background process. |
11,497 | def sanity(request, sysmeta_pyxb):
_does_not_contain_replica_sections(sysmeta_pyxb)
_is_not_archived(sysmeta_pyxb)
_obsoleted_by_not_specified(sysmeta_pyxb)
if in request.META:
return
_has_correct_file_size(request, sysmeta_pyxb)
_is_supported_checksum_algorithm(sysmeta_pyxb)
_... | Check that sysmeta_pyxb is suitable for creating a new object and matches the
uploaded sciobj bytes. |
11,498 | def _specialKeyEvent(key, upDown):
assert upDown in (, ), "upDown argument must be or "
key_code = special_key_translate_table[key]
ev = AppKit.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
Quartz.NSSystemDefined,
(0,0... | Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac |
11,499 | def run(self):
from pyrocore import config
try:
config.engine.open()
items = []
self.run_filter(items)
except (error.LoggableError, xmlrpc.ERRORS) as exc:
self.LOG.warn(str(exc)) | Filter job callback. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.