Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
348,100 | def get_calltip(project, source_code, offset, resource=None,
maxfixes=1, ignore_unknown=False, remove_self=False):
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes)
pyname = fixer.pyname_at(offset)
if pyname is None:
return None
pyobject = pyname.get_obje... | Get the calltip of a function
The format of the returned string is
``module_name.holding_scope_names.function_name(arguments)``. For
classes `__init__()` and for normal objects `__call__()` function
is used.
Note that the offset is on the function itself *not* after the its
open parenthesis. ... |
348,101 | def import_attribute(name):
try:
sep = if in name else
module_name, attribute = name.rsplit(sep, 1)
module = importlib.import_module(module_name)
return operator.attrgetter(attribute)(module)
except (ValueError, ImportError, AttributeError) as e:
raise TaskImpor... | Return an attribute from a dotted path name (e.g. "path.to.func"). |
348,102 | def _start_trial(self, trial, checkpoint=None):
prior_status = trial.status
self.set_status(trial, Trial.RUNNING)
trial.runner = self._setup_runner(
trial,
reuse_allowed=checkpoint is not None
or trial._checkpoint.value is not None)
if not sel... | Starts trial and restores last result if trial was paused.
Raises:
ValueError if restoring from checkpoint fails. |
348,103 | def has_manifest(app, filename=):
try:
return pkg_resources.resource_exists(app, filename)
except ImportError:
return os.path.isabs(filename) and os.path.exists(filename) | Verify the existance of a JSON assets manifest |
348,104 | def fit(self, y, exogenous=None, **fit_args):
y = c1d(check_array(y, ensure_2d=False, force_all_finite=False,
copy=True, dtype=DTYPE))
n_samples = y.shape[0]
if exogenous is not None:
exogenous = check_array(exogenous, ensure_2d=True,
... | Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)
The time-series to which to fit the ``ARIMA`` estimator. This may
either be a Pandas ``Series... |
348,105 | async def send(
self,
request: Union[str, Dict, List],
trim_log_values: bool = False,
validate_against_schema: bool = True,
**kwargs: Any
) -> Response:
if isinstance(request, str):
request_text = request
request_deserialized ... | Async version of Client.send. |
348,106 | def _avoid_setuptools_zipped_egg_upgrade_issue(env, ez_setup):
if env.sys_version_info[:2] != (2, 5):
return
if not env.setuptools_zipped_egg:
return
pv_new = parse_version(ez_setup.setuptools_version())
if pv_new != parse_version(env.setuptools_version):
return
... | Avoid the setuptools self-upgrade issue.
setuptools versions prior to version 3.5.2 have a bug that can cause their
upgrade installations to fail when installing a new zipped egg distribution
over an existing zipped egg setuptools distribution with the same name.
The following Python versions ar... |
348,107 | def weighted_mse(self, dataset, n_jobs=-1):
predictions = np.zeros((len(self), len(dataset.clampings), len(dataset.setup.readouts)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, dataset.clampings, dataset.setup.readouts) for n in self)
for i, _ in ... | Returns the weighted MSE over all logical networks with respect to the given :class:`caspo.core.dataset.Dataset` object instance.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
dataset: :class:`caspo.core.dataset... |
348,108 | def register(self):
user, created = self.Model.create_account(
self._json_params)
if not created:
raise JHTTPConflict()
self.request._user = user
pk_field = user.pk_field()
headers = remember(self.request, getattr(user, pk_field))
return... | Register new user by POSTing all required data. |
348,109 | def required_for_output(inputs, outputs, connections):
required = set(outputs)
s = set(outputs)
while 1:
t = set(a for (a, b) in connections if b in s and a not in s)
if not t:
break
layer_nodes = set(x for x in t if x not in inputs)
if not layer_... | Collect the nodes whose state is required to compute the final network output(s).
:param inputs: list of the input identifiers
:param outputs: list of the output node identifiers
:param connections: list of (input, output) connections in the network.
NOTE: It is assumed that the input identifier set and... |
348,110 | def get_grade_entry_admin_session(self):
if not self.supports_grade_entry_admin():
raise errors.Unimplemented()
return sessions.GradeEntryAdminSession(runtime=self._runtime) | Gets the ``OsidSession`` associated with the grade entry administration service.
return: (osid.grading.GradeEntryAdminSession) - a
``GradeEntryAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_grade_entry_admin()`` is
... |
348,111 | def set_flags(self):
offset = self.template[]//8
self.tpl_buff = bytes_transform(self.tpl_buff, offset+1, offset+2, lambda x: self.set_flag_bit(x)) | Set flags representing generation way accordingly - commkeys are client generated, app key is server generated.
:return: |
348,112 | def modifyReject(LowLayerCompatibility_presence=0,
HighLayerCompatibility_presence=0):
a = TpPd(pd=0x3)
b = MessageType(mesType=0x13)
c = BearerCapability()
d = Cause()
packet = a / b / c / d
if LowLayerCompatibility_presence is 1:
e = LowLayerCompatibilityHdr(iei... | MODIFY REJECT Section 9.3.15 |
348,113 | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
super(KeyWrappingSpecification, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.WRA... | Read the data encoding the KeyWrappingSpecification struct and decode
it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_versio... |
348,114 | def greedy_set_cover(universe, subsets, costs):
elements = set(e for s in subsets.keys() for e in subsets[s])
if elements != universe:
return None
covered = set()
cover_sets = []
while covered != universe:
min_cost_elem_ratio = float("inf")
min_set = None
... | Approximate greedy algorithm for set-covering. Can be used on large
inputs - though not an optimal solution.
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...} |
348,115 | def _import_epublication(self, epub):
prefixed_annotation = ANNOTATION_PREFIX + epub.anotace
self._POST["P0501010__a"] = epub.ISBN
self._POST["P07012001_a"] = epub.nazev
self._POST["P07032001_e"] = epub.podnazev
self._POST["P0502010__b"] = epub.vazba
... | Fill internal property ._POST dictionary with data from EPublication. |
348,116 | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
base_estimators, kernel_cache = self._get_base_estimators(X)
out = Parallel(
n_jobs=self.n_jobs, verbose=self.ver... | Create a cross-validated model by training a model for each fold with the same model parameters |
348,117 | def device_id_to_slug(did):
try:
device_slug = IOTileDeviceSlug(did, allow_64bits=False)
except ValueError:
raise ArgumentError("Unable to recognize {} as a device id".format(did))
return str(device_slug) | Converts a device id into a correct device slug.
Args:
did (long) : A device id
did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX
Returns:
str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format
Raises:
ArgumentError: if the ... |
348,118 | def filter_for_probability(self, population: Union[pd.DataFrame, pd.Series, Index],
probability: Array, additional_key: Any=None) -> Index:
return filter_for_probability(self._key(additional_key), population, probability, self.index_map) | Decide an event outcome for each individual in a population from probabilities.
Given a population or its index and an array of associated probabilities
for some event to happen, we create and return the sub-population for whom
the event occurred.
Parameters
----------
... |
348,119 | def show(self):
if self.brightness > 0.99:
neopixel_write(self.pin, self.buf)
else:
neopixel_write(self.pin, bytearray([int(i * self.brightness) for i in self.buf])) | Shows the new colors on the pixels themselves if they haven't already
been autowritten.
The colors may or may not be showing after this function returns because
it may be done asynchronously. |
348,120 | def _extract_residues(self):
r_list = self.handle.getElementsByTagName("response")
r_data = {}
for r in r_list:
data = self._parse_residue(r)
res_id = (data[], data[], data[])
if not r_data.has_key(res_id):
... | WHAT IF puts terminal atoms in new residues at the end for some reason.. |
348,121 | def mouseMove(self, x, y):
log.debug(, x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self | Move the mouse pointer to position (x, y) |
348,122 | def get_issuers(self):
issuers = []
message_issuer_nodes = OneLogin_Saml2_Utils.query(self.document, )
if len(message_issuer_nodes) > 0:
if len(message_issuer_nodes) == 1:
issuers.append(OneLogin_Saml2_Utils.element_text(message_issuer_nodes[0]))
... | Gets the issuers (from message and from assertion)
:returns: The issuers
:rtype: list |
348,123 | def handle_set_statement_group(self, _, __, tokens: ParseResults) -> ParseResults:
self.statement_group = tokens[]
return tokens | Handle a ``SET STATEMENT_GROUP = "X"`` statement. |
348,124 | def laplacian_calculation(mesh, equal_weight=True):
neighbors = mesh.vertex_neighbors
vertices = mesh.vertices.view(np.ndarray)
col = np.concatenate(neighbors)
row = np.concatenate([[i] * len(n)
for i, n in enumerate(neighbors)])
if equal_weight:
... | Calculate a sparse matrix for laplacian operations.
Parameters
-------------
mesh : trimesh.Trimesh
Input geometry
equal_weight : bool
If True, all neighbors will be considered equally
If False, all neightbors will be weighted by inverse distance
Returns
----------
laplac... |
348,125 | def AddDateTimeRange(
self, time_value, start_time_string=None, end_time_string=None):
if not isinstance(time_value, py2to3.STRING_TYPES):
raise ValueError()
if start_time_string is None and end_time_string is None:
raise ValueError(
)
time_value_lower = time_value.lower()... | Adds a date time filter range.
The time strings are formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, seconds fraction
and timezone offset are optional. The default timezone is UTC.... |
348,126 | def compute_step(self, state, lstm_cell=None, input=None, additional_inputs=None):
if not self.initialized:
input_dim = None
if input and hasattr(input.tag, ):
input_dim = input.tag.last_dim
self.init(input_dim)
input_map = self.merge_inputs(... | Compute one step in the RNN.
:return: one variable for RNN and GRU, multiple variables for LSTM |
348,127 | def feed_interval_get(feed_id, parameters):
val = cache.get(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ))
return val if isinstance(val, tuple) else (val, None) | Get adaptive interval between checks for a feed. |
348,128 | def add_pagination_links(data, object_count, querystring, base_url):
links = {}
all_qs_args = copy(querystring.querystring)
links[] = base_url
if all_qs_args:
links[] += + urlencode(all_qs_args)
if querystring.pagination.get() != and object_count > 1:
page_siz... | Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination |
348,129 | def encode_request(name, uuid, callable, partition_id):
client_message = ClientMessage(payload_size=calculate_size(name, uuid, callable, partition_id))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_str... | Encode request into client_message |
348,130 | def items_pending_or_purchased(self):
status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]
return self._items(status) | Returns the items that this user has purchased or has pending. |
348,131 | def _get_grouper(self, obj, validate=True):
self._set_grouper(obj)
self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key],
axis=self.axis,
level=self.level,
... | Parameters
----------
obj : the subject object
validate : boolean, default True
if True, validate the grouper
Returns
-------
a tuple of binner, grouper, obj (possibly sorted) |
348,132 | def err(self, output, newline=True):
click.echo(output, nl=newline, err=True) | Outputs an error string to the console (stderr). |
348,133 | def _cached_replace_compile(pattern, repl, flags, pattern_type):
return _bregex_parse._ReplaceParser().parse(pattern, repl, bool(flags & FORMAT)) | Cached replace compile. |
348,134 | def id(self):
sigs = self.data["signatures"]
self.data.pop("signatures", None)
h = hashlib.sha256(bytes(self)).digest()
self.data["signatures"] = sigs
return hexlify(h[:20]).decode("ascii") | The transaction id of this transaction |
348,135 | def is_cython_or_generator(fn):
if hasattr(fn, "__func__"):
fn = fn.__func__
if inspect.isgeneratorfunction(fn):
return True
name = type(fn).__name__
return (
name == "generator"
or name == "method_descriptor"
or name == "cython_function_or_method"
... | Returns whether this function is either a generator function or a Cythonized function. |
348,136 | def warm(self, jittering_ratio=0.2):
if self.snapshot_to_load == None:
last_period = self.current_period - dt.timedelta(days=self.expiration-1)
self.compute_refresh_period()
self.snapshot_to_load = []
base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path... | Progressively load the previous snapshot during the day.
Loading all the snapshots at once can takes a substantial amount of time. This method, if called
periodically during the day will progressively load those snapshots one by one. Because many workers are
going to use this method at the same... |
348,137 | def get_personalities(self, line):
return [split(, i)[1] for i in line.split()[1].split() if i.startswith()] | Return a list of personalities readed from the input line. |
348,138 | def _layers_to_squash(self, layers, from_layer):
to_squash = []
to_leave = []
should_squash = True
for l in reversed(layers):
if l == from_layer:
should_squash = False
if should_squash:
to_squash.append(l)
els... | Prepares a list of layer IDs that should be squashed |
348,139 | def _init():
import importlib
import os
import re
filenames = os.listdir(os.path.dirname(__file__))
module_names = set()
for filename in filenames:
match = re.match(r, filename)
if match:
module_names.add(match.group())
for module_name in module_names:
... | Dynamically import engines that initialize successfully. |
348,140 | def pretty_str(self, indent=0):
spaces = * indent
condition = pretty_str(self.condition)
pretty = .format(spaces, condition)
pretty += self.body.pretty_str(indent=indent + 2)
if self.else_body:
pretty += .format(spaces)
pretty += self.else_body.p... | Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation. |
348,141 | def _lookup(self, timestamp):
idx = search_greater(self._values, timestamp)
if (idx < len(self._values)
and math.fabs(self._values[idx][0] - timestamp) < self.EPSILON):
return idx
return None | Return the index of the value associated with "timestamp" if any, else
None. Since the timestamps are floating-point values, they are
considered equal if their absolute difference is smaller than
self.EPSILON |
348,142 | def dump_dict(self):
dump_dict = dict()
dump_dict[] = self.name
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, (int, long)):
if key == or key == :
... | Returns a dictionary representation of the structure. |
348,143 | def vdatainfo(self, listAttr=0):
lst = []
ref = -1
while True:
try:
nxtRef = self.next(ref)
except HDF4Error:
break
ref = nxtRef
vdObj = self.attach(ref)
if listAttr or no... | Return info about all the file vdatas.
Args::
listAttr Set to 0 to ignore vdatas used to store attribute
values, 1 to list them (see the VD._isattr readonly
attribute)
Returns::
List of vdata descriptions. Each vdata is described as
... |
348,144 | async def xgroup_del_consumer(self, name: str, group: str, consumer: str) -> int:
return await self.execute_command(, name, group, consumer) | [NOTICE] Not officially released yet
XGROUP is used in order to create, destroy and manage consumer groups.
:param name: name of the stream
:param group: name of the consumer group
:param consumer: name of the consumer |
348,145 | def setup_logging(self):
is_custom_logging = len(self.options.logging_config) > 0
is_custom_logging = is_custom_logging and os.path.isfile(self.options.logging_config)
is_custom_logging = is_custom_logging and not self.options.dry_run
if is_custom_logging:
Logger.co... | Setup of application logging. |
348,146 | def _paste_using_mouse_button_2(self):
focus = self.localDisplay.get_input_focus().focus
xtest.fake_input(focus, X.ButtonPress, X.Button2)
xtest.fake_input(focus, X.ButtonRelease, X.Button2)
logger.debug("Mouse Button2 event sent.") | Paste using the mouse: Press the second mouse button, then release it again. |
348,147 | def stop(name, timeout=None, **kwargs):
s configuration
will be checked. If the container was created using the
``stop_timeout`` argument, then the configured timeout will be
used, otherwise the timeout will be 10 seconds.
**RETURN DATA**
A dictionary will be returned, ... | Stops a running container
name
Container name or ID
unpause : False
If ``True`` and the container is paused, it will be unpaused before
attempting to stop the container.
timeout
Timeout in seconds after which the container will be killed (if it has
not yet graceful... |
348,148 | def adjustMinimumWidth( self ):
pw = self.pixmapSize().width()
self.setMinimumWidth(pw * self.maximum() + 3 * self.maximum()) | Modifies the minimum width to factor in the size of the pixmaps and the
number for the maximum. |
348,149 | def complete_pbar(self):
if hasattr(self, ) and self.pbar:
self.pbar.n = len(self.nb.cells)
self.pbar.refresh() | Refresh progress bar |
348,150 | def trainRegressor(cls, data, categoricalFeaturesInfo, numTrees, featureSubsetStrategy="auto",
impurity="variance", maxDepth=4, maxBins=32, seed=None):
return cls._train(data, "regression", 0, categoricalFeaturesInfo, numTrees,
featureSubsetStrategy, imp... | Train a random forest model for regression.
:param data:
Training dataset: RDD of LabeledPoint. Labels are real numbers.
:param categoricalFeaturesInfo:
Map storing arity of categorical features. An entry (n -> k)
indicates that feature n is categorical with k categories
... |
348,151 | def add_connection_throttle(self, loadbalancer, maxConnectionRate=None,
maxConnections=None, minConnections=None, rateInterval=None):
settings = {}
if maxConnectionRate:
settings["maxConnectionRate"] = maxConnectionRate
if maxConnections:
settings["ma... | Creates or updates the connection throttling information for the load
balancer. When first creating the connection throttle, all 4 parameters
must be supplied. When updating an existing connection throttle, at
least one of the parameters must be supplied. |
348,152 | def render(self, file_path, **kwargs):
temp = get_tempfile(suffix=)
self.save_content(temp.name)
try:
self._render_function(temp.name, file_path, output_format=)
except:
log.exception(.format(file_path))
raise | Save the content of the .text file in the PDF.
Parameters
----------
file_path: str
Path to the output file. |
348,153 | def call(self, method_name: str, *args, rpc_timeout: float = None, **kwargs):
request = utils.rpc_request(method_name, *args, **kwargs)
_log.debug("Sending request: %s", request)
self._socket.send_multipart([to_msgpack(request)])
if rpc_timeout is None:
rp... | Send JSON RPC request to a backend socket and receive reply
Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async
fashion or provide your own event loop then use .async_call instead
:param method_name: Method name
:param args: Args t... |
348,154 | async def async_while(timeout, while_clause, *args):
loop = get_event_loop()
start = loop.time()
di = 0.1
interval = 0
result = while_clause(*args)
while result:
interval = min(interval+di, MAX_ASYNC_WHILE)
try:
await sleep(interval, loop=loop)
except Ti... | The asynchronous equivalent of ``while while_clause(*args):``
Use this function within a :ref:`coroutine <coroutine>` when you need
to wait ``while_clause`` to be satisfied.
:parameter timeout: a timeout in seconds after which this function stop.
:parameter while_clause: while clause callable.
:pa... |
348,155 | def save(self, *args, **kwargs):
self.type = INTERFACE_TYPES.get()
super(Ethernet, self).save(*args, **kwargs) | automatically set Interface.type to ethernet |
348,156 | def capture_on_device_name(device_name, callback):
with WinPcap(device_name) as capture:
capture.run(callback=callback) | :param device_name: the name (guid) of a device as provided by WinPcapDevices.list_devices()
:param callback: a function to call with each intercepted packet |
348,157 | def strip_querystring(url):
p = six.moves.urllib.parse.urlparse(url)
return p.scheme + "://" + p.netloc + p.path | Remove the querystring from the end of a URL. |
348,158 | def overall_f_measure(self):
if self.overall[] == 0 and self.empty_system_output_handling == :
precision = 0
else:
precision = metric.precision(
Ntp=self.overall[],
Nsys=self.overall[]
)
recall = metric.recall(
... | Overall f-measure metrics (f_measure, precision, and recall)
Returns
-------
dict
results in a dictionary format |
348,159 | def get_viewable_members(self, user=None):
members = []
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
... | Get the list of members that you have permissions to view.
Returns: List of members |
348,160 | def http_basic_auth_login_required(func=None):
wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated])
if func is None:
return wrapper
return wrapper(func) | Decorator. Use it to specify a RPC method is available only to logged users |
348,161 | def dependencies_of(self, address):
assert address in self._target_by_address, (
.format(address=address)
)
return self._target_dependencies_by_address[address] | Returns the dependencies of the Target at `address`.
This method asserts that the address given is actually in the BuildGraph.
:API: public |
348,162 | def find_one(self, filter=None):
if self.table is None:
self.build_table()
allcond = self.parse_query(filter)
return self.table.get(allcond) | Finds one matching query element
:param query: dictionary representing the mongo query
:return: the resulting document (if found) |
348,163 | def triggers(self):
self._triggers, value = self.get_attr_set(self._triggers, )
return value | Returns a list of available triggers. |
348,164 | def find_command(self, argv):
search_args = argv[:]
name =
while search_args:
if search_args[0].startswith():
name = % (name, search_args[0])
raise ValueError( % name)
next_val = search_args.pop(0)
name = % (name, ne... | Given an argument list, find a command and
return the processor and any remaining arguments. |
348,165 | def _remove_dupes(self, phonetic):
alt_string = phonetic
alt_array = alt_string.split()
result =
for i in range(len(alt_array)):
alt = alt_array[i]
if alt and + alt + not in result:
result += alt +
return result[1:-1] | Remove duplicates from a phonetic encoding list.
Parameters
----------
phonetic : str
A Beider-Morse phonetic encoding
Returns
-------
str
A Beider-Morse phonetic code |
348,166 | def get_template_context_processors(exclude=(), append=(),
current={: TEMPLATE_CONTEXT_PROCESSORS}):
current[] = tuple(
[p for p in current[] if p not in exclude]
) + tuple(append)
return current[] | Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in
exclude and with the processors listed in append.
The use of a mutable dict is intentional, in order to preserve the state of
the TEMPLATE_CONTEXT_PROCESSORS tuple across multiple settings files. |
348,167 | def create_prediction_estimator(hyper_params, model, checkpoint_path=None):
if checkpoint_path is None:
chkpts = sorted([name for name in os.listdir(hyper_params.train.checkpoint_path)])
checkpoint_path = hyper_params.train.checkpoint_path + "/" + chkpts[-1]
print("Latest found checkpoi... | Create an estimator for prediction purpose only.
:param hyper_params: The hyper params file.
:param model: The keras model.
:param checkpoint_path: (Optional) Path to the specific checkpoint to use.
:return: |
348,168 | async def x_get_ics_statistics(self) -> Tuple[int, int, int, int, str, str]:
return await self.gateway.commands.X_GetICSStatistics() | Returns (TotalBytesSent, TotalBytesReceived, TotalPacketsSent, TotalPacketsReceived, Layer1DownstreamMaxBitRate, Uptime) |
348,169 | def subscribed(self, user):
for who, record in self.logs:
if (record["field_name"] == "cc" and
user.email in record["added"]):
return True
return False | True if CC was added in given time frame |
348,170 | def get_enabled_browsers():
global _enabled_browsers_cache
if _enabled_browsers_cache is not None:
return _enabled_browsers_cache
enabled = []
for browser_path in settings.ADMINFILES_BROWSER_VIEWS:
try:
view_class = import_browser(browser_path)
except ImportError... | Check the ADMINFILES_BROWSER_VIEWS setting and return a list of
instantiated browser views that have the necessary
dependencies/configuration to run. |
348,171 | def _visited_callback(self, state, pc, instr):
pc = state.platform.current.PC
with self.locked_context(, dict) as ctx:
ctx[pc] = ctx.get(pc, 0) + 1 | Maintain our own copy of the visited set |
348,172 | def _dask_array_with_chunks_hint(array, chunks):
import dask.array as da
if len(chunks) < array.ndim:
raise ValueError()
new_chunks = []
for chunk, size in zip(chunks, array.shape):
new_chunks.append(chunk if size > 1 else (1,))
return da.from_array(array, new_chunks) | Create a dask array using the chunks hint for dimensions of size > 1. |
348,173 | def check_file_version(file):
from distutils.version import StrictVersion as Version
try:
ver = file.attrs.get(, None)
if ver is None:
ver = file.attrs[]
except KeyError:
raise UserWarning(
"Unable to determine ARF version for {0.filename};"
"... | Check the ARF version attribute of file for compatibility.
Raises DeprecationWarning for backwards-incompatible files, FutureWarning
for (potentially) forwards-incompatible files, and UserWarning for files
that may not have been created by an ARF library.
Returns the version for the file |
348,174 | def iter_trigger(self, iter_wave_values):
window_size = (2 * self.cfg.END_COUNT) + self.cfg.MID_COUNT
pos_null_transit = [(0, self.cfg.END_COUNT), (self.cfg.END_COUNT, 0)]
neg_null_transit = [(self.cfg.END_COUNT, 0), (0, self.cfg.END_COUNT)]
if self.cfg.MID_... | trigger middle crossing of the wave sinus curve |
348,175 | def getSequence(self, level=0):
seq = []
op =
left_operand = None
right_operand = None
sequence_closed = False
while True:
c = self.next()
if not c:
break
if c and c not in self.meta_chars:
seq... | Get a sequence of nodes. |
348,176 | def set_mode_send(self, target_system, base_mode, custom_mode, force_mavlink1=False):
return self.send(self.set_mode_encode(target_system, base_mode, custom_mode), force_mavlink1=force_mavlink1) | THIS INTERFACE IS DEPRECATED. USE COMMAND_LONG with
MAV_CMD_DO_SET_MODE INSTEAD. Set the system mode, as
defined by enum MAV_MODE. There is no target component
id as the mode is by definition for the overall
aircraft, not only for one component.
... |
348,177 | def parse_cron_line(self, line):
stripped = line.strip()
if stripped and stripped.startswith() is False:
rexres = self.rex.search(stripped)
if rexres:
return .join(rexres.group(1).split())
return None | Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line |
348,178 | def release_all(self, keys: Sequence[str]) -> Set[str]:
released: List[str] = []
for key in keys:
released.append(self.release(key))
return set(filter(None,released)) | Releases all of the given keys.
:param keys: the keys to release
:return: the names of the keys that were released |
348,179 | def _reduce_nbest_translations(nbest_translations_list: List[Translation]) -> Translation:
best_translation = nbest_translations_list[0]
sequences = [translation.target_ids for translation in nbest_translations_list]
attention_matrices = [translation.attention_matrix for translation in nbest_translati... | Combines Translation objects that are nbest translations of the same sentence.
:param nbest_translations_list: A list of Translation objects, all of them translations of
the same source sentence.
:return: A single Translation object where nbest lists are collapsed. |
348,180 | def add_package_dependency(self, package_name, version):
if not PEP440_VERSION_PATTERN.match(version):
raise ValueError(.format(version))
self.dependencies.add(PackageDependency(package_name, version)) | Add a package to the list of dependencies.
:param package_name: The name of the package dependency
:type package_name: str
:param version: The (minimum) version of the package
:type version: str |
348,181 | def init_app(self, app):
self.init_config(app.config)
state = _InvenioMigratorState(app)
app.extensions[] = state
app.cli.add_command(dumps)
return state | Flask application initialization. |
348,182 | def countPrint(mesg, count, len1, len2=None):
def percentage(a, b):
return 100.0 * a / b if b else 0.0
if count == 0:
return % (mesg, count)
else:
len2 = len2 or len1
if len1 == len2:
return % (
mesg, count, len1, percentage(count,... | Format a message followed by an integer count and a percentage (or
two, if the sequence lengths are unequal).
@param mesg: a C{str} message.
@param count: a numeric value.
@param len1: the C{int} length of sequence 1.
@param len2: the C{int} length of sequence 2. If C{None}, will
default to... |
348,183 | def hist_file(ticker: str, dt, typ=) -> str:
data_path = os.environ.get(assist.BBG_ROOT, ).replace(, )
if not data_path: return
asset = ticker.split()[-1]
proper_ticker = ticker.replace(, )
cur_dt = pd.Timestamp(dt).strftime()
return f | Data file location for Bloomberg historical data
Args:
ticker: ticker name
dt: date
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Returns:
file location
Examples:
>>> os.environ['BBG_ROOT'] = ''
>>> hist_file(ticker='ES1 Index', dt='2018-08... |
348,184 | def remember(self, chain=-1, trace_index=None):
if trace_index is None:
trace_index = randint(self._cur_trace_index)
for variable in self._variables_to_tally:
if isinstance(variable, Stochastic):
try:
variable.value = self.trace(
... | remember(chain=-1, trace_index = randint(trace length to date))
Sets the value of all tracing variables to a value recorded in
their traces. |
348,185 | def on_train_begin(self, **kwargs:Any)->None:
"Initialize inner arguments."
self.wait, self.opt = 0, self.learn.opt
super().on_train_begin(**kwargs) | Initialize inner arguments. |
348,186 | def layout_filename(fallback):
global display_size
global vehiclename
(dw,dh) = display_size
if in os.environ:
dirname = os.path.join(os.environ[], ".mavproxy")
if not os.path.exists(dirname):
try:
os.mkdir(dirname)
except Exception:
... | get location of layout file |
348,187 | def render(source, target, context, owner=, group=,
perms=0o444, templates_dir=None, encoding=,
template_loader=None, config_template=None):
try:
from jinja2 import FileSystemLoader, Environment, exceptions
except ImportError:
try:
from charmhelpers.fetch i... | Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template m... |
348,188 | def make_sentence_with_start(self, beginning, strict=True, **kwargs):
split = tuple(self.word_split(beginning))
word_count = len(split)
if word_count == self.state_size:
init_states = [ split ]
elif word_count > 0 and word_count < self.state_size:
if st... | Tries making a sentence that begins with `beginning` string,
which should be a string of one to `self.state` words known
to exist in the corpus.
If strict == True, then markovify will draw its initial inspiration
only from sentences that start with the specified word/phrase.
... |
348,189 | def get_last(self, n=1):
rows = []
if self.tracker.dbcon_part and check_table_exists(self.tracker.dbcon_part, self.name):
rows.extend(get_last_row(self.tracker.dbcon_part, self.name, n))
if len(rows) < n and check_table_exists(self.tracker.dbcon_master, sel... | Retrieve the last n rows from the table
:param n: number of rows to return
:return: list of rows |
348,190 | def _do_layout(self):
dialog_main_sizer = wx.BoxSizer(wx.HORIZONTAL)
upper_sizer = wx.BoxSizer(wx.HORIZONTAL)
lower_sizer = wx.FlexGridSizer(2, 1, 5, 0)
lower_sizer.AddGrowableRow(0)
lower_sizer.AddGrowableCol(0)
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
... | Layout sizers |
348,191 | def truncate(when, unit, week_start=mon):
if is_datetime(when):
if unit == millisecond:
return when.replace(microsecond=int(round(when.microsecond / 1000.0)) * 1000)
elif unit == second:
return when.replace(microsecond=0)
elif unit == minute:
return w... | Return the datetime truncated to the precision of the provided unit. |
348,192 | def show_info(self):
sender = self.sender()
tree = sender.parent()
index = tree.selectedIndexes()
info =
if index != []:
index = index[0]
name = str(index.model().itemFromIndex(index).text())
self.selected_element_name = name
... | displays the doc string of the selected element |
348,193 | def name(self):
doc = self.get_main_doc()
headerwords = doc()[0].text_content().split()
lastIdx = headerwords.index()
teamwords = headerwords[:lastIdx]
return .join(teamwords) | Returns the real name of the franchise given the team ID.
Examples:
'nwe' -> 'New England Patriots'
'sea' -> 'Seattle Seahawks'
:returns: A string corresponding to the team's full name. |
348,194 | def download_url(url, content_type=None, download_to_file=None,
retry_count=10, timeout=10.0):
if not download_to_file:
download_to_file = safe_mkstemp(suffix=".tmp",
prefix="filedownloadutils_")
try:
if is_url_a_local_file(url):
... | Will download a file from given URL (either local or external) to the
desired path (or generate one if none is given). Local files are copied
directly.
The function will retry a number of times based on retry_count (default 10)
parameter and sleeps a number of seconds based on given timeout
(defaul... |
348,195 | def calc_ifft_with_PyCUDA(Signalfft):
print("starting ifft")
Signalfft = Signalfft.astype(_np.complex64)
Signalfft_gpu = _gpuarray.to_gpu(Signalfft[0:len(Signalfft)//2+1])
Signal_gpu = _gpuarray.empty(len(Signalfft),_np.float32)
plan = _Plan(len(Signalfft),_np.complex64,_np.float32)
_ifft(S... | Calculates the inverse-FFT of the passed FFT-signal by
using the scikit-cuda libary which relies on PyCUDA
Parameters
----------
Signalfft : ndarray
FFT-Signal to be transformed into Real space
Returns
-------
Signal : ndarray
Array containing the ifft signal |
348,196 | def get_referenced_object_as_list(
prev_obj, obj, dot_separated_name, desired_type=None):
res = get_referenced_object(prev_obj, obj, dot_separated_name,
desired_type)
if res is None:
return []
elif type(res) is list:
return res
else:
r... | Same as get_referenced_object, but always returns a list.
Args:
prev_obj: see get_referenced_object
obj: see get_referenced_object
dot_separated_name: see get_referenced_object
desired_type: see get_referenced_object
Returns:
same as get_referenced_object, but always re... |
348,197 | def delete(self, *args, **kwargs):
from bakery import tasks
from django.contrib.contenttypes.models import ContentType
unpublish = kwargs.pop(, True)
super(AutoPublishingBuildableModel, self).delete(*args, **kwargs)
if unpublish:
ct = Conten... | Triggers a task that will unpublish the object after it is deleted.
Save with keyword argument obj.delete(unpublish=False) to skip it. |
348,198 | def DbPutProperty(self, argin):
self._log.debug("In DbPutProperty()")
object_name = argin[0]
nb_properties = int(argin[1])
self.db.put_property(object_name, properties, argin[2:]) | Create / Update free object property(ies)
:param argin: Str[0] = Object name
Str[1] = Property number
Str[2] = Property name
Str[3] = Property value number
Str[4] = Property value 1
Str[n] = Property value n
....
:type: tango.DevVarStringArray
:re... |
348,199 | def receives(self, idA, idB):
objA = self.chart.get(idA)
objB = self.chart.get(idB)
asp = aspects.isAspecting(objB, objA, const.MAJOR_ASPECTS)
return self.inDignities(idB, idA) if asp else [] | Returns the dignities where A receives B.
A receives B when (1) B aspects A and (2) B is in
dignities of A. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.