Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,400 | def tag(filepath, loudness, peak, *,
album_loudness=None, album_peak=None, opus_output_gain=False, mtime_second_offset=None):
assert((loudness is not None) or (album_loudness is not None))
if peak is not None:
assert(0 <= peak <= 1.0)
if album_peak is not None:
assert(0 <= album_peak <= 1.... | Tag audio file with loudness metadata. |
342,401 | def consume_faces(self, collected_faces = None):
Vertex = namedtuple(, )
def emit_vertex(vertex):
for v in vertex.uv:
yield v
for v in vertex.color:
yield v
for v in vertex.normal:
yield... | Consume all consecutive faces
If more than three vertices are specified, we triangulate by the following procedure:
Let the face have n vertices in the order v_1 v_2 v_3 ... v_n, n >= 3.
We emit the first face as usual: (v_1, v_2, v_3). For each remaining vertex v_j,
j > 3,... |
342,402 | def get_decoder(encoding, *args, **kwargs):
def _get_decoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except ImportError:
from pyamf import amf0
return amf0.Decoder
elif encoding == AMF3:
try:
... | Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}. |
342,403 | def add_wf(self,wf_obj):
if self.text_layer is None:
self.text_layer = Ctext(type=self.type)
self.root.append(self.text_layer.get_node())
self.text_layer.add_wf(wf_obj) | Adds a token to the text layer
@type wf_obj: L{Cwf}
@param wf_obj: the token object |
342,404 | def delete(self, space, key, **kwargs) -> _MethodRet:
return self._db.delete(space, key, **kwargs) | Delete request coroutine.
Examples:
.. code-block:: pycon
# Assuming tuple [0, 'hello'] is in space tester
>>> await conn.delete('tester', [0])
<Response sync=3 rowcount=1 data=[
<TarantoolTuple id=0 name='hello'>
... |
342,405 | def policy_list(request, **kwargs):
policies = neutronclient(request).list_qos_policies(
**kwargs).get()
return [QoSPolicy(p) for p in policies] | List of QoS Policies. |
342,406 | def _set_rsvp_authentication(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=rsvp_authentication.rsvp_authentication, is_container=, presence=False, yang_name="rsvp-authentication", rest_name="authentication", parent=self, path_helper=self._path_helpe... | Setter method for rsvp_authentication, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/rsvp_authentication (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_rsvp_authentication is considered as a private
method. Backends look... |
342,407 | def init_realms(self, realms):
self.realms = tuple(realm for realm in realms
if isinstance(realm, realm_abcs.AuthenticatingRealm))
self.register_cache_clear_listener()
self.token_realm_resolver = self.init_token_resolution()
self.init_locking() | :type realms: Tuple |
342,408 | def fit_doublegauss_samples(samples,**kwargs):
sorted_samples = np.sort(samples)
N = len(samples)
med = sorted_samples[N/2]
siglo = med - sorted_samples[int(0.16*N)]
sighi = sorted_samples[int(0.84*N)] - med
return fit_doublegauss(med,siglo,sighi,median=True,**kwargs) | Fits a two-sided Gaussian to a set of samples.
Calculates 0.16, 0.5, and 0.84 quantiles and passes these to
`fit_doublegauss` for fitting.
Parameters
----------
samples : array-like
Samples to which to fit the Gaussian.
kwargs
Keyword arguments passed to `fit_doublegauss`. |
342,409 | def touvw(self, v):
if is_measure(v) and v[] == :
m = _measures.uvw(self, v)
m[] = dq.quantity(m[])
m[] = dq.quantity(m[])
return m
else:
raise TypeError() | Calculates a uvw measure from a baseline. The baseline can consist
of a vector of actual baseline positions. Note that the baseline does
not have to be a proper baseline, but can be a series of positions
(to call positions baselines see :meth:`asbaseline` ) for speed
reasons: operations... |
342,410 | def generated_targets (self, sources, prop_set, project, name):
if __debug__:
from .targets import ProjectTarget
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
assert isinstance(prop_set, property_set.PropertySet)
assert isinstance(projec... | Constructs targets that are created after consuming 'sources'.
The result will be the list of virtual-target, which the same length
as 'target_types' attribute and with corresponding types.
When 'name' is empty, all source targets must have the same value of
the 'name' a... |
342,411 | def get_errvar_dataframe(self, singular_values=None):
if singular_values is None:
singular_values = \
np.arange(0, min(self.pst.nnz_obs, self.pst.npar_adj) + 1)
if not isinstance(singular_values, list) and \
not isinstance(singular_values, np.ndarray)... | get a pandas dataframe of error variance results indexed
on singular value and (prediction name,<errvar term>)
Parameters
----------
singular_values : list
singular values to test. defaults to
range(0,min(nnz_obs,nadj_par) + 1)
Returns
-----... |
342,412 | def search(self, query):
url = self.url + "/" + query
log.debug("GitHub query: {0}".format(url))
try:
request = urllib2.Request(url, headers=self.headers)
response = urllib2.urlopen(request)
log.debug("Response headers:\n{0}".format(
u... | Perform GitHub query |
342,413 | def __getiterable(value):
if isinstance(value, Selection):
return [value]
try:
for selection in value:
if not isinstance(selection, Selection):
raise TypeError
return list(value)
except TypeError:
rai... | Try to convert the given argument to a |list| of |Selection|
objects and return it. |
342,414 | def show_sbridges(self):
grp = self.getPseudoBondGroup("Salt Bridges-%i" % self.tid, associateWith=[self.model])
grp.lineWidth = 3
grp.lineType = self.chimera.Dash
for i, sbridge in enumerate(self.plcomplex.saltbridges):
m = self.model
r = m.new... | Visualizes salt bridges. |
342,415 | def tabify(text, options):
opts = parse_options(options)
if opts.tab_size < 1:
return text
else:
tab_equiv = * opts.tab_size
return text.replace(tab_equiv, ) | tabify(text : str, options : argparse.Namespace|str) -> str
>>> tabify(' (println "hello world")', '--tab=3')
'\t\t (println "hello world")'
Replace spaces with tabs |
342,416 | def __complete_refers(self, value: str) -> Iterable[str]:
return map(
lambda entry: f"{entry[0].name}",
filter(
Namespace.__completion_matcher(value), [(s, v) for s, v in self.refers]
),
) | Return an iterable of possible completions matching the given
prefix from the list of referred Vars. |
342,417 | def paths_to_polygons(paths, scale=None):
polygons = [None] * len(paths)
for i, path in enumerate(paths):
if len(path) < 4:
continue
try:
polygons[i] = repair_invalid(Polygon(path), scale)
except ValueError:
... | Given a sequence of connected points turn them into
valid shapely Polygon objects.
Parameters
-----------
paths : (n,) sequence
Of (m,2) float, closed paths
scale: float
Approximate scale of drawing for precision
Returns
-----------
polys: (p,) list
shapely.geom... |
342,418 | def images(self):
try:
images = [image for image in self._safe_get_element(
)]
except TypeError:
images = []
return images | List of images for a response.
When using lookup with RespnoseGroup 'Images', you'll get a
list of images. Parse them so they are returned in an easily
used list format.
:return:
A list of `ObjectifiedElement` images |
342,419 | def task_dropped(self):
tracker = self.task().tracker_storage()
if tracker is not None and self.track_drop() is True:
details = self.task().event_details(WTrackerEvents.drop)
tracker.register_drop(self.task(), event_details=details)
WScheduleRecord.task_dropped(self) | Track (if required) drop event and do the same job as :meth:`.WScheduleRecord.task_dropped`
method do
:return: None |
342,420 | def _verify_page(self):
title_date = self._get_date_in_title().lower()
split_date = self.date.lower().split()
split_date[0] = split_date[0][:3]
return all(term in title_date for term in split_date) | Verify the ratings page matches the correct date |
342,421 | def set_attributes(d, elm):
for key in d:
elm.setAttribute(key, d[key]) | Set attributes from dictionary of values. |
342,422 | def public_broadcaster():
while __websocket_server_running__:
pipein = open(PUBLIC_PIPE, )
line = pipein.readline().replace(, ).replace(, )
if line != :
WebSocketHandler.broadcast(line)
print line
remaining_lines = pipein.read()
... | Thread which runs in parallel and constantly checks for new messages
in the public pipe and broadcasts them publicly to all connected clients. |
342,423 | def _disable_autopx(self):
if self._autopx:
self.shell.run_cell = self._original_run_cell
self._autopx = False
print "%autopx disabled" | Disable %autopx by restoring the original InteractiveShell.run_cell. |
342,424 | def add_block_hash( self, block_hash ):
if len(self.block_hashes) > 2000:
raise Exception("A getheaders request cannot have over 2000 block hashes")
hash_num = int("0x" + block_hash, 16)
bh = BlockHash()
bh.block_hash = hash_num
self.block_hashes.a... | Append up to 2000 block hashes for which to get headers. |
342,425 | def _init_modules_stub(self, **_):
from google.appengine.api import request_info
all_versions = {}
def_versions = {}
m2h = {}
for module in self.configuration.modules:
module_name = module._module_name or
module_version = module._v... | Initializes the modules stub based off of your current yaml files
Implements solution from
http://stackoverflow.com/questions/28166558/invalidmoduleerror-when-using-testbed-to-unit-test-google-app-engine |
342,426 | def _add(self, shard_uri, name):
return self.router_command("addShard", (shard_uri, {"name": name}), is_eval=False) | execute addShard command |
342,427 | def string_matches_sans_whitespace(self, str1, str2_fuzzy_whitespace):
str2_fuzzy_whitespace = re.sub(, , str2_fuzzy_whitespace)
return re.search(str2_fuzzy_whitespace, str1) is not None | Check if two strings match, modulo their whitespace. |
342,428 | def calloc(self, sim_nmemb, sim_size):
raise NotImplementedError("%s not implemented for %s" % (self.calloc.__func__.__name__,
self.__class__.__name__)) | A somewhat faithful implementation of libc `calloc`.
:param sim_nmemb: the number of elements to allocated
:param sim_size: the size of each element (in bytes)
:returns: the address of the allocation, or a NULL pointer if the allocation failed |
342,429 | def _attach_to_model(self, model):
super(RelatedFieldMixin, self)._attach_to_model(model)
if model.abstract:
relation = (self._model._name, self.name, self.related_name)
self.database._relations[self.related_to].append(relation) | When we have a model, save the relation in the database, to later create
RelatedCollection objects in the related model |
342,430 | def expose(rule, **options):
def decorator(f):
if not hasattr(f, "urls"):
f.urls = []
if isinstance(rule, (list, tuple)):
f.urls.extend(rule)
else:
f.urls.append((rule, options))
return f
return decorator | Decorator to add an url rule to a function |
342,431 | def k_array_rank_jit(a):
k = len(a)
idx = a[0]
for i in range(1, k):
idx += comb_jit(a[i], i+1)
return idx | Numba jit version of `k_array_rank`.
Notes
-----
An incorrect value will be returned without warning or error if
overflow occurs during the computation. It is the user's
responsibility to ensure that the rank of the input array fits
within the range of possible values of `np.intp`; a sufficient... |
342,432 | def eratosthene(n):
P = [True] * n
answ = [2]
for i in range(3, n, 2):
if P[i]:
answ.append(i)
for j in range(2 * i, n, i):
P[j] = False
return answ | Prime numbers by sieve of Eratosthene
:param n: positive integer
:assumes: n > 2
:returns: list of prime numbers <n
:complexity: O(n loglog n) |
342,433 | def _get_optional_args(args, opts, err_on_missing=False, **kwargs):
parsed = {}
for arg in args:
try:
parsed[arg] = getattr(opts, arg)
except AttributeError as e:
if err_on_missing:
raise AttributeError(e)
... | Convenience function to retrieve arguments from an argparse
namespace.
Parameters
----------
args : list of str
List of arguments to retreive.
opts : argparse.namespace
Namespace to retreive arguments for.
err_on_missing : bool, optional
... |
342,434 | def _define_csbi():
if _WindowsCSBI.CSBI is not None:
return
class COORD(ctypes.Structure):
_fields_ = [(, ctypes.c_short), (, ctypes.c_short)]
class SmallRECT(ctypes.Structure):
_fields_ = [(, ctypes.c_short), (, ctypes.c_... | Defines structs and populates _WindowsCSBI.CSBI. |
342,435 | def get_struct_type(self, name):
p = ffi.lib.LLVMPY_GetNamedStructType(self, _encode_string(name))
if not p:
raise NameError(name)
return TypeRef(p) | Get a TypeRef pointing to a structure type named *name*.
NameError is raised if the struct type isn't found. |
342,436 | async def vafter(self):
self.logger.debug("Finished playing a song")
if self.state != :
self.logger.debug("Returning because player is in state {}".format(self.state))
return
self.pause_time = None
if self.vclient_task:
loop = asyncio.get_ev... | Function that is called after a song finishes playing |
342,437 | def _wait_on_instance(self, state, timeout=600, wait_period=10):
current_state =
start = time.time()
end = start + timeout
while time.time() < end:
current_state = self._get_instance_state()
if state.lower() == current_state.lower():
re... | Wait until instance is in given state. |
342,438 | def logical_xor(f1, f2):
def f_xor(arr):
return np.logical_xor(f1(arr), f2(arr))
f_xor.__name__ = f1.__name__ + "_xor_" + f2.__name__
return f_xor | Logical xor from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function |
342,439 | def ChiSquared(k: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Double(context.jvm_view().ChiSquaredVertex, label, cast_to_integer_vertex(k)) | One to one constructor for mapping some shape of k to
a matching shaped ChiSquared.
:param k: the number of degrees of freedom |
342,440 | def fix_colocation_after_import(input_map, absolute_import_scope):
attr_map = _build_colocation_attr_map(input_map, absolute_import_scope)
_apply_colocation_attr_map(attr_map, absolute_import_scope) | Fixes colocation attributes after import according to input_map.
This function is meant to be called after importing a GraphDef, in order
to rewrite colocate_with constrains analogous to how inputs to ops
are rewritten by input_map during import. It also updates devices accordingly.
The nodes in the given imp... |
342,441 | def remove_response_property(xml_root):
if xml_root.tag == "testsuites":
properties = xml_root.find("properties")
resp_properties = []
for prop in properties:
prop_name = prop.get("name", "")
if "polarion-response-" in prop_name:
resp_properties.a... | Removes response properties if exist. |
342,442 | def _is_better_match(x, y, matched_a, matched_b, attributes_dict_a, attributes_dict_b):
attributes_x = attributes_dict_a[x]
attributes_y = attributes_dict_b[y]
if x in matched_a:
attributes_match = attributes_dict_b[matched_a[x]]
if _euclidean_dist(attributes_x, attributes_y) >= _euclid... | :param x: The first element of a possible match.
:param y: The second element of a possible match.
:param matched_a: The current matches for the first set.
:param matched_b: The current matches for the second set.
:param attributes_dict_a: The at... |
342,443 | def _map_seqprop_resnums_to_structprop_chain_index(self, resnums, seqprop=None, structprop=None, chain_id=None,
use_representatives=False):
resnums = ssbio.utils.force_list(resnums)
if use_representatives:
seqprop = self.repres... | Map a residue number in any SeqProp to the mapping index in the StructProp + chain ID. This does not provide
a mapping to residue number, only a mapping to the index which then can be mapped to the structure resnum!
Args:
resnums (int, list): Residue numbers in the sequence
seqp... |
342,444 | def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs):
header = {
u"Content-Type": u"application/json",
u"User-Agent": u"salesking_api_py_v1",
}
if headers:
headers.update(header)
else:
headers = header
... | hook for manipulating the _pre request data |
342,445 | def send_margin_order(self, acc_id, amount, symbol, _type, price=0, _async=False):
params = {
: acc_id,
: amount,
: symbol,
: _type,
:
}
if price:
params[] = price
path =
return api_key_post(para... | 创建并执行借贷订单
:param amount:
:param symbol:
:param _type: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param price:
:return: |
342,446 | def sort_state(self, best_hyp_indices: mx.nd.NDArray):
self.states = [mx.nd.take(ds, best_hyp_indices) for ds in self.states] | Sorts states according to k-best order from last step in beam search. |
342,447 | def search(self, query, **kwargs):
response = self._new_response()
if self._check_supported_op(, response):
if not in query:
response.status =
response.error_type =
msg =
response.error_message = msg
els... | Cruddy provides a limited but useful interface to search GSI indexes in
DynamoDB with the following limitations (hopefully some of these will
be expanded or eliminated in the future.
* The GSI must be configured with a only HASH and not a RANGE.
* The only operation supported in the que... |
342,448 | def is_valid(self):
return len(self.ref) == 1 and \
len(self.alt) == 1 and \
len(self.alt[0]) == 1 | Only retain SNPs or single indels, and are bi-allelic |
342,449 | def get_members(self, group_id):
self._valid_group_id(group_id)
url = "{}/group/{}/member".format(self.API, group_id)
data = self._get_resource(url)
members = []
for datum in data.get("data"):
members.append(self._group_member_from_json(datum))
ret... | Returns a list of restclients.GroupMember objects for the group
identified by the passed group ID. |
342,450 | def declare_type(self, declared_type):
if declared_type not in self.collected_types:
self.collected_types[declared_type.name] = declared_type
return declared_type | Add this type to our collection, if needed. |
342,451 | def get_text(self):
self._load_raw_content()
if self._text is None:
assert self._raw_content is not None
ret_cont = self._raw_content
if self.compressed:
ret_cont = zlib.decompress(ret_cont, zlib.MAX_WBITS+16)
if self.encoded:
... | Get the loaded, decompressed, and decoded text of this content. |
342,452 | def _get_distance_scaling_term(self, C, mag, rrup):
return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"]) | Returns the distance scaling parameter |
342,453 | def getModel(self,name):
if name in self.modelobjcache:
return self.modelobjcache[name]
return self.loadModel(name) | Gets the model object by the given name.
If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache. |
342,454 | def _validate_claim_request(claims, ignore_errors=False):
results = {}
claims = claims if claims else {}
for name, value in claims.iteritems():
if value is None:
results[name] = None
elif isinstance(value, dict):
results[name] = _validate_claim_values(name, val... | Validates a claim request section (`userinfo` or `id_token`) according
to section 5.5 of the OpenID Connect specification:
- http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
Returns a copy of the claim request with only the valid fields and values.
Raises ValueError is the claim r... |
342,455 | def nla_for_each_attr(head, len_, rem):
pos = head
rem.value = len_
while nla_ok(pos, rem):
yield pos
pos = nla_next(pos, rem) | Iterate over a stream of attributes.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/attr.h#L262
Positional arguments:
head -- first nlattr with more in its bytearray payload (nlattr class instance).
len_ -- length of attribute stream (integer).
rem -- initialized to len, holds b... |
342,456 | def edges(self, edges):
res = copy.copy(self)
res._edges = edges
return res | Specify edge list data and associated edge attribute values.
:param edges: Edges and their attributes.
:type point_size: Pandas dataframe, NetworkX graph, or IGraph graph.
:returns: Plotter.
:rtype: Plotter.
**Example**
::
import graphistry
... |
342,457 | def _filter_and_bucket_subtokens(subtoken_counts, min_count):
subtoken_buckets = []
for subtoken, count in six.iteritems(subtoken_counts):
if count < min_count:
continue
while len(subtoken_buckets) <= len(subtoken):
subtoken_buckets.append(set())
subtoken_buckets[len(subtoken)].add(s... | Return a bucketed list of subtokens that are filtered by count.
Args:
subtoken_counts: defaultdict mapping subtokens to their counts
min_count: int count used to filter subtokens
Returns:
List of subtoken sets, where subtokens in set i have the same length=i. |
342,458 | def _fill_vao(self):
with self.vao:
self.vbos = []
for loc, verts in enumerate(self.arrays):
vbo = VBO(verts)
self.vbos.append(vbo)
self.vao.assign_vertex_attrib_location(vbo, loc) | Put array location in VAO for shader in same order as arrays given to Mesh. |
342,459 | def login(request, user):
session_auth_hash =
if user is None:
user = request.user
if hasattr(user, ):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
session_key = request.session[SESSION_KEY]
if session_key != user.pk or (
... | Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in. |
342,460 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.name is not None:
_dict[] = self.name
if hasattr(self, ) and self.classifier_id is not None:
_dict[] = self.classifier_id
if hasattr(self, ) and self.classes is not None:
_dict[] = [x.... | Return a json dictionary representing this model. |
342,461 | def folderitem(self, obj, item, index):
obj = api.get_object(obj)
uid = api.get_uid(obj)
url = api.get_url(obj)
title = api.get_title(obj)
if self.show_categories_enabled():
category = obj.getCategoryTitle()
if category not in s... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current i... |
342,462 | def flipsign(U):
midx = abs(U).argmax(axis=0)
for i in range(U.shape[1]):
if U[midx[i], i] < 0:
U[:, i] = -U[:, i]
return U | Flip sign of factor matrices such that largest magnitude
element will be positive |
342,463 | def _set_error_handler_callbacks(self, app):
@app.errorhandler(NoAuthorizationError)
def handle_no_auth_error(e):
return self._unauthorized_callback(str(e))
@app.errorhandler(InvalidHeaderError)
def handle_invalid_header_error(e):
return self._invalid_to... | Sets the error handler callbacks used by this extension |
342,464 | def fetch(self):
params = values.of({})
payload = self._version.fetch(
,
self._uri,
params=params,
)
return AssetVersionInstance(
self._version,
payload,
service_sid=self._solution[],
asset_sid... | Fetch a AssetVersionInstance
:returns: Fetched AssetVersionInstance
:rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance |
342,465 | def getEntity(self, id=None, uri=None, match=None):
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not uri.startswith("http://"):
match = uri
uri = None
... | get a generic entity with given ID or via other methods... |
342,466 | def get_octahedra(self, atoms, periodicity=3):
octahedra = []
for n, i in enumerate(atoms):
found = []
if i.symbol in Perovskite_Structure.B:
for m, j in enumerate(self.virtual_atoms):
if j.symbol in Perovskite_Structure.C and self.vir... | Extract octahedra as lists of sequence numbers of corner atoms |
342,467 | def process_mavlink(slave):
try:
buf = slave.recv()
except socket.error:
return
try:
global mavversion
if slave.first_byte and mavversion is None:
slave.auto_mavlink_version(buf)
msgs = slave.mav.parse_buffer(buf)
except mavutil.mavlink.MAVError a... | process packets from MAVLink slaves, forwarding to the master |
342,468 | def holds(snapshot, **kwargs):
*
flags = []
target = []
if kwargs.get(, False):
flags.append()
target.append(snapshot)
res = __salt__[](
__utils__[](
command=,
flags=flags,
target=target,
),
python_sh... | Lists all existing user references for the given snapshot or snapshots.
snapshot : string
name of snapshot
recursive : boolean
lists the holds that are set on the named descendent snapshots also.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' zfs.h... |
342,469 | def convert(input_format, output_format, b64_data):
assert input_format in INPUT_FORMATS, "Unsupported input format!"
assert output_format in OUTPUT_FORMATS, "Unsupported output format!"
with NTFile(mode="wb", suffix="." + input_format, dir="/tmp") as ifile:
ofilename = ifile.name + "." +... | Convert `b64_data` fron `input_format` to `output_format`.
Args:
input_format (str): Specification of input format (pdf/epub/whatever),
see :attr:`INPUT_FORMATS` for list.
output_format (str): Specification of output format (pdf/epub/..),
s... |
342,470 | def read_line(csv_contents, options, prop_indices, mol):
status_field = options.status_field
active_label = options.active_label
decoy_label = options.decoy_label
active_value_matcher = re.compile(active_label)
decoy_value_matcher = re.compile(decoy_label)
status_label_inde... | read csv line |
342,471 | def rawq_getchar(self):
if not self.rawq:
self.fill_rawq()
if self.eof:
raise EOFError
c = self.rawq[self.irawq]
if not py2:
c = c.to_bytes((c.bit_length()+7)//8, )
self.irawq += 1
if self.irawq >= len(self.r... | Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed. |
342,472 | def get_client_settings_env(**_):
return {
: os.environ.get(),
: os.environ.get(),
: os.environ.get(),
} | Retrieve client settings from environment settings.
:param \\*\\*kwargs: Arguments that are passed into the client instance |
342,473 | def readline(self, continuation=False):
prompt = (self.secondary_prompt_string if continuation else
self.primary_prompt_string)
try:
line = raw_input(prompt)
while line.endswith("\\"):
line = line[:-1] + raw_input(self.secondary_prompt_s... | Read a line from the terminal.
A backslash followed by a <newline> is interpreted as a line
continuation. The backslash and <newline>s are removed before return.
For example::
$ uname \
> -m
x86_64
:param continuation:
True if the line ... |
342,474 | def _append_theme_dir(self, name):
path = "[{}]".format(get_file_directory() + "/" + name)
self.tk.call("lappend", "auto_path", path) | Append a theme dir to the Tk interpreter auto_path |
342,475 | def set_contrast_levels(self, contrast_level=None):
if contrast_level is None:
clevel = self.contrast_panel.choice.GetStringSelection()
if clevel == :
contrast_level = 0
else:
contrast_level = float(clevel)
conf = self.panel.c... | enhance contrast levels, or use full data range
according to value of self.panel.conf.contrast_level |
342,476 | def header_without_lines(header, remove):
remove = set(remove)
lines = []
for line in header.lines:
if hasattr(line, "mapping"):
if (line.key, line.mapping.get("ID", None)) in remove:
continue
else:
if (line.key, line.value) in remove:
... | Return :py:class:`Header` without lines given in ``remove``
``remove`` is an iterable of pairs ``key``/``ID`` with the VCF header key
and ``ID`` of entry to remove. In the case that a line does not have
a ``mapping`` entry, you can give the full value to remove.
.. code-block:: python
# head... |
342,477 | def run_expect_command(self, cmd, expect_end=None, timeout=3, wait_seconds=2):
shell = self.ssh_session.invoke_shell()
last_time = int(time.time())
if not cmd.endswith():
cmd +=
def receive():
buff =
if expect_end is None:
... | 执行 shell 命令并获取返回结果
:param timeout:
:param wait_seconds:
:param cmd:
:param expect_end:
:return: |
342,478 | def list_(bank, cachedir=None):
if cachedir is None:
cachedir = __opts__[]
try:
cache = salt.cache.Cache(__opts__, cachedir=cachedir)
except TypeError:
cache = salt.cache.Cache(__opts__)
return cache.list(bank) | Lists entries stored in the specified bank.
CLI Example:
.. code-block:: bash
salt-run cache.list cloud/active/ec2/myec2 cachedir=/var/cache/salt/ |
342,479 | def buy_streak_freeze(self):
lang = self.get_abbreviation_of(self.get_user_info()[])
if lang is None:
raise Exception()
try:
self.buy_item(, lang)
return True
except AlreadyHaveStoreItemException:
return False | figure out the users current learning language
use this one as parameter for the shop |
342,480 | def load_source_vocabs(folder: str) -> List[Vocab]:
return [vocab_from_json(os.path.join(folder, fname)) for fname in
sorted([f for f in os.listdir(folder) if f.startswith(C.VOCAB_SRC_PREFIX)])] | Loads source vocabularies from folder. The first element in the list is the primary source vocabulary.
Other elements correspond to optional additional source factor vocabularies found in folder.
:param folder: Source folder.
:return: List of vocabularies. |
342,481 | def build(cls, node):
if not isinstance(node, gast.FunctionDef):
raise ValueError
namer = cls()
namer.names.update(get_names(node))
return namer | Construct a namer object for a given function scope. |
342,482 | def get_float_info(self, field):
length = ctypes.c_ulong()
ret = ctypes.POINTER(ctypes.c_float)()
_check_call(_LIB.XGDMatrixGetFloatInfo(self.handle,
c_str(field),
ctypes.byref(length),
... | Get float property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data |
342,483 | def create_corpus(src, out_dir, no_below=20, keep_words=_DEFAULT_KEEP_WORDS):
wordid_filename = os.path.join(out_dir, )
bow_filename = os.path.join(out_dir, )
tfidf_filename = os.path.join(out_dir, )
predicate = None
dct = Dictionary()
dct_handler = DictionaryHandler(dct)
handler ... | \ |
342,484 | def convert_PDF_to_plaintext(fpath, keep_layout=False):
if keep_layout:
layout_option = "-layout"
else:
layout_option = "-raw"
status = 0
doclines = []
p_break_in_line = re.compile(r, re.UNICODE)
cmd_pdftotext = [current_app.config.get("CLASSIFIER_PA... | Convert PDF to txt using pdftotext.
Take the path to a PDF file and run pdftotext for this file, capturing
the output.
:param fpath: (string) path to the PDF file
:return: (list) of unicode strings (contents of the PDF file translated
into plaintext; each string is a line in the document.) |
342,485 | def title(self, title):
title = " What's it like out side {0}? ".format(title)
click.secho("{:=^62}".format(title), fg=self.colors.WHITE)
click.echo() | Prints the title |
342,486 | def prepare_env(org):
key_service = org.service(type=, name=)
wf_service = org.service(type=, name=, parameters=)
env = org.environment(name=)
env.clean()
env.add_service(key_service)
env.add_service(wf_service)
env.add_policy(
{"action": "provisionVms",
"pa... | Example shows how to configure environment from scratch |
342,487 | def write_geno(data, sidx):
start = time.time()
tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name))
with h5py.File(tmparrs, ) as io5:
snparr = io5["snparr"]
bisarr = io5["bisarr"]
bend = np.where(np.all(bisarr[:] == "", axis=0))[0]
... | write the geno output formerly used by admixture, still supported by
adegenet, perhaps. Also, sNMF still likes .geno. |
342,488 | def GetFormatSpecification(cls):
format_specification = specification.FormatSpecification(cls.NAME)
format_specification.AddNewSignature(cls._DLS_V1_SIGNATURE, offset=0)
format_specification.AddNewSignature(cls._DLS_V2_SIGNATURE, offset=0)
return format_specification | Retrieves the format specification.
Returns:
FormatSpecification: format specification. |
342,489 | def _service_by_name(name):
services = _available_services()
name = name.lower()
if name in services:
return services[name]
for service in six.itervalues(services):
if service[].lower() == name:
return service
basename, ext = os.path.split... | Return the service info for a service by label, filename or path |
342,490 | def reject(self):
if self.acknowledged:
raise self.MessageStateError(
"Message already acknowledged with state: %s" % self._state)
self.backend.reject(self.delivery_tag)
self._state = "REJECTED" | Reject this message.
The message will be discarded by the server.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected. |
342,491 | async def process_response(self, request, response):
await super().process_response(request, response)
if COOKIE_AUTH_KEY in request:
if response.started:
raise RuntimeError("Cannot save cookie into started response")
cookie = request[COOKIE_AUTH_KEY]
... | Called to perform any processing of the response required.
This function stores any cookie data in the COOKIE_AUTH_KEY as a
cookie in the response object. If the value is a empty string, the
associated cookie is deleted instead.
This function requires the response to be a aiohttp Respo... |
342,492 | def get_chatlist(chatfile):
if not chatfile:
return set()
try:
with open(chatfile) as file_contents:
return set(int(chat) for chat in file_contents)
except (OSError, IOError) as exc:
LOGGER.error(, exc)
return set() | Try reading ids of saved chats from file.
If we fail, return empty set |
342,493 | def moveCommonAttributesToParentGroup(elem, referencedElements):
num = 0
childElements = []
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
if not child.getAttribute() in referencedElements:
childElements.append(child)
... | This recursively calls this function on all children of the passed in element
and then iterates over all child elements and removes common inheritable attributes
from the children and places them in the parent group. But only if the parent contains
nothing but element children and whitespace. The attribut... |
342,494 | def VerifyRow(self, parser_mediator, row):
try:
time_elements_tuple = self._GetTimeElementsTuple(row[])
except (TypeError, ValueError):
return False
try:
dfdatetime_time_elements.TimeElements(
time_elements_tuple=time_elements_tuple)
except ValueError:
return Fals... | Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified in COLUMNS.
Returns:
bool: True if thi... |
342,495 | def reweight(self, weight, edges=None, copy=False):
if not self.is_weighted():
warnings.warn(
)
return self
if edges is None:
return self._update_edges(weight, copy=copy)
ii, jj = self.pairs()[edges].T
return self.add_edges(ii, jj, weight=weight, symmetric=Fals... | Replaces existing edge weights. weight may be a scalar or 1d array.
edges is a mask or index array that specifies a subset of edges to modify |
342,496 | def generate_synthObs(self, bases_wave, bases_flux, basesCoeff, Av_star, z_star, sigma_star, resample_range = None, resample_int = 1):
nbases = basesCoeff.shape[0]
bases_wave_resam = arange(int(resample_range[0]), int(resample_range[-1]), resample_int, dtype=flo... | basesWave: Bases wavelength must be at rest |
342,497 | def rlaplace(mu, tau, size=None):
u = np.random.uniform(-0.5, 0.5, size)
return mu - np.sign(u) * np.log(1 - 2 * np.abs(u)) / tau | Laplace (double exponential) random variates. |
342,498 | def visitLexerElement(self, ctx: jsgParser.LexerElementContext):
self.visitChildren(ctx)
if ctx.ebnfSuffix():
self._rulePattern += ctx.ebnfSuffix().getText() | lexerElement: lexerAtom ebnfSuffix? | lexerBlock ebnfSuffix? |
342,499 | def get(cls, sensor_type):
app = AndroidApplication.instance()
f = app.create_future()
def on_sensor(sid, mgr):
if sid is None:
f.set_result(None)
else:
f.set_result(Sensor(__id__=sid, manager=mgr, type=sensor_type))
Sens... | Shortcut that acquires the default Sensor of a given type.
Parameters
----------
sensor_type: int
Type of sensor to get.
Returns
-------
result: Future
A future that resolves to an instance of the Sensor or None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.