text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_customjs(self, references, plot_id=None):
"""
Creates a CustomJS callback that will send the requested
attributes back to python.
"""
# Generate callback JS code to get all the requested data
if plot_id is None:
plot_id = self.plot.id or 'PLACEHOLDER_P... | 0.001988 |
def _find_cmd(cmd):
"""Find the full path to a .bat or .exe using the win32api module."""
try:
from win32api import SearchPath
except ImportError:
raise ImportError('you need to have pywin32 installed for this to work')
else:
PATH = os.environ['PATH']
extensions = ['.exe'... | 0.004792 |
def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] | 0.010239 |
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one... | 0.001531 |
def auc(x, y, reorder=False): #from sklearn, http://scikit-learn.org, licensed under BSD License
"""Compute Area Under the Curve (AUC) using the trapezoidal rule
This is a general fuction, given points on a curve. For computing the area
under the ROC-curve, see :func:`auc_score`.
Parameters
-----... | 0.003035 |
def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
color_labels=None, **kwargs):
"""Plot the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.sub... | 0.003974 |
def _remove(self, shard_name):
"""remove member from configuration"""
result = self.router_command("removeShard", shard_name, is_eval=False)
if result['ok'] == 1 and result['state'] == 'completed':
shard = self._shards.pop(shard_name)
if shard.get('isServer', False):
... | 0.004132 |
def insert(self, item, priority):
"""Adds item to DEPQ with given priority by performing a binary
search on the concurrently rotating deque. Amount rotated R of
DEPQ of length n would be n <= R <= 3n/2. Performance: O(n)"""
with self.lock:
self_data = self.data
... | 0.000826 |
def round_sig_error(num, uncert, pm=False):
"""
Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods.
The uncertainty determines the sig fig rounding of the number.
https://pythonhosted.org/uncertainties/user_guide.html
"""
u = ufloat(num, uncer... | 0.004831 |
def calculate_max_cols_length(table, size):
"""
:param table: list of lists:
[["row 1 column 1", "row 1 column 2"],
["row 2 column 1", "row 2 column 2"]]
each item consists of instance of urwid.Text
:returns dict, {index: width}
"""
max_cols_lengths = {}
for row in table:
... | 0.00321 |
def parse_comment_telemetry(text):
"""
Looks for base91 telemetry found in comment field
Returns [remaining_text, telemetry]
"""
parsed = {}
match = re.findall(r"^(.*?)\|([!-{]{4,14})\|(.*)$", text)
if match and len(match[0][1]) % 2 == 0:
text, telemetry, post = match[0]
tex... | 0.001299 |
def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit.
Return '' if EOF is hit. Block if no data is immediately
available.
"""
self.process_rawq()
while self.cookedq.tell() == 0 and not self.eof:
self.fill_rawq()
self.p... | 0.004435 |
async def request_proof(self, connection: Connection):
"""
Example:
connection = await Connection.create(source_id)
await connection.connect(phone_number)
name = "proof name"
requested_attrs = [{"name": "age", "restrictions": [{"schema_id": "6XFh8yBzrpJQmNyZzgoTqB:2:schem... | 0.001977 |
def get_score(self, member, default=None, pipe=None):
"""
Return the score of *member*, or *default* if it is not in the
collection.
"""
pipe = self.redis if pipe is None else pipe
score = pipe.zscore(self.key, self._pickle(member))
if (score is None) and (defaul... | 0.005102 |
def strip_cdata(text):
"""Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped str... | 0.001972 |
def _set_below(self, v, load=False):
"""
Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_below is considered as a private
method. Backends l... | 0.006013 |
def encode_timestamp(timestamp: hints.Buffer) -> str:
"""
Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the first 6 bytes of a ULID, which
are a timestamp in milliseconds.
.. note:: This uses an optimized strategy from the `NU... | 0.003501 |
def collect(items, convert=(list, tuple), convert_to=tuple):
"""
Converts a nested list/tuple/generator into a tuple. If no nested list/tuple/generator
is found (or if multiple are found) then "items" is returned unchanged to the caller.
Useful for generic functions.
:param items: Target sequ... | 0.004038 |
def _wanmen_get_title_by_json_topic_part(json_content, tIndex, pIndex):
"""JSON, int, int, int->str
Get a proper title with courseid+topicID+partID."""
return '_'.join([json_content[0]['name'],
json_content[0]['Topics'][tIndex]['name'],
json_content[0]['Topics']... | 0.008451 |
def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.batch_size
r = []
... | 0.008527 |
def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warn... | 0.002278 |
def mpsse_read_gpio(self):
"""Read both GPIO bus states and return a 16 bit value with their state.
D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
"""
# Send command to read low byte and high byte.
self._write('\x81\x83')
# Wait for 2 byte response.
da... | 0.006568 |
def _handle_message_for_stream(self, stream_transport, message, timeout):
"""Handle an incoming message, check if it's for the given stream.
If the message is not for the stream, then add it to the appropriate
message queue.
Args:
stream_transport: AdbStreamTransport currently waiting on a messa... | 0.006132 |
async def emit(self, event, data=None, room=None, skip_sid=None,
namespace=None, callback=None, **kwargs):
"""Emit a custom event to one or more connected clients.
:param event: The event name. It can be any string. The event names
``'connect'``, ``'message'`` a... | 0.001125 |
def getShocks(self):
'''
Draws a new Markov state and income shocks for the representative agent.
Parameters
----------
None
Returns
-------
None
'''
cutoffs = np.cumsum(self.MrkvArray[self.MrkvNow,:])
MrkvDraw = drawUniform(N=1,s... | 0.021386 |
def _unascii(s):
"""Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8
This method takes the output of the JSONEncoder and expands any \\uNNNN
escapes it finds (except for \\u0000 to \\u001F, which are converted to
\\xNN escapes).
For performance, it assumes that the input is valid JSO... | 0.000367 |
def buffer_side(linestring, side, buffer):
"""
Given a Shapely LineString, a side of the LineString
(string; 'left' = left hand side of LineString,
'right' = right hand side of LineString, or
'both' = both sides), and a buffer size in the distance units of
the LineString, buffer the LineString o... | 0.00103 |
def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Optional[tuple] = None) -> List[IModel]:
"""Get aggregated results
: param query: Rulez based query
: param group: Grouping structure
: param order_by: Tuple of ... | 0.007828 |
def entries(self):
"""A list of :class:`PasswordEntry` objects."""
passwords = []
for store in self.stores:
passwords.extend(store.entries)
return natsort(passwords, key=lambda e: e.name) | 0.008658 |
def http_put(self, path, query_data={}, post_data={}, files=None,
**kwargs):
"""Make a PUT request to the Gitlab server.
Args:
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data... | 0.002618 |
def _format_playlist_line(self, lineNum, pad, station):
""" format playlist line so that if fills self.maxX """
line = "{0}. {1}".format(str(lineNum + self.startPos + 1).rjust(pad), station[0])
f_data = ' [{0}, {1}]'.format(station[2], station[1])
if version_info < (3, 0):
if... | 0.00501 |
def demo(context):
"""Setup a scout demo instance. This instance will be populated with a
case, a gene panel and some variants.
"""
LOG.info("Running scout setup demo")
institute_name = context.obj['institute_name']
user_name = context.obj['user_name']
user_mail = context.obj['user_mail']... | 0.011804 |
def init_send(self):
"""
Generates the first (IKE_INIT) packet for Initiator
:return: bytes() containing a valid IKE_INIT packet
"""
packet = Packet()
self.packets.append(packet)
packet.add_payload(payloads.SA())
packet.add_payload(payloads.KE(diffie_hell... | 0.003839 |
def from_config(cls, cp, model, nprocesses=1, use_mpi=False):
"""
Loads the sampler from the given config file.
For generating the temperature ladder to be used by emcee_pt, either
the number of temperatures (provided by the option 'ntemps'),
or the path to a file storing invers... | 0.000717 |
def get_dtype_kinds(l):
"""
Parameters
----------
l : list of arrays
Returns
-------
a set of kinds that exist in this list of arrays
"""
typs = set()
for arr in l:
dtype = arr.dtype
if is_categorical_dtype(dtype):
typ = 'category'
elif is_s... | 0.001951 |
def select_graphic_rendition(self, *attrs):
"""Set display attributes.
:param list attrs: a list of display attributes to set.
"""
replace = {}
# Fast path for resetting all attributes.
if not attrs or attrs == (0, ):
self.cursor.attrs = self.default_char
... | 0.001055 |
def parse(self, scope):
"""Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
self
"""
if not self.parsed:
if len(self.tokens) > 2:
property, style, _ = self.tokens
sel... | 0.003021 |
def getLinkedRequests(self):
"""Lookup linked Analysis Requests
:returns: sorted list of ARs, where the latest AR comes first
"""
rc = api.get_tool("reference_catalog")
refs = rc.getBackReferences(self, "AnalysisRequestAttachment")
# fetch the objects by UID and handle n... | 0.002604 |
def put(self, item):
''' store item in sqlite database
'''
if isinstance(item, self._item_class):
self._put_one(item)
elif isinstance(item, (list, tuple)):
self._put_many(item)
else:
raise RuntimeError('Unknown item(s) type, %s' % type(item)) | 0.006289 |
def appendInputWithNSimilarValues(inputs, numNear = 10):
""" Creates a neighboring record for each record in the inputs and adds
new records at the end of the inputs list
"""
numInputs = len(inputs)
skipOne = False
for i in xrange(numInputs):
input = inputs[i]
numChanged = 0
newInput = copy.deep... | 0.016304 |
def _readClusterSettings(self):
"""
Read the current instance's meta-data to get the cluster settings.
"""
# get the leader metadata
mdUrl = "http://169.254.169.254/metadata/instance?api-version=2017-08-01"
header = {'Metadata': 'True'}
request = urllib.request.Re... | 0.004766 |
def create(self, vlans):
"""
Method to create vlan's
:param vlans: List containing vlan's desired to be created on database
:return: None
"""
data = {'vlans': vlans}
return super(ApiVlan, self).post('api/v3/vlan/', data) | 0.007194 |
def from_callback(cls, cb, ny=None, nparams=None, dep_scaling=1, indep_scaling=1,
**kwargs):
"""
Create an instance from a callback.
Analogous to :func:`SymbolicSys.from_callback`.
Parameters
----------
cb : callable
Signature rhs(x, y[... | 0.005055 |
def release(self):
"""
Releases this resource back to the pool it came from.
"""
if self.errored:
self.pool.delete_resource(self)
else:
self.pool.release(self) | 0.008969 |
def root():
"""Placeholder root url for the PCI.
Ideally this should never be called!
"""
response = {
"links": {
"message": "Welcome to the SIP Processing Controller Interface",
"items": [
{"href": "{}health".format(request.url)},
{"href"... | 0.001789 |
def IsPrimitiveType(obj):
"""See if the passed in type is a Primitive Type"""
return (isinstance(obj, types.bool) or isinstance(obj, types.byte) or
isinstance(obj, types.short) or isinstance(obj, six.integer_types) or
isinstance(obj, types.double) or isinstance(obj, types.float) or
isinstance(ob... | 0.018727 |
def _create_instance(self, cls, args, ref=None):
"""
Returns an instance of `cls` with `args` passed as arguments.
Recursively inspects `args` to create nested objects and functions as
necessary.
`cls` will only be considered only if it's an object we track
(i.e.: trop... | 0.000453 |
def exclude_paths(root, patterns, dockerfile=None):
"""
Given a root directory path and a list of .dockerignore patterns, return
an iterator of all paths (both regular files and directories) in the root
directory that do *not* match any of the patterns.
All paths returned are relative to the root.
... | 0.002033 |
def estimate_chi2mixture(self, lrt):
"""
estimates the parameters of a mixture of a chi-squared random variable of degree
0 and a scaled chi-squared random variable of degree d
(1-mixture)*chi2(0) + (mixture)*scale*chi2(dof),
where
scale is the scaling paramet... | 0.018421 |
def get(self, key, local_default = None, required = False):
"""Get a parameter value.
If parameter is not set, return `local_default` if it is not `None`
or the PyXMPP global default otherwise.
:Raise `KeyError`: if parameter has no value and no global default
:Return: paramet... | 0.005929 |
def system_bus(**kwargs) :
"returns a Connection object for the D-Bus system bus."
return \
Connection(dbus.Connection.bus_get(DBUS.BUS_SYSTEM, private = False)) \
.register_additional_standard(**kwargs) | 0.017621 |
def update_experiments(self):
"""Experiment mapping."""
# 693 Remove if 'not applicable'
for field in record_get_field_instances(self.record, '693'):
subs = field_get_subfields(field)
all_subs = subs.get('a', []) + subs.get('e', [])
if 'not applicable' in [x.l... | 0.001511 |
def default_icon_path(self):
"""Returns default path to icon of this assistant.
Assuming self.path == "/foo/assistants/crt/python/django.yaml"
For image format in [png, svg]:
1) Take the path of this assistant and strip it of load path
(=> "crt/python/django.yaml")
... | 0.003724 |
def get_updated(self, from_time, to_time=None):
"""
Retrives a list of series that have changed on TheTVDB since a provided from time parameter and optionally to an
specified to time.
:param from_time: An epoch representation of the date from which to restrict the query to.
:par... | 0.008712 |
def get(self):
"""
Get a JSON-ready representation of this Section.
:returns: This Section, ready for use in a request body.
:rtype: dict
"""
section = {}
if self.key is not None and self.value is not None:
section[self.key] = self.value
retur... | 0.006079 |
def deploy_from_template(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
"""
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder: DeployFromTemplateDetails
:type vcenter_data_mod... | 0.003333 |
def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True,
for_maps=False, *args, **kwargs):
"""
Function to create subplots.
This function creates so many subplots on so many figures until the
specified number `n` is reached.
Parameters
----------
rows: i... | 0.000485 |
def filter_macro(func, *args, **kwargs):
"""
Promotes a function that returns a filter into its own filter type.
Example::
@filter_macro
def String():
return Unicode | Strip | NotEmpty
# You can now use `String` anywhere you would use a regular Filter:
(String ... | 0.000568 |
def callback_prototype(prototype):
"""Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
whic... | 0.004621 |
def reduce_configs(self):
"""Reduce the experiments to restart."""
experiment_ids = self.get_reduced_configs()
experiments = self.experiment_group.experiments.filter(id__in=experiment_ids)
self.create_iteration()
iteration_config = self.experiment_group.iteration_config
h... | 0.003842 |
def set_pairs(self):
"""
%prog pairs <blastfile|samfile|bedfile>
Report how many paired ends mapped, avg distance between paired ends, etc.
Paired reads must have the same prefix, use --rclip to remove trailing
part, e.g. /1, /2, or .f, .r, default behavior is to truncate until ... | 0.010093 |
def load_data(self, pdbid):
"""Loads and parses an XML resource and saves it as a tree if successful"""
f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower())
self.doc = etree.parse(f) | 0.016064 |
def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING):
"""similar to colRowIsOnSciencePixelList() but takes lists as input"""
out = np.ones(len(col), dtype=bool)
col_arr = np.array(col)
row_arr = np.array(row)
mask = np.bitwise_or(col_arr < 12. - padding, col_ar... | 0.004082 |
def QueryUsers(self, database_link, query, options=None):
"""Queries users in a database.
:param str database_link:
The link to the database.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query... | 0.003742 |
def radiated_intensity(rho, i, j, epsilonp, rm, omega_level, xi,
N, D, unfolding):
r"""Return the radiated intensity in a given direction.
>>> from fast import State, Integer, split_hyperfine_to_magnetic
>>> g = State("Rb", 87, 5, 1, 3/Integer(2), 0)
>>> e = State("Rb", 87, 4, 2,... | 0.000378 |
def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs):
"""
This is an asynchronous sender callable that uses the Django ORM to store
webhooks. Redis is used to handle the message queue.
dkwargs argument requires the following key/values:
:event: A string representi... | 0.002674 |
def toStr(self) :
"""returns a string version of the CSV"""
s = [self.strLegend]
for l in self.lines :
s.append(l.toStr())
return self.lineSeparator.join(s) | 0.05988 |
def get_formset(self):
"""Provide the formset corresponding to this DataTable.
Use this to validate the formset and to get the submitted data back.
"""
if self._formset is None:
self._formset = self.formset_class(
self.request.POST or None,
in... | 0.004762 |
def common_vector_root(vec1, vec2):
"""
Return common root of the two vectors.
Args:
vec1 (list/tuple): First vector.
vec2 (list/tuple): Second vector.
Usage example::
>>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0])
[1, 2]
Returns:
list: Common pa... | 0.001949 |
def put(self, item, priority=None):
"""
Stores a transition in replay memory.
If the memory is full, the oldest entry is replaced.
"""
if not self._isfull():
self._memory.append(None)
position = self._next_position_then_increment()
old_priority = 0 if... | 0.003454 |
def whitelist(self, address: Address):
"""Whitelist peer address to receive communications from
This may be called before transport is started, to ensure events generated during
start are handled properly.
"""
self.log.debug('Whitelist', address=to_normalized_address(address))
... | 0.008219 |
def parse(cls, headers):
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
"""
h = cls()
for line i... | 0.007212 |
def create(self, index, doc_type, body, id=None, **query_params):
"""
Adds a typed JSON document in a specific index, making it searchable.
Behind the scenes this method calls index(..., op_type='create')
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`... | 0.002823 |
def show(self):
"""Shows the main window and grabs the focus on it.
"""
self.hidden = False
# setting window in all desktops
window_rect = RectCalculator.set_final_window_rect(self.settings, self.window)
self.window.stick()
# add tab must be called before windo... | 0.002695 |
def contains_variance(arrays, names):
"""
Make sure both arrays for bivariate ("scatter") plot have a stddev > 0
"""
for ar, name in zip(arrays, names):
if np.std(ar) == 0:
sys.stderr.write(
"No variation in '{}', skipping bivariate plots.\n".format(name.lower()))
... | 0.006397 |
def iter_parts(self):
"""
Generate exactly one reference to each of the parts in the package by
performing a depth-first traversal of the rels graph.
"""
def walk_parts(source, visited=list()):
for rel in source.rels.values():
if rel.is_external:
... | 0.002861 |
def desc(self, table):
'''Returns table description
>>> yql.desc('geo.countries')
>>>
'''
query = "desc {0}".format(table)
response = self.raw_query(query)
return response | 0.008772 |
def statuses_update(self, status, in_reply_to_status_id=None, lat=None,
long=None, place_id=None, display_coordinates=None,
trim_user=None, media_ids=None):
"""
Posts a tweet.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
:par... | 0.001238 |
def _legacy_handle_registration(config, pconn):
'''
Handle the registration process
Returns:
True - machine is registered
False - machine is unregistered
None - could not reach the API
'''
logger.debug('Trying registration.')
# force-reregister -- remove machine-id files ... | 0.000392 |
def LockRetryWrapper(self,
subject,
retrywrap_timeout=1,
retrywrap_max_timeout=10,
blocking=True,
lease_time=None):
"""Retry a DBSubjectLock until it succeeds.
Args:
subject: The subject whi... | 0.007779 |
def users_update(self, user_id, **kwargs):
"""Update an existing user."""
return self.__call_api_post('users.update', userId=user_id, data=kwargs) | 0.018519 |
def clean_cache(self, request):
"""
Remove all MenuItems from Cache.
"""
treenav.delete_cache()
self.message_user(request, _('Cache menuitem cache cleaned successfully.'))
info = self.model._meta.app_label, self.model._meta.model_name
changelist_url = reverse('adm... | 0.009479 |
def update_configuration(app):
"""Update parameters which are dependent on information from the
project-specific conf.py (including its location on the filesystem)"""
config = app.config
project = config.project
config_dir = app.env.srcdir
sys.path.insert(0, os.path.join(config_dir, '..'))
... | 0.002323 |
def wall_factor_fd(mu, mu_wall, turbulent=True, liquid=False):
r'''Computes the wall correction factor for pressure drop due to friction
between a fluid and a wall. These coefficients were derived for internal
flow inside a pipe, but can be used elsewhere where appropriate data is
missing.
.... | 0.004739 |
def create_new_example(self, foo='', a='', b=''):
"""Entity object factory."""
return create_new_example(foo=foo, a=a, b=b) | 0.014388 |
def plot_op(fn, inputs=[], outputs=[]):
"""
User-exposed api method for constructing a python_node
Args:
fn: python function that computes some np.ndarrays given np.ndarrays as inputs. it can have arbitrary side effects.
inputs: array of tf.Tensors (optional). These are where fn derives its values from
outputs: ... | 0.035573 |
def coderef_to_ecoclass(self, code, reference=None):
"""
Map a GAF code to an ECO class
Arguments
---------
code : str
GAF evidence code, e.g. ISS, IDA
reference: str
CURIE for a reference for the evidence instance. E.g. GO_REF:0000001.
... | 0.01023 |
def diff(self, test_id_1, test_id_2, config=None, **kwargs):
"""
Create a diff report using test_id_1 as a baseline
:param: test_id_1: test id to be used as baseline
:param: test_id_2: test id to compare against baseline
:param: config file for diff (optional)
:param: **kwargs: keyword arguments... | 0.007819 |
def uncompressed(self):
"""If true, handle uncompressed data
"""
ISUNCOMPRESSED = self.verboseRead(
BoolCode('UNCMPR', description='Is uncompressed?'))
if ISUNCOMPRESSED:
self.verboseRead(FillerAlphabet(streamPos=self.stream.pos))
print('Uncompressed d... | 0.004193 |
def __request_start(self, queue_item):
"""Execute the request in given queue item.
Args:
queue_item (:class:`nyawc.QueueItem`): The request/response pair to scrape.
"""
try:
action = self.__options.callbacks.request_before_start(self.queue, queue_item)
... | 0.004704 |
def items(self):
"""
Generator returning all keys and values stored in a trie.
"""
L = []
def aux(node, s):
s = s + node.char
if node.output is not nil:
L.append((s, node.output))
for child in node.children.values():
if child is not node:
aux(child, s)
aux(self.root, '')
return it... | 0.049231 |
def iterate(self, image, feature_extractor, feature_vector):
"""iterate(image, feature_extractor, feature_vector) -> bounding_box
Scales the given image, and extracts features from all possible bounding boxes.
For each of the sampled bounding boxes, this function fills the given pre-allocated feature vect... | 0.006056 |
def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`."
sz_dict = ifnone(sz_dict, {})
n_cat = len(classes[n])
sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb
return n_cat,sz | 0.01087 |
def unsafe_ask(self, patch_stdout: bool = False) -> Any:
"""Ask the question synchronously and return user response.
Does not catch keyboard interrupts."""
if patch_stdout:
with prompt_toolkit.patch_stdout.patch_stdout():
return self.application.run()
else:
... | 0.00554 |
def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon):
# https://github.com/Tencent/ncnn/blob/master/src/layer/batchnorm.cpp
""" float sqrt_var = sqrt(var_data[i]);
a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var;
b_data[i] = slope_data[i] / sqrt_var;
...
... | 0.002096 |
def call_webhook(event, webhook, payload):
"""Build request from event,webhook,payoad and parse response."""
started_at = time()
request = _build_request_for_calling_webhook(event, webhook, payload)
logger.info('REQUEST %(uuid)s %(method)s %(url)s %(payload)s' % dict(
uuid=str(event['uuid']),
... | 0.000656 |
def queryMulti(self, queries):
"""
Execute a series of Deletes,Inserts, & Updates in the Queires List
@author: Nick Verbeck
@since: 9/7/2008
"""
self.lastError = None
self.affectedRows = 0
self.rowcount = None
self.record = None
cursor = None
try:
try:
self._GetConnection()
#Execu... | 0.045402 |
def get_platform_metadata(self, platform, build_annotations):
"""
Return the metadata for the given platform.
"""
# retrieve all the workspace data
build_info = get_worker_build_info(self.workflow, platform)
osbs = build_info.osbs
kind = "configmap/"
cml... | 0.001595 |
def _get_cgroup_measurements(self, cgroups, ru_child, result):
"""
This method calculates the exact results for time and memory measurements.
It is not important to call this method as soon as possible after the run.
"""
logging.debug("Getting cgroup measurements.")
cput... | 0.005916 |
def get_var_shape(self, name):
"""
Return shape of the array.
"""
rank = self.get_var_rank(name)
name = create_string_buffer(name)
arraytype = ndpointer(dtype='int32',
ndim=1,
shape=(MAXDIMS, ),
... | 0.003584 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.