Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
359,300 | def crs(self):
if self._crs is None:
self._populate_from_rasterio_object(read_image=False)
return self._crs | Raster crs. |
359,301 | def add_predicate(self, predicate):
_predicate = predicate
if isinstance(predicate, partial):
_predicate = % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS[]:
hookenv.log( % (self.id(), _predicate), level=hookenv.DEBUG)
self._predicates... | Add a new predicate callback to this handler. |
359,302 | def Authenticate(self, app_id, challenge_data,
print_callback=sys.stderr.write):
try:
device = u2f.GetLocalU2FInterface(origin=self.origin)
except errors.NoDeviceFoundError:
print_callback()
six.moves.input()
device = u2f.GetLocalU2FInterface(origin=self.orig... | See base class. |
359,303 | def resolve_doc(cls, manifest, target_doc_name, target_doc_package,
current_project, node_package):
if target_doc_package is not None:
return manifest.find_docs_by_name(target_doc_name,
target_doc_package)
candidate_... | Resolve the given documentation. This follows the same algorithm as
resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled. |
359,304 | def PSWAP(angle, q1, q2):
return Gate(name="PSWAP", params=[angle], qubits=[unpack_qubit(q) for q in (q1, q2)]) | Produces a parameterized SWAP gate::
PSWAP(phi) = [[1, 0, 0, 0],
[0, 0, exp(1j * phi), 0],
[0, exp(1j * phi), 0, 0],
[0, 0, 0, 1]]
:param angle: The angle of the phase... |
359,305 | def __parse_arguments(self, *args):
params = self.parser.parse_args(args)
uuid = params.uuid
kw = {}
if params.name:
kw[] = params.name
if params.email:
kw[] = params.email
if params.gender:
kw[] = params.gender
if ... | Parse command line arguments |
359,306 | def put(self, path, payload=None, headers=None):
return self._request(, path, payload, headers) | HTTP PUT operation.
:param path: URI Path
:param payload: HTTP Body
:param headers: HTTP Headers
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:return: Response |
359,307 | def write(self, string):
string = string.rstrip()
if string:
self.logger.critical(string) | Erase newline from a string and write to the logger. |
359,308 | def client(self, name):
for client in self.clients():
if client and client.title == name:
return client
raise NotFound( % name) | Returns the :class:`~plexapi.client.PlexClient` that matches the specified name.
Parameters:
name (str): Name of the client to return.
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown client name |
359,309 | def compile_create(self, blueprint, command, _):
columns = ", ".join(self._get_columns(blueprint))
return "CREATE TABLE %s (%s)" % (self.wrap_table(blueprint), columns) | Compile a create table command. |
359,310 | def add(places, name, cmd, args, env=None, uid=None, gid=None, extras=None,
env_inherit=None):
args = [cmd]+args
config = filepath.FilePath(places.config)
fle = config.child(name)
details = dict(args=args)
if env is not None:
newEnv = {}
for thing in env:
nam... | Add a process.
:param places: a Places instance
:param name: string, the logical name of the process
:param cmd: string, executable
:param args: list of strings, command-line arguments
:param env: dictionary mapping strings to strings
(will be environment in subprocess)
:param uid: int... |
359,311 | def on_separate_dimensions(self):
if np.any([isinstance(k.active_dims, slice) for k in self.kernels]):
return False
else:
dimlist = [k.active_dims for k in self.kernels]
overlapping = False
for i, dims_i in enumerate(dimlist):
... | Checks whether the kernels in the combination act on disjoint subsets
of dimensions. Currently, it is hard to asses whether two slice objects
will overlap, so this will always return False.
:return: Boolean indicator. |
359,312 | def __init(self):
params = {
"f" : "json",
}
json_dict = self._get(self._url, params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy... | initializes the service |
359,313 | def update_firmware(self, file_url, component_type):
fw_update_uri = self._get_firmware_update_service_resource()
action_data = {
: ,
: file_url,
}
LOG.debug(self._(), file_url)
status, headers, response = self._rest_post(
fw... | Updates the given firmware on the server for the given component.
:param file_url: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of c... |
359,314 | async def handle_jobs(job_handler, host, port, *, loop):
try:
try:
reader, writer = await asyncio.open_connection(host, port, loop=loop)
except OSError:
logging.error("worker could not connect to server")
return
while True:
try:
... | Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted. |
359,315 | def delete_snapshot(self, snapshot_id):
query = self.query_factory(
action="DeleteSnapshot", creds=self.creds, endpoint=self.endpoint,
other_params={"SnapshotId": snapshot_id})
d = query.submit()
return d.addCallback(self.parser.truth_return) | Remove a previously created snapshot. |
359,316 | def get_vmpolicy_macaddr_input_last_rcvd_instance(self, **kwargs):
config = ET.Element("config")
get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr")
config = get_vmpolicy_macaddr
input = ET.SubElement(get_vmpolicy_macaddr, "input")
last_rcvd_instance = ET.SubElemen... | Auto Generated Code |
359,317 | def _check_zone(self, name, create=False):
.
self.log.debug(, name)
try:
if name in self._azure_zones:
return name
self._dns_client.zones.get(self._resource_group, name)
self._azure_zones.add(name)
return name
except CloudEr... | Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zo... |
359,318 | def find_nested_meta_first(d, prop_name, version):
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = + prop_name
return d.get(p) | Returns obj. for badgerfish and val for hbf. Appropriate for nested literals |
359,319 | def strip_qos_cntrl(self, idx, prot_type):
qos_cntrl, = struct.unpack(, self._packet[idx:idx + 2])
qos_cntrl_bits = format(qos_cntrl, )[::-1]
qos_pri = qos_cntrl & 0x000f
qos_bit = int(qos_cntrl_bits[5])
qos_ack = int(qos_cntrl_bits[6:8], 2)
amsdupresent = 0
... | strip(2 byte) wlan.qos
:idx: int
:prot_type: string
802.11 protocol type(.11ac, .11a, .11n, etc)
:return: int
number of processed bytes
:return: int
qos priority
:return: int
qos bit
:return: int
qos acknowledgem... |
359,320 | def Robbins(L, G, rhol, rhog, mul, H=1.0, Fpd=24.0):
rs displayed equation has a typo in a superscript.
This model is based on the example in Perry
L = L*737.33812
G = G*737.33812
rhol = rhol*0.062427961
rhog = rhog*0.062427961
mul = mul*1000.0
C3 = 7.4E-8
C4 = 2.7E-5
... | r'''Calculates pressure drop across a packed column, using the Robbins
equation.
Pressure drop is given by:
.. math::
\Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4
.. math::
G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5}
.. math:... |
359,321 | def locale(self):
name = self.json_data[]
if name is None:
name = "Undefined"
return (int(self.json_data[][name]), name) | Do a lookup for the locale code that is set for this layout.
NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0
@return: Tuple (<USB HID locale code>, <name>) |
359,322 | def mro_resolve(name, bases, dict):
if name in dict:
return dict[name]
for base in bases:
if hasattr(base, name):
return getattr(base, name)
try:
return mro_resolve(name, base.__bases__, {})
except KeyError:
pass
raise KeyError(name) | Given a tuple of baseclasses and a dictionary that takes precedence
over any value in the bases, finds a value with the specified *name*
and returns it. Raises #KeyError if the value can not be found. |
359,323 | def DumpDirHashToStringIO(directory, stringio, base=, exclude=None, include=None):
/
import fnmatch
import os
files = [(os.path.join(directory, i), i) for i in os.listdir(directory)]
files = [i for i in files if os.path.isfile(i[0])]
for fullname, filename in files:
if include is not No... | Helper to iterate over the files in a directory putting those in the passed StringIO in ini
format.
:param unicode directory:
The directory for which the hash should be done.
:param StringIO stringio:
The string to which the dump should be put.
:param unicode base:
If provided... |
359,324 | def getTemplates(self, workitems, template_folder=None,
template_names=None, keep=False, encoding="UTF-8"):
if (not workitems or isinstance(workitems, six.string_types) or
isinstance(workitems, int) or
isinstance(workitems, float) or
... | Get templates from a group of to-be-copied :class:`Workitems` and
write them to files named after the names in `template_names`
respectively.
:param workitems: a :class:`list`/:class:`tuple`/:class:`set`
contains the ids (integer or equivalent string) of some
to-be-copie... |
359,325 | def restore(self, url, tags=None):
args = {
: url,
}
return JSONResponse(self._client.raw(, args, tags=tags)) | Full restore of a container backup. This restore method will recreate
an exact copy of the backedup container (including same network setup, and other
configurations as defined by the `create` method.
To just restore the container data, and use new configuration, use the create method instead
... |
359,326 | def group_by_allele(self, locus):
locus = to_locus(locus)
read_to_allele = None
loci = []
if locus.positions:
for position in locus.positions:
base_position = Locus.from_interbase_coordinates(
locus.contig, position)
... | Split the PileupCollection by the alleles suggested by the reads at the
specified locus.
If a read has an insertion immediately following the locus, then the
insertion is included in the allele. For example, if locus is the
1-base range [5,6), one allele might be "AGA", indicating that ... |
359,327 | def package_info(cls, package):
if package not in cls.package_info_cache:
package_json_url = % package
try:
logging.getLogger().setLevel(logging.WARN)
response = requests.get(package_json_url)
response.raise_for_status()
... | All package info for given package |
359,328 | def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
def decorator(callback):
self.register_edited_channel_post_handler(callback, *custom_filters, commands=commands, ... | Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:par... |
359,329 | def _FlushExportBuffer(self, output_module, deduplicate_events=True):
last_macb_group_identifier = None
last_content_identifier = None
macb_group = []
generator = self._export_event_heap.PopEvents()
for macb_group_identifier, content_identifier, event in generator:
if deduplicate_events... | Flushes buffered events and writes them to the output module.
Args:
output_module (OutputModule): output module.
deduplicate_events (Optional[bool]): True if events should be
deduplicated. |
359,330 | def init_discrete_hmm_spectral(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None,
eps_A=None, eps_B=None, separate=None):
nfull = C_full.shape[0]
if eps_A is None:
eps_A = 0.01 / nstates
if eps_B is None:
eps_B = 0.0... | Initializes discrete HMM using spectral clustering of observation counts
Initializes HMM as described in [1]_. First estimates a Markov state model
on the given observations, then uses PCCA+ to coarse-grain the transition
matrix [2]_ which initializes the HMM transition matrix. The HMM output
probabili... |
359,331 | def hset(self, hashroot, key, value):
hroot = self.root / hashroot
if not hroot.is_dir():
hroot.mkdir()
hfile = hroot / gethashfile(key)
d = self.get(hfile, {})
d.update( {key : value})
self[hfile] = d | hashed set |
359,332 | def _security_auth_headers(self, username, password, headers):
userColonPassword = username + ":" + password
b64UserColonPassword = base64. \
b64encode(str_to_bytes(userColonPassword)).decode("ascii")
headers[] = % b64UserColonPassword | Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:type dict |
359,333 | def unwrap(self, value, session=None):
self.validate_unwrap(value)
value = self.item_type.unwrap(value, session=session)
for val in self.values:
if val == value:
return val
self._fail_validation(value, ) | Unwrap value using the unwrap function from ``EnumField.item_type``.
Since unwrap validation could not happen in is_valid_wrap, it
happens in this function. |
359,334 | def write_file(writer, filename):
for line in txt_line_iterator(filename):
writer.write(line)
writer.write("\n") | Write all of lines from file using the writer. |
359,335 | def get_deadline_metadata(self):
metadata = dict(self._mdata[])
metadata.update({: self._my_map[]})
return Metadata(**metadata) | Gets the metadata for the assessment deadline.
return: (osid.Metadata) - metadata for the end time
*compliance: mandatory -- This method must be implemented.* |
359,336 | def scalarDecorator(func):
@wraps(func)
def scalar_wrapper(*args,**kwargs):
if nu.array(args[0]).shape == ():
scalarOut= True
newargs= ()
for ii in range(len(args)):
newargs= newargs+(nu.array([args[ii]]),)
args= newargs
else:
... | Decorator to return scalar outputs as a set |
359,337 | def generate_dataset_shelve(filename, number_items=1000):
if os.path.exists(filename):
os.remove(filename)
data = shelve.open(filename)
names = get_names()
totalnames = len(names)
random.seed()
for i in range(number_items):
data[str(i+1)] = {"name":names[random.ra... | Generate a dataset with number_items elements. |
359,338 | def entropy_from_samples(samples, vec):
samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32)
samples_uniform = samples[:, NUM_CLASS:]
cat, uniform = get_distributions(vec[:, :NUM_CLASS], vec[:, NUM_CLASS:])
def neg_logprob(dist, sample, name):
nll = -dist.log_prob(... | Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. |
359,339 | def status(config):
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
accounts.setdefault(a, {})[region] = last
p... | time series lastest record time by account. |
359,340 | def unit(self, expression, default=None):
expression = _ensure_string_from_expression(expression)
try:
unit_or_quantity = eval(expression, expression_namespace, scopes.UnitScope(self))
unit = unit_or_quantity.unit if hasattr(unit_or_quantity, "unit") else un... | Returns the unit (an astropy.unit.Units object) for the expression.
Example
>>> import vaex
>>> ds = vaex.example()
>>> df.unit("x")
Unit("kpc")
>>> df.unit("x*L")
Unit("km kpc2 / s")
:param expression: Expression, which can be a column name
:p... |
359,341 | def send_group_text(self, sender, receiver, content):
return self.send_text(sender, , receiver, content) | 发送群聊文本消息
:param sender: 发送人
:param receiver: 会话 ID
:param content: 消息内容
:return: 返回的 JSON 数据包 |
359,342 | def _report_disabled_command_usage(self, *args, message_to_print: str, **kwargs) -> None:
self.decolorized_write(sys.stderr, "{}\n".format(message_to_print)) | Report when a disabled command has been run or had help called on it
:param args: not used
:param message_to_print: the message reporting that the command is disabled
:param kwargs: not used |
359,343 | def unlist(ctx, unlist_account, account):
account = Account(account, blockchain_instance=ctx.blockchain)
print_tx(account.nolist(unlist_account)) | Remove an account from any list |
359,344 | def generator(
worker_id,
sleep=lambda x: time.sleep(x/1000.0),
now=lambda: int(time.time()*1000)):
assert worker_id >= 0 and worker_id <= max_worker_id
last_timestamp = -1
sequence = 0
while True:
timestamp = now()
if last_timestamp > timestamp:
... | worker_id: a unique for your *entire* environment number between 0 and 255
to identify this generator.
sleep(n): function to pause this worker for n milliseconds. you usually
want to supply a custom method for this in asynchronous
processes.
now(): function to... |
359,345 | def bind(self, source, dest, destmeth):
self.connect(source, getattr(dest, destmeth)) | Guild compatible version of :py:meth:`connect`.
This allows Pyctools compound components to be used in `Guild
<https://github.com/sparkslabs/guild>`_ pipelines. |
359,346 | def revoke(self):
self.client.post(self.client.get_url("/kv/lease/revoke"),
json={"ID": self.id})
return True | LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: |
359,347 | def gmap(google_api_key, map_options, **kwargs):
return GMap(api_key=google_api_key, map_options=map_options, **kwargs) | Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-key
map_options: (GMapOptions)
Config... |
359,348 | def _assemble_complex(stmt):
member_strs = [_assemble_agent_str(m) for m in stmt.members]
stmt_str = member_strs[0] + + _join_list(member_strs[1:])
return _make_sentence(stmt_str) | Assemble Complex statements into text. |
359,349 | def process_user(self, user: types.User):
if not user:
return
yield , user.id
if self.include_content:
yield , user.full_name
if user.username:
yield , f"@{user.username}" | Generate user data
:param user:
:return: |
359,350 | def create_asset_model(self, project, releasetype):
rootdata = treemodel.ListItemData([])
rootitem = treemodel.TreeItem(rootdata)
for atype in project.atype_set.all():
atypedata = djitemdata.AtypeItemData(atype)
atypeitem = treemodel.TreeItem(atypedata, rootitem)... | Create and return a new tree model that represents assets til descriptors
The tree will include assettypes, assets, tasks and descriptors of the given releaetype.
:param releasetype: the releasetype for the model
:type releasetype: :data:`djadapter.RELEASETYPES`
:param project: the pro... |
359,351 | def wrap_iter_with_message_events(
request_or_response_iter,
span,
message_event_type
):
for message_id, message in enumerate(request_or_response_iter, start=1):
add_message_event(
proto_message=message,
span=span,
message_event_type=message_event_type,
... | Wraps a request or response iterator to add message events to the span
for each proto message sent or received |
359,352 | def use_federated_vault_view(self):
self._vault_view = FEDERATED
for session in self._get_provider_sessions():
try:
session.use_federated_vault_view()
except AttributeError:
pass | Pass through to provider AuthorizationLookupSession.use_federated_vault_view |
359,353 | def is_abstract(self) -> bool:
meta_value = getattr(self.clsdict.get(), , False)
return self.clsdict.get(ABSTRACT_ATTR, meta_value) is True | Whether or not the class-under-construction was declared as abstract (**NOTE:**
this property is usable even *before* the :class:`MetaOptionsFactory` has run) |
359,354 | def remove(self, force=False):
return self.client.api.remove_plugin(self.name, force=force) | Remove the plugin from the server.
Args:
force (bool): Remove even if the plugin is enabled.
Default: False
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. |
359,355 | def evaluate_at_x(self, arg, def_val=0):
y = np.interp(arg, self.x, self.y, left=def_val, right=def_val)
return y | Returns Y value at arg of self. Arg can be a scalar,
but also might be np.array or other iterable
(like list). If domain of self is not wide enough to
interpolate the value of Y, method will return
def_val for those arguments instead.
Check the interpolation when arg in domain o... |
359,356 | def get_data(self, name):
r
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._db[name]["data"] | r"""
Get the data associated with a node.
:param name: Node name
:type name: :ref:`NodeName`
:rtype: any type or list of objects of any type
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree) |
359,357 | def _add_conversion(self, plugin, pbt):
assert self.shape == pbt.shape
assert len(self.inserts) == len(pbt.inserts)
for (i, o) in zip(self.inserts, pbt.inserts):
assert i.shape == o.shape
assert i.kind == o.kind
assert i.unevaluated == o.unevaluated
... | Add a new PluginBlockType conversion.
If the plugin already exists, do nothing. |
359,358 | def clean(self, settings):
return {k: v for k, v in settings.items() if k in DEFAULT_SETTINGS} | Filter given settings to keep only key names available in
``DEFAULT_SETTINGS``.
Args:
settings (dict): Loaded settings.
Returns:
dict: Settings object filtered. |
359,359 | def get_image(self):
posts_with_images = self.post_set.filter(image__gt=)
if posts_with_images:
return posts_with_images[0].image | Gets first image from post set. |
359,360 | def body_encode(body, maxlinelen=76, eol=NL):
if maxlinelen < 4:
raise ValueError("maxlinelen must be at least 4")
if not body:
return body
last_has_eol = (body[-1] in )
encoded_body = _body_accumulator(maxlinelen, eol)
lines = body.splitlines()
last_line_no = ... | Encode with quoted-printable, wrapping at maxlinelen characters.
Each line of encoded text will end with eol, which defaults to "\\n". Set
this to "\\r\\n" if you will be using the result of this function directly
in an email.
Each line will be wrapped at, at most, maxlinelen characters before the
... |
359,361 | def set(self, key, value):
value_encoded = encode(value, self.get_change_trigger(key))
if key in self.data and self.data[key] == value_encoded:
return self
self.data[key] = value_encoded
return self.trigger_changed(key) | Set a value at key and return a Future.
:rtype: tornado.concurrent.Future |
359,362 | def get_currency(currency_str):
path =
filepath = pkg_resources.resource_filename(, path)
with open(filepath, ) as fp:
reader = csv.reader(fp, delimiter=, quotechar=)
next(reader, None)
for row in reader:
is_currency = currency_str in [row[0], row[1], row[2]]
... | Convert an identifier for a currency into a currency object.
Parameters
----------
currency_str : str
Returns
-------
currency : Currency |
359,363 | def set_default(self, channels=None):
if not channels:
channels = self._ch_cal.keys()
for channel in channels:
self.set_voltage(channel, self._ch_cal[channel][], unit=) | Setting default voltage |
359,364 | def resize(self, size, interp=):
color_im_resized = self.color.resize(size, interp)
depth_im_resized = self.depth.resize(size, interp)
return RgbdImage.from_color_and_depth(
color_im_resized, depth_im_resized) | Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-si... |
359,365 | def get_cluster_custom_object_status(self, group, version, plural, name, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_cluster_custom_object_status_with_http_info(group, version, plural, name, **kwargs)
else:
(data) = self.get_cluster_custom_obj... | get_cluster_custom_object_status # noqa: E501
read status of the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_cluster_custom_object_sta... |
359,366 | def list_groups(self, filtr, url_prefix, auth, session, send_opts):
req = self.get_group_request(
, , url_prefix, auth)
if filtr is not None:
if not filtr == and not filtr == :
raise RuntimeError(
)
req.params = {: filtr}
... | Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (string|None): ['member'|'maintainer'] or defaults to None.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send ... |
359,367 | def url_decode(s, charset=, decode_keys=False, include_empty=True,
errors=, separator=, cls=None):
if cls is None:
cls = MultiDict
return cls(_url_decode_impl(str(s).split(separator), charset, decode_keys,
include_empty, errors)) | Parse a querystring and return it as :class:`MultiDict`. Per default
only values are decoded into unicode strings. If `decode_keys` is set to
`True` the same will happen for keys.
Per default a missing value for a key will default to an empty key. If
you don't want that behavior you can set `include... |
359,368 | def _names_to_bytes(names):
names = sorted(names)
names_bytes = json.dumps(names).encode()
return names_bytes | Reproducibly converts an iterable of strings to bytes
:param iter[str] names: An iterable of strings
:rtype: bytes |
359,369 | def request(
self, method, url, timeout=None,
headers=None, data=None, params=None
):
if headers is None:
headers = {}
if not self.session:
self._browser_init()
try:
response = self.session.request(
method,... | Make a request using the requests library
:param method: Which http method to use (GET/POST)
:type method: str | unicode
:param url: Url to make request to
:type url: str | unicode
:param timeout: Timeout for request (default: None)
None -> infinite timeout
:... |
359,370 | def get_value_length(byte):
length_value = byte & length_type_mask
return LengthTypes.to_ints.get(length_value, byte & length_mask) | Length of the value, in bytes (value can be 8/16/24/custom bits)
:param byte:
:return: |
359,371 | def get_header(self, key):
key = canonicalize_header(key)
if key in self.header:
return self.header[key]
return | Returns the requested header, or an empty string if the header is not set.
Keyword arguments:
key -- The header name. It will be canonicalized before use. |
359,372 | def proxied_attribute(local_attr, proxied_attr, doc):
def fget(self):
return getattr(getattr(self, local_attr), proxied_attr)
def fset(self, value):
setattr(getattr(self, local_attr), proxied_attr, value)
def fdel(self):
delattr(getattr(self, local_attr), proxied_attr)
retur... | Create a property that proxies attribute ``proxied_attr`` through
the local attribute ``local_attr``. |
359,373 | def get_build_artefacts(config):
def aux(ctx, service_name, service):
compiler, environment = get_compiler(config, service)
new_service, service_barts = compiler.getBuildArtefacts(environment, ctx, service)
ctx = ctx + [service_name]
for child_name, child in compiler.children(s... | Create all required build artefacts, modify config to refer to them. |
359,374 | def create_all(self, checkfirst: bool = True) -> None:
self.base.metadata.create_all(bind=self.engine, checkfirst=checkfirst) | Create the PyBEL cache's database and tables.
:param checkfirst: Check if the database exists before trying to re-make it |
359,375 | def security():
sessions = SessionActivity.query_by_user(
user_id=current_user.get_id()
).all()
master_session = None
for index, session in enumerate(sessions):
if SessionActivity.is_current(session.sid_s):
master_session = session
del sessions[index]
ret... | View for security page. |
359,376 | def copy_object(self, container, obj, new_container, new_obj_name=None,
content_type=None, extra_info=None):
return self._manager.copy_object(container, obj, new_container,
new_obj_name=new_obj_name, content_type=content_type) | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
You can optionally change the content_type of the object by supplying
that in the 'content_type' parameter.
The 'extra_info' parameter is includ... |
359,377 | def configure_uploads(app, upload_sets):
if isinstance(upload_sets, UploadSet):
upload_sets = (upload_sets,)
if not hasattr(app, ):
app.upload_set_config = {}
set_config = app.upload_set_config
defaults = dict(dest=app.config.get(),
url=app.config.get())
fo... | Call this after the app has been configured. It will go through all the
upload sets, get their configuration, and store the configuration on the
app. It will also register the uploads module if it hasn't been set. This
can be called multiple times with different upload sets.
.. versionchanged:: 0.1.3
... |
359,378 | def get_day_of_month(datestring):
get_day = re.compile(r"\d{1,2}(st|nd|rd|th)?", re.IGNORECASE)
day = get_day.search(datestring)
the_day = None
if day:
if bool(re.search(r"[st|nd|rd|th]", day.group().lower())):
the_day = day.group()[:-2]
else:
the_day = day.... | Transforms an ordinal number into plain number with padding zero.
E.g. 3rd -> 03, or 12th -> 12
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails |
359,379 | def sort_values(self, return_indexer=False, ascending=True):
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
if return_indexer:
return sorted_index, _as
else:
return sorted_index | Return a sorted copy of the index.
Return a sorted copy of the index, and optionally return the indices
that sorted the index itself.
Parameters
----------
return_indexer : bool, default False
Should the indices that would sort the index be returned.
ascendi... |
359,380 | def cached_workflow_property(func=None, attr=None, setter=True):
def wrapper(func):
_attr = attr or "_workflow_cached_" + func.__name__
@functools.wraps(func)
def getter(self):
wf = self.as_workflow()
if not hasattr(wf, _attr):
setattr(wf, _attr,... | Decorator to declare an attribute that is stored only on a workflow and also cached for
subsequent calls. Therefore, the decorated method is expected to (lazily) provide the value to
cache. The resulting value is stored as ``_workflow_cached_<func.__name__>`` on the workflow,
which can be overwritten by set... |
359,381 | def is_android(filename):
if not filename:
return None
with open(filename, "rb") as fd:
f_bytes = fd.read()
return is_android_raw(f_bytes)
return None | Return the type of the file
@param filename : the filename
@rtype : "APK", "DEX", None |
359,382 | def defrise(space, nellipses=8, alternating=False, min_pt=None, max_pt=None):
ellipses = defrise_ellipses(space.ndim, nellipses=nellipses,
alternating=alternating)
return ellipsoid_phantom(space, ellipses, min_pt, max_pt) | Phantom with regularily spaced ellipses.
This phantom is often used to verify cone-beam algorithms.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created, must be 2- or
3-dimensional.
nellipses : int, optional
Number of ellipses. If more el... |
359,383 | def rank_genes_groups(
adata,
groupby,
use_raw=True,
groups: Union[str, Iterable[str]] = ,
reference=,
n_genes=100,
rankby_abs=False,
key_added=None,
copy=False,
method=,
corr_method=,
log_transformed=True,
**kwds
):
if in kwds:
rankby_abs = not kwds... | Rank genes for characterizing groups.
Parameters
----------
adata : :class:`~anndata.AnnData`
Annotated data matrix.
groupby : `str`
The key of the observations grouping to consider.
use_raw : `bool`, optional (default: `True`)
Use `raw` attribute of `adata` if present.
... |
359,384 | def _add_standard_attributes(cls):
setattr(
cls.context.new_class,
cls.context.new_meta[],
cls.context.state_value)
setattr(
cls.context.new_class,
cls.context.state_name,
utils.state_property)
setattr(cls.context.... | Add attributes common to all state machines.
These are methods for setting and checking state etc. |
359,385 | def does_not_contain(self, element):
self._run(unittest_case.assertNotIn, (element, self._subject))
return ChainInspector(self._subject) | Ensures :attr:`subject` does not contain *element*. |
359,386 | def _get_text(self, text):
tokens = text.get_tokens()
for i, token in enumerate(tokens):
if len(token) > 1:
char = chr(self._char_code)
substitute = self._substitutes.setdefault(token, char)
if substitute == char:
s... | Returns the text content of `text`, with all multi-character tokens
replaced with a single character. Substitutions are recorded
in self._substitutes.
:param text: text to get content from
:type text: `Text`
:rtype: `str` |
359,387 | def mac_str_to_bytes(mac_str):
08:00:27:13:69:77080027136977
if len(mac_str) == 12:
pass
elif len(mac_str) == 17:
sep = mac_str[2]
mac_str = mac_str.replace(sep, )
else:
raise ValueError()
chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2))
return bytes(cha... | Convert a MAC address string into bytes. Works with or without separators:
b1 = mac_str_to_bytes('08:00:27:13:69:77')
b2 = mac_str_to_bytes('080027136977')
assert b1 == b2
assert isinstance(b1, bytes) |
359,388 | def set_power_configuration(policy=None, delayType=None, delayValue=None):
**
query = ""
if policy == "reset":
query =
if delayType:
if delayType == "fixed":
query +=
if delayValue:
query += .format(delayValue)
el... | Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server... |
359,389 | def remove_instance(self, item):
self.instances.remove(item)
self.remove_item(item) | Remove `instance` from model |
359,390 | def SetModel( self, model, adapter=None ):
self.model = model
if adapter is not None:
self.adapter = adapter
self.UpdateDrawing() | Set our model object (root of the tree) |
359,391 | def load_ext(self):
try:
super().load_ext()
except BaseException:
if hydpy.pub.options.warnmissingsimfile:
warnings.warn(str(sys.exc_info()[1])) | Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
The method's "special handling" is to convert errors to warnings.
We explain the reasons in the documentation on method |Obs.load_ext|
of class |Obs|, from which we ... |
359,392 | def configure(self, listener):
listener.capture([
lambda msg: flavor(msg) == ,
{: self._chat_origin_included}
])
listener.capture([
lambda msg: flavor(msg) == ,
{: self._inline_origin_included}
]) | Configure a :class:`.Listener` to capture callback query |
359,393 | def search(self, query: Optional[dict] = None, offset: Optional[int] = None,
limit: Optional[int] = None,
order_by: Union[None, list, tuple] = None) -> Sequence[]:
raise NotImplementedError | return search result based on specified rulez query |
359,394 | def _find_dependent_modules(self, module):
dms = set()
for um in inspect.getmembers(module, inspect.ismodule):
dms.add(um[1])
for uc in inspect.getmembers(module, inspect.isclass):
self._add_obj_module(dms, uc[1])
for ur in inspect.getmembers(module, ins... | Return the set of dependent modules for used modules,
classes and routines. |
359,395 | def add(self, model):
def foo(m, p, i):
if m[i][0].name == model.name:
raise ValueError("Model already exists")
return
self.foreach(foo)
self.append((model,))
return | raises an exception if the model cannot be added |
359,396 | def __parse_addr(self, addr):
from email.utils import parseaddr
value = parseaddr(addr)
return value[0], value[1] | Parse email addresses |
359,397 | def add_job(self, func, *args):
job = func, args
reply = self.run_job(job)
self.send(reply) | Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol.
The async version of this method will send the repl... |
359,398 | def getDailyMenu(self, restaurant_id):
params = {"res_id": restaurant_id}
daily_menu = self.api.get("/dailymenu", params)
return daily_menu | :param restaurant_id: id of restaurant whose details are requested
:return: json response
Get daily menu using Zomato restaurant ID. |
359,399 | def convertDict2Attrs(self, *args, **kwargs):
for n,c in enumerate(self.attrs):
try:
params = self.params
except AttributeError as aerr:
params = {}
kwargs.update(params)
try:
group = self.mambu... | The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Group object for each one, initializing them
one at a time, and changing the attrs attribute (which just
holds a list of plain dictionaries) with a MambuGr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.