Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
16,600 | def read_socket_input(connection, socket_obj):
count = connection.needs_input
if count <= 0:
return count
while True:
try:
sock_data = socket_obj.recv(count)
break
except socket.timeout as e:
LOG.debug("Socket timeout exception %s", str(e))... | Read from the network layer and processes all data read. Can
support both blocking and non-blocking sockets.
Returns the number of input bytes processed, or EOS if input processing
is done. Any exceptions raised by the socket are re-raised. |
16,601 | def variantAnnotationsGenerator(self, request):
compoundId = datamodel.VariantAnnotationSetCompoundId.parse(
request.variant_annotation_set_id)
dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
variantSet = dataset.getVariantSet(compoundId.variant_set_id)
... | Returns a generator over the (variantAnnotaitons, nextPageToken) pairs
defined by the specified request. |
16,602 | def deactivate_in_ec(self, ec_index):
with self._mutex:
if ec_index >= len(self.owned_ecs):
ec_index -= len(self.owned_ecs)
if ec_index >= len(self.participating_ecs):
raise exceptions.BadECIndexError(ec_index)
ec = self.pa... | Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index... |
16,603 | def get_tracerinfo(tracerinfo_file):
widths = [rec.width for rec in tracer_recs]
col_names = [rec.name for rec in tracer_recs]
dtypes = [rec.type for rec in tracer_recs]
usecols = [name for name in col_names if not name.startswith()]
tracer_df = pd.read_fwf(tracerinfo_file, widths=widths, nam... | Read an output's tracerinfo.dat file and parse into a DataFrame for
use in selecting and parsing categories.
Parameters
----------
tracerinfo_file : str
Path to tracerinfo.dat
Returns
-------
DataFrame containing the tracer information. |
16,604 | def filter_by(self, string):
self._reatach()
if string == :
self.filter_remove()
return
self._expand_all()
self.treeview.selection_set()
children = self.treeview.get_children()
for item in children:
_, detached = self._detac... | Filters treeview |
16,605 | def CRRAutility(c, gam):
if gam == 1:
return np.log(c)
else:
return( c**(1.0 - gam) / (1.0 - gam) ) | Evaluates constant relative risk aversion (CRRA) utility of consumption c
given risk aversion parameter gam.
Parameters
----------
c : float
Consumption value
gam : float
Risk aversion
Returns
-------
(unnamed) : float
Utility
Tests
-----
Test a val... |
16,606 | def add_file_recursive(self, filename, trim=False):
assert not self.final,
self.add_source_file(filename)
queue = collections.deque([filename])
seen = set()
while queue:
filename = queue.popleft()
self.graph.add_node(filename)
try:
... | Add a file and all its recursive dependencies to the graph.
Args:
filename: The name of the file.
trim: Whether to trim the dependencies of builtin and system files. |
16,607 | def unwrap_state_dict(self, obj: Dict[str, Any]) -> Union[Tuple[str, Any], Tuple[None, None]]:
if len(obj) == 2:
typename = obj.get(self.type_key)
state = obj.get(self.state_key)
if typename is not None:
return typename, state
return None, No... | Unwraps a marshalled state previously wrapped using :meth:`wrap_state_dict`. |
16,608 | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
evaluated_data = [v.evaluate(verbose, decode, passes, num_threads, apply_experimental) for v in self.values]
return MultiIndex(evaluated_data, self.names) | Evaluates by creating a MultiIndex containing evaluated data and index.
See `LazyResult`
Returns
-------
MultiIndex
MultiIndex with evaluated data. |
16,609 | def create_parser(self, prog_name, subcommand):
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_option_list())
for name, description, option_list in self.get_option_gro... | Customize the parser to include option groups. |
16,610 | def has_active_condition(self, condition, instances):
return_value = None
for instance in instances + [None]:
if not self.can_execute(instance):
continue
result = self.is_active(instance, condition)
if result is False:
return F... | Given a list of instances, and the condition active for
this switch, returns a boolean representing if the
conditional is met, including a non-instance default. |
16,611 | def xpathNextAncestor(self, ctxt):
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.xmlXPathNextAncestor(ctxt__o, self._o)
if ret is None:raise xpathError()
__tmp = xmlNode(_obj=ret)
return __tmp | Traversal function for the "ancestor" direction the
ancestor axis contains the ancestors of the context node;
the ancestors of the context node consist of the parent of
context node and the parent's parent and so on; the nodes
are ordered in reverse document order; thus the paren... |
16,612 | def set(self, instance, value, **kw):
ref = []
if api.is_uid(value):
ref.append(api.get_object_by_uid(value))
if api.is_at_content(value):
ref.append(value)
if u.is_dict(value):
results = api.search(por... | Set the value of the refernce field |
16,613 | def _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir):
log_dir = utils.safe_makedir(os.path.join(work_dir, "log"))
example_dir = utils.safe_makedir(os.path.join(work_dir, "examples"))
if len(glob.glob(os.path.join(example_dir, "%s.tfrecord*.gz" % dd.get_sample_name(data)))) == 0:... | Create example pileup images to feed into variant calling. |
16,614 | def rewrite_references_json(json_content, rewrite_json):
for ref in json_content:
if ref.get("id") and ref.get("id") in rewrite_json:
for key, value in iteritems(rewrite_json.get(ref.get("id"))):
ref[key] = value
return json_content | general purpose references json rewriting by matching the id value |
16,615 | def prepare_check(data):
if not data:
return None, {}
if isinstance(data, str):
return data, {}
result = {}
if "ID" in data:
result["CheckID"] = data["ID"]
for k in ("Node", "CheckID", "Name", "Notes", "Status", "ServiceID"):
if k in data:
result[k]... | Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition |
16,616 | def _copyAllocatedStates(self):
if self.verbosity > 1 or self.retrieveLearningStates:
(activeT, activeT1, predT, predT1) = self.cells4.getLearnStates()
self.lrnActiveState[] = activeT1.reshape((self.numberOfCols, self.cellsPerColumn))
self.lrnActiveState[] = activeT.reshape((self.number... | If state is allocated in CPP, copy over the data into our numpy arrays. |
16,617 | def merge_dicts(base, updates):
if not base:
base = dict()
if not updates:
updates = dict()
z = base.copy()
z.update(updates)
return z | Given two dicts, merge them into a new dict as a shallow copy.
Parameters
----------
base: dict
The base dictionary.
updates: dict
Secondary dictionary whose values override the base. |
16,618 | def _get_new_column_header(self, vcf_reader):
mutect_dict = self._build_mutect_dict(vcf_reader.metaheaders)
new_header_list = []
required_keys = set([self._NORMAL_SAMPLE_KEY, self._TUMOR_SAMPLE_KEY])
mutect_keys = set(mutect_dict.keys())
if not required_keys.issubset(m... | Returns a standardized column header.
MuTect sample headers include the name of input alignment, which is
nice, but doesn't match up with the sample names reported in Strelka
or VarScan. To fix this, we replace with NORMAL and TUMOR using the
MuTect metadata command line to replace them... |
16,619 | def submit_vasp_directory(self, rootdir, authors, projects=None,
references=, remarks=None, master_data=None,
master_history=None, created_at=None,
ncpus=None):
from pymatgen.apps.borg.hive import VaspToComputedEn... | Assimilates all vasp run directories beneath a particular
directory using BorgQueen to obtain structures, and then submits thhem
to the Materials Project as SNL files. VASP related meta data like
initial structure and final energies are automatically incorporated.
.. note::
... |
16,620 | def table_to_csv(table, engine, filepath, chunksize=1000, overwrite=False):
sql = select([table])
sql_to_csv(sql, engine, filepath, chunksize) | Export entire table to a csv file.
:param table: :class:`sqlalchemy.Table` instance.
:param engine: :class:`sqlalchemy.engine.base.Engine`.
:param filepath: file path.
:param chunksize: number of rows write to csv each time.
:param overwrite: bool, if True, avoid to overite existing file.
**中文... |
16,621 | def fetch_uri(self, uri, start=None, end=None):
namespace, alias = uri_re.match(uri).groups()
return self.fetch(alias=alias, namespace=namespace, start=start, end=end) | fetch sequence for URI/CURIE of the form namespace:alias, such as
NCBI:NM_000059.3. |
16,622 | async def login(self, email: str, password: str) -> bool:
login_resp = await self._request(
,
API_URL_USER,
json={
: ,
: ,
: {
: email,
: password,
:
... | Login to the profile. |
16,623 | def respects_language(fun):
@wraps(fun)
def _inner(*args, **kwargs):
with respect_language(kwargs.pop(, None)):
return fun(*args, **kwargs)
return _inner | Decorator for tasks with respect to site's current language.
You can use this decorator on your tasks together with default @task
decorator (remember that the task decorator must be applied last).
See also the with-statement alternative :func:`respect_language`.
**Example**:
.. code-block:: pytho... |
16,624 | def connection_key(self):
return "{host}:{namespace}:{username}".format(host=self.host, namespace=self.namespace, username=self.username) | Return an index key used to cache the sampler connection. |
16,625 | def _layout(dict_vars, dict_vars_extra):
desc = [(v, m.description) for v, m in dict_vars.items()]
desc.extend((v, baredoc(m.description))
for v, m in dict_vars_extra.items())
_pretty_print(desc, min_col_width=26) | Print nicely [(var, description)] from phyvars |
16,626 | def http_purge_url(url):
url = urlparse(url)
connection = HTTPConnection(url.hostname, url.port or 80)
path = url.path or
connection.request(, % (path, url.query) if url.query else path, ,
{: % (url.hostname, url.port) if url.port else url.hostname})
response = connect... | Do an HTTP PURGE of the given asset.
The URL is run through urlparse and must point to the varnish instance not the varnishadm |
16,627 | def load_external_components(typesys):
from iotile.core.dev.registry import ComponentRegistry
reg = ComponentRegistry()
modules = reg.list_components()
typelibs = reduce(lambda x, y: x+y, [reg.find_component(x).find_products() for x in modules], [])
for lib in typelibs:
if lib.e... | Load all external types defined by iotile plugins.
This allows plugins to register their own types for type annotations and
allows all registered iotile components that have associated type libraries to
add themselves to the global type system. |
16,628 | def xml_compare(expected, found):
if expected == found:
return True
if set(expected.items()) != set(found.items()):
return False
expected_children = list(expected)
found_children = list(found)
if len(expected_children) != len(found_children):
return Fal... | Checks equality of two ``ElementTree`` objects.
:param expected: An ``ElementTree`` object.
:param found: An ``ElementTree`` object.
:return: ``Boolean``, whether the two objects are equal. |
16,629 | def get_output_structure(self):
bohr_to_angstrom = 0.529177249
natoms = int(float(self._get_line(, self.outputf).split()[-1]))
alat = float(self._get_line(, self.outputf).split()[-1].split()[0])
unit_cell = []
with open(self.outputf, ) as fp... | Determine the structure from the output |
16,630 | def format_message(self, msg):
return {: int(msg.created * 1000),
: self.format(msg),
: self.log_stream or msg.name,
: self.log_group} | format message. |
16,631 | def get_tournament_prize_pool(self, leagueid=None, **kwargs):
if not in kwargs:
kwargs[] = leagueid
url = self.__build_url(urls.GET_TOURNAMENT_PRIZE_POOL, **kwargs)
req = self.executor(url)
if self.logger:
self.logger.info(.format(url))
if not se... | Returns a dictionary that includes community funded tournament prize pools
:param leagueid: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>` |
16,632 | def todegdec(origin):
try:
return float(origin)
except ValueError:
pass
m = dms_re.search(origin)
if m:
degrees = int(m.group())
minutes = float(m.group())
seconds = float(m.group())
return degrees + minutes / 60 + seconds / 3600
... | Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD |
16,633 | def to_dict(self):
fields = dict(vars(self).items())
if self.populated:
fields[] = []
fields[] = []
for ip in self.ip_addresses:
fields[].append({
: ip.address,
: ip.access,
: ip.fam... | Prepare a JSON serializable dict for read-only purposes.
Includes storages and IP-addresses.
Use prepare_post_body for POST and .save() for PUT. |
16,634 | def import_data(self, data):
_completed_num = 0
for trial_info in data:
logger.info("Importing data, current processing progress %s / %s" %(_completed_num, len(data)))
_completed_num += 1
if self.algorithm_name == :
return
assert "... | Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' |
16,635 | def scan_forever(queue, *args, **kwargs):
process_once_now = kwargs.get(, True)
if process_once_now:
for work in scan(queue, *args, **kwargs):
yield work
while True:
with open(fsq_path.trigger(queue), ) as t:
t.read(1)
for work in scan(queue, *args, **kwa... | Return an infinite iterator over an fsq queue that blocks waiting
for the queue trigger. Work is yielded as FSQWorkItem objects when
available, assuming the default generator (FSQScanGenerator) is
in use.
Essentially, this function wraps fsq.scan() and blocks for more work.
It takes... |
16,636 | def _ProcessAudio(self, tag, wall_time, step, audio):
event = AudioEvent(wall_time=wall_time,
step=step,
encoded_audio_string=audio.encoded_audio_string,
content_type=audio.content_type,
sample_rate=audio.sample_rate,
... | Processes a audio by adding it to accumulated state. |
16,637 | def run(self, plugins, context, callback=None, callback_args=[]):
self.data["state"]["is_running"] = True
util.timer("publishing")
stats = {"requestCount": self.host.stats()["totalRequestCount"]}
def on_next(resu... | Commence asynchronous tasks
This method runs through the provided `plugins` in
an asynchronous manner, interrupted by either
completion or failure of a plug-in.
Inbetween processes, the GUI is fed information
from the task and redraws itself.
Arguments:
plu... |
16,638 | def polylog2(x):
rs pade approximation.
Required for the entropy integral of
:obj:`thermo.heat_capacity.Zabransky_quasi_polynomial`.
Examples
--------
>>> polylog2(0.5)
0.5822405264516294
Approximation is valid between 0 and 1 only.')
x = x - offset
return horner(p, x)/horner(q... | r'''Simple function to calculate PolyLog(2, x) from ranges 0 <= x <= 1,
with relative error guaranteed to be < 1E-7 from 0 to 0.99999. This
is a Pade approximation, with three coefficient sets with splits at 0.7
and 0.99. An exception is raised if x is under 0 or above 1.
Parameters
--------... |
16,639 | def decrypt_file(file, key):
if not file.endswith():
raise ValueError("%s does not end with .enc" % file)
fer = Fernet(key)
with open(file, ) as f:
decrypted_file = fer.decrypt(f.read())
with open(file[:-4], ) as f:
f.write(decrypted_file)
os.chmod(file[:-4], 0o600) | Decrypts the file ``file``.
The encrypted file is assumed to end with the ``.enc`` extension. The
decrypted file is saved to the same location without the ``.enc``
extension.
The permissions on the decrypted file are automatically set to 0o600.
See also :func:`doctr.local.encrypt_file`. |
16,640 | def get(method, hmc, uri, uri_parms, logon_required):
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
raise InvalidResourceError(method, uri)
result_lpars = []
if not cpc.dpm_enab... | Operation: List Logical Partitions of CPC (empty result in DPM
mode. |
16,641 | def koji_instance(config, message, instance=None, *args, **kw):
instance = kw.get(, instance)
if not instance:
return False
instances = [item.strip() for item in instance.split()]
return message[].get() in instances | Particular koji instances
You may not have even known it, but we have multiple instances of the koji
build system. There is the **primary** buildsystem at
`koji.fedoraproject.org <http://koji.fedoraproject.org>`_ and also
secondary instances for `ppc <http://ppc.koji.fedoraproject.org>`_, `arm
<ht... |
16,642 | def get_bss_load(_, data):
answers = {
: (data[1] << 8) | data[0],
: data[2] / 255.0,
: (data[4] << 8) | data[3],
}
return answers | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n935.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict. |
16,643 | def add_file(self, file_obj):
BalancedDiscStorage._check_interface(file_obj)
file_hash = self._get_hash(file_obj)
dir_path = self._create_dir_path(file_hash)
final_path = os.path.join(dir_path, file_hash)
def copy_to_file(from_file, to_path):
with open(to_... | Add new file into the storage.
Args:
file_obj (file): Opened file-like object.
Returns:
obj: Path where the file-like object is stored contained with hash\
in :class:`.PathAndHash` object.
Raises:
AssertionError: If the `file_obj` is not fi... |
16,644 | def _Close(self):
super(EWFFile, self)._Close()
for file_object in self._file_objects:
file_object.close()
self._file_objects = [] | Closes the file-like object. |
16,645 | def bucket_policy_to_dict(policy):
import json
if not isinstance(policy, dict):
policy = json.loads(policy)
statements = {s[]: s for s in policy[]}
d = {}
for rw in (, ):
for prefix in TOP_LEVEL_DIRS:
sid = rw.title() + prefix.title()
if sid in state... | Produce a dictionary of read, write permissions for an existing bucket policy document |
16,646 | def centroid(self):
if self.v is None:
raise ValueError()
return np.mean(self.v, axis=0) | Return the geometric center. |
16,647 | def save_aggregate_report_to_elasticsearch(aggregate_report,
index_suffix=None,
monthly_indexes=False):
logger.debug("Saving aggregate report to Elasticsearch")
aggregate_report = aggregate_report.copy()
metadata = ag... | Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed forensic report
index_suffix (str): The suffix of the name of the index to save to
monthly_indexes (bool): Use monthly indexes instead of daily indexes
Raises:
AlreadySaved |
16,648 | def _save_if_needed(request, response_content):
if request.save_response:
file_path = request.get_file_path()
create_parent_folder(file_path)
with open(file_path, ) as file:
file.write(response_content)
LOGGER.debug(, request.url, file_path) | Save data to disk, if requested by the user
:param request: Download request
:type request: DownloadRequest
:param response_content: content of the download response
:type response_content: bytes |
16,649 | def get_representation(self, prefix="", suffix="\n"):
res = prefix + "Section " + self.get_section_name().upper() + suffix
return res | return the string representation of the current object. |
16,650 | def get_decode_value(self):
if self._store_type == PUBLIC_KEY_STORE_TYPE_HEX:
value = bytes.fromhex(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
value = b64decode(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE85:
... | Return the key value based on it's storage type. |
16,651 | async def connect(self, hostname=None, port=None, tls=False, **kwargs):
if not port:
if tls:
port = DEFAULT_TLS_PORT
else:
port = rfc1459.protocol.DEFAULT_PORT
return await super().connect(hostname, port, tls=tls, **kwargs) | Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. |
16,652 | def require_condition(cls, expr, message, *format_args, **format_kwds):
if not expr:
raise cls(message, *format_args, **format_kwds) | used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param: expr: A boolean value indicating an evaluated expression
:param: format_arg... |
16,653 | def credentials(self):
if self._credentials is None:
self._credentials, _ = google.auth.default()
return self._credentials | google.auth.credentials.Credentials: Credentials to use for queries
performed through IPython magics
Note:
These credentials do not need to be explicitly defined if you are
using Application Default Credentials. If you are not using
Application Default Credentials, m... |
16,654 | def search_channels(self, query, limit=25, offset=0):
r = self.kraken_request(, ,
params={: query,
: limit,
: offset})
return models.Channel.wrap_search(r) | Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of channels
:rt... |
16,655 | def _patch_expand_paths(self, settings, name, value):
return [self._patch_expand_path(settings, name, item)
for item in value] | Apply ``SettingsPostProcessor._patch_expand_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Returns:
list: Patched path list to an absolute path. |
16,656 | def assertSameType(a, b):
if not isinstance(b, type(a)):
raise NotImplementedError("This operation is only supported for " \
"elements of the same type. Instead found {} and {}".
format(type(a), type(b))) | Raises an exception if @b is not an instance of type(@a) |
16,657 | def _path_polygon(self, points):
"Low-level polygon-drawing routine."
(xmin, ymin, xmax, ymax) = _compute_bounding_box(points)
if invisible_p(xmax, ymax):
return
self.setbb(xmin, ymin)
self.setbb(xmax, ymax)
self.newpath()
self.moveto(xscale(points[0]... | Low-level polygon-drawing routine. |
16,658 | def _revert_categories(self):
for column, dtype in self._categories.items():
if column in self.columns:
self[column] = self[column].astype(dtype) | Inplace conversion to categories. |
16,659 | def vx(self,*args,**kwargs):
thiso= self(*args,**kwargs)
if not len(thiso.shape) == 2: thiso= thiso.reshape((thiso.shape[0],1))
if len(thiso[:,0]) == 2:
return thiso[1,:]
if len(thiso[:,0]) != 4 and len(thiso[:,0]) != 6:
raise AttributeError("orbit must t... | NAME:
vx
PURPOSE:
return x velocity at time t
INPUT:
t - (optional) time at which to get the velocity
vo= (Object-wide default) physical scale for velocities to use to convert
use_physical= use to override Object-wide default for using a physical sc... |
16,660 | def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="",
add_join=False):
node_type = node[1][consts.Consts.type]
if node_type == consts.Consts.start_event:
return BpmnDiagramGraphCsvExport.export_start_ev... | General method for node exporting
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
... |
16,661 | def _add_none_handler(validation_callable,
none_policy
):
if none_policy is NonePolicy.SKIP:
return _none_accepter(validation_callable)
elif none_policy is NonePolicy.FAIL:
return _none_rejecter(validation_callable)
eli... | Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
:param none_policy: an int representing the None policy, see NonePolicy
:return: |
16,662 | def symmetric_difference_update(self, that):
_set = self._set
_list = self._list
_set.symmetric_difference_update(that)
_list.clear()
_list.update(_set)
return self | Update the set, keeping only elements found in either *self* or *that*,
but not in both. |
16,663 | def get_first_n_queues(self, n):
try:
while len(self.queues) < n:
self.__fetch__()
except StopIteration:
pass
values = list(self.queues.values())
missing = n - len(values)
values.extend(iter([]) for n in range(missing))
return values | Run through the sequence until n queues are created and return
them. If fewer are created, return those plus empty iterables to
compensate. |
16,664 | def _shuffled_order(w, h):
rowsize = 4 * w
for row in range(0, rowsize * h, rowsize):
for offset in range(row, row + w):
for x in range(offset, offset + rowsize, w):
yield x | Generator for the order of 4-byte values.
32bit channels are also encoded using delta encoding,
but it make no sense to apply delta compression to bytes.
It is possible to apply delta compression to 2-byte or 4-byte
words, but it seems it is not the best way either.
In PSD, each 4-byte item is spli... |
16,665 | def add(self, doc, attributes=None):
doc_ref = str(doc[self._ref])
self._documents[doc_ref] = attributes or {}
self.document_count += 1
for field_name, field in self._fields.items():
extractor = field.extractor
field_value = doc[field_name] if extractor ... | Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (by default
this is 'id') and it should h... |
16,666 | def _read_header(stream, decoder, strict=False):
name_len = stream.read_ushort()
name = stream.read_utf8_string(name_len)
required = bool(stream.read_uchar())
data_len = stream.read_ulong()
pos = stream.tell()
data = decoder.readElement()
if strict and pos + data_len != stream.tell(... | Read AMF L{Message} header from the stream.
@type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>}
@param decoder: An AMF0 decoder.
@param strict: Use strict decoding policy. Default is C{False}. Will raise a
L{pyamf.DecodeError} if the data that was read from the stream does not
... |
16,667 | def choose_one(things):
choice = SystemRandom().randint(0, len(things) - 1)
return things[choice].strip() | Returns a random entry from a list of things |
16,668 | def account_settings_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/account_settings
api_path = "/api/v2/account/settings.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/account_settings#update-account-settings |
16,669 | def parse_datetime(value: Union[datetime, StrIntFloat]) -> datetime:
if isinstance(value, datetime):
return value
number = get_numeric(value)
if number is not None:
return from_unix_seconds(number)
match = datetime_re.match(cast(str, value))
if not match:
raise errors.... | Parse a datetime/int/float/string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raise ValueError if the input is well formatted but not a valid datetime.
Raise ValueError if the input isn'... |
16,670 | def save(self, filesto, upload_to=None, name=None, secret=None, prefix=None,
allowed=None, denied=None, max_size=None, **kwargs):
if not filesto:
return None
upload_to = upload_to or self.upload_to
secret = secret or self.secret
prefix = prefix or self.p... | Except for `filesto`, all of these parameters are optional, so only
bother setting the ones relevant to *this upload*.
filesto
: A `werkzeug.FileUploader`.
upload_to
: Relative path to where to upload
secret
: If True, instead of the original filename, a ... |
16,671 | def _create_response_future(self, query, parameters, trace, custom_payload,
timeout, execution_profile=EXEC_PROFILE_DEFAULT,
paging_state=None, host=None):
prepared_statement = None
if isinstance(query, six.string_types):
... | Returns the ResponseFuture before calling send_request() on it |
16,672 | def call_sockeye_train(model: str,
bpe_dir: str,
model_dir: str,
log_fname: str,
num_gpus: int,
test_mode: bool = False):
fnames = ["--source={}".format(os.path.join(bpe_dir, PREFIX_TRAIN + S... | Call sockeye.train with specified arguments on prepared inputs. Will resume
partial training or skip training if model is already finished. Record
command for future use.
:param model: Type of translation model to train.
:param bpe_dir: Directory of BPE-encoded input data.
:param model_dir: Model... |
16,673 | def update_status(self, helper, status):
if status:
self.status(status[0])
if status[0] == 0:
self.add_long_output(status[1])
else:
self.add_summary(status[1]) | update the helper |
16,674 | def get_available_user_FIELD_transitions(instance, user, field):
for transition in get_available_FIELD_transitions(instance, field):
if transition.has_perm(instance, user):
yield transition | List of transitions available in current model state
with all conditions met and user have rights on it |
16,675 | def acorr(blk, max_lag=None):
if max_lag is None:
max_lag = len(blk) - 1
return [sum(blk[n] * blk[n + tau] for n in xrange(len(blk) - tau))
for tau in xrange(max_lag + 1)] | Calculate the autocorrelation of a given 1-D block sequence.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
max_lag :
The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``,
since any lag beyond would result in z... |
16,676 | def as_dict(self):
d = {"comment": self.comment, "nkpoints": self.num_kpts,
"generation_style": self.style.name, "kpoints": self.kpts,
"usershift": self.kpts_shift,
"kpts_weights": self.kpts_weights, "coord_type": self.coord_type,
"labels": self.label... | json friendly dict representation of Kpoints |
16,677 | def coroutine(func):
@wraps(func)
def initialization(*args, **kwargs):
start = func(*args, **kwargs)
next(start)
return start
return initialization | Initializes coroutine essentially priming it to the yield statement.
Used as a decorator over functions that generate coroutines.
.. code-block:: python
# Basic coroutine producer/consumer pattern
from translate import coroutine
@coroutine
def coroutine_foo(bar):
t... |
16,678 | def get_properties(self):
variables = self.model.nodes()
property_tag = {}
for variable in sorted(variables):
properties = self.model.node[variable]
properties = collections.OrderedDict(sorted(properties.items()))
property_tag[variable] = []
... | Add property to variables in BIF
Returns
-------
dict: dict of type {variable: list of properties }
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>>> writer = BIFWriter(model)
... |
16,679 | def get_results(self, hql, schema=, fetch_size=None, hive_conf=None):
results_iter = self._get_results(hql, schema,
fetch_size=fetch_size, hive_conf=hive_conf)
header = next(results_iter)
results = {
: list(results_iter),
... | Get results of the provided hql in target schema.
:param hql: hql to be executed.
:type hql: str or list
:param schema: target schema, default to 'default'.
:type schema: str
:param fetch_size: max size of result to fetch.
:type fetch_size: int
:param hive_conf: ... |
16,680 | def create_cursor(self, name=None):
return Cursor(self.client_connection, self.connection, self.djongo_connection) | Returns an active connection cursor to the database. |
16,681 | def placeholder(type_):
typetuple = type_ if isinstance(type_, tuple) else (type_,)
if any in typetuple:
typetuple = any
if typetuple not in EMPTY_VALS:
EMPTY_VALS[typetuple] = EmptyVal(typetuple)
return EMPTY_VALS[typetuple] | Returns the EmptyVal instance for the given type |
16,682 | def get_resource_by_urn(self, urn):
search_query = % urn
try:
assert isinstance(urn, CTS_URN)
except Exception as e:
return self._session.get_resource(resource_uri, Person) | Fetch the resource corresponding to the input CTS URN.
Currently supports
only HucitAuthor and HucitWork.
:param urn: the CTS URN of the resource to fetch
:return: either an instance of `HucitAuthor` or of `HucitWork` |
16,683 | def proto_avgRange(theABF,m1=None,m2=None):
abf=ABF(theABF)
abf.log.info("analyzing as a fast IV")
if m1 is None:
m1=abf.sweepLength
if m2 is None:
m2=abf.sweepLength
I1=int(abf.pointsPerSec*m1)
I2=int(abf.pointsPerSec*m2)
Ts=np.arange(abf.sweeps)*abf.sweepInterval
... | experiment: generic VC time course experiment. |
16,684 | def get_recipe_env(self, arch, with_flags_in_cc=True):
env = super(ScryptRecipe, self).get_recipe_env(arch, with_flags_in_cc)
openssl_recipe = self.get_recipe(, self.ctx)
env[] += openssl_recipe.include_flags(arch)
env[] += .format(self.ctx.get_libs_dir(arch.arch))
env[]... | Adds openssl recipe to include and library path. |
16,685 | def hash_file(filepath: str) -> str:
md5 = hashlib.md5()
acc_hash(filepath, md5)
return md5.hexdigest() | Return the hexdigest MD5 hash of content of file at `filepath`. |
16,686 | def exception_handle(method):
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception(, args)
raise ProxyError()
except ConnectionException:
LOG.exception(, args)
... | Handle exception raised by requests library. |
16,687 | def revcomp(sequence):
"returns reverse complement of a string"
sequence = sequence[::-1].strip()\
.replace("A", "t")\
.replace("T", "a")\
.replace("C", "g")\
.replace("G", "c").upper()
return... | returns reverse complement of a string |
16,688 | def handle_message(self, msg):
if msg.msg_id not in self.msg_types:
self.report_message_type(msg)
self.msg_types.add(msg.msg_id)
self.tc.message(, typeId=msg.msg_id, message=msg.msg,
file=os.path.relpath(msg.abspath).replace(, ),
... | Issues an `inspection` service message based on a PyLint message.
Registers each message type upon first encounter.
:param utils.Message msg: a PyLint message |
16,689 | def __search(self, obj, item, parent="root", parents_ids=frozenset({})):
if self.__skip_this(item, parent):
return
elif isinstance(obj, strings) and isinstance(item, strings):
self.__search_str(obj, item, parent)
elif isinstance(obj, strings) and isinstance(it... | The main search method |
16,690 | def all(self, data={}, **kwargs):
return super(Refund, self).all(data, **kwargs) | Fetch All Refund
Returns:
Refund dict |
16,691 | def _parse_sections(self):
def _list_to_dict(_dict, path, sec):
tmp = _dict
for elm in path[:-1]:
tmp = tmp[elm]
tmp[sec] = OrderedDict()
self._sections = list()
section_regexp = r"\n==* .* ==*\n"
found_obj = re.findall(sec... | parse sections and TOC |
16,692 | def on_any_event(self, event):
if os.path.isfile(event.src_path):
self.callback(event.src_path, **self.kwargs) | File created or modified |
16,693 | def startProcesses(self):
self.process_map = {}
for mvision_class in self.mvision_classes:
name = mvision_class.name
tag = mvision_class.tag
num = mvision_class.max_instances
if (tag not in self.process_map):
... | Create and start python multiprocesses
Starting a multiprocess creates a process fork.
In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied), but in practice, all kinds of weird... |
16,694 | def init_debug(self):
import signal
def debug_trace(sig, frame):
self.log()
self.log(.join(traceback.format_stack(frame)))
signal.signal(signal.SIGUSR2, debug_trace) | Initialize debugging features, such as a handler for USR2 to print a trace |
16,695 | def push_resource_cache(resourceid, info):
if not resourceid:
raise ResourceInitError("Resource id missing")
if not DutInformationList._cache.get(resourceid):
DutInformationList._cache[resourceid] = dict()
DutInformationList._cache[resourceid] = merge(DutInformat... | Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing |
16,696 | def _get_dirs(user_dir, startup_dir):
try:
users = os.listdir(user_dir)
except WindowsError:
users = []
full_dirs = []
for user in users:
full_dir = os.path.join(user_dir, user, startup_dir)
if os.path.exists(full_dir):
full_dirs.append(full_dir)
r... | Return a list of startup dirs |
16,697 | def get_asset_form_for_create(self, asset_record_types):
for arg in asset_record_types:
if not isinstance(arg, ABCType):
raise errors.InvalidArgument()
if asset_record_types == []:
obj_form = objects.AssetForm(
repository... | Gets the asset form for creating new assets.
A new form should be requested for each create transaction.
arg: asset_record_types (osid.type.Type[]): array of asset
record types
return: (osid.repository.AssetForm) - the asset form
raise: NullArgument - ``asset_record... |
16,698 | def kernels_initialize(self, folder):
if not os.path.isdir(folder):
raise ValueError( + folder)
resources = []
resource = {: }
resources.append(resource)
username = self.get_config_value(self.CONFIG_NAME_USER)
meta_data = {
: username + ... | create a new kernel in a specified folder from template, including
json metadata that grabs values from the configuration.
Parameters
==========
folder: the path of the folder |
16,699 | def mask(self):
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.