Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
373,300 | def edit_inputs(client, workflow):
types = {
: int,
: str,
: lambda x: File(path=Path(x).resolve()),
}
for input_ in workflow.inputs:
convert = types.get(input_.type, str)
input_.default = convert(
click.prompt(
.format(input_),
... | Edit workflow inputs. |
373,301 | def emit(self, action, payload=None, retry=0):
payload = payload or {}
if retry:
_retry = self.transport.retry(retry)
emit = _retry(self.transport.emit)
else:
emit = self.transport.emit
return emit(action, payload) | Emit action with payload.
:param action: an action slug
:param payload: data, default {}
:param retry: integer, default 0.
:return: information in form of dict. |
373,302 | def _load_image_labels(self):
temp = []
for idx in self.image_set_index:
label_file = self._label_path_from_index(idx)
tree = ET.parse(label_file)
root = tree.getroot()
size = root.find()
width = float(size.find().text)
... | preprocess all ground-truths
Returns:
----------
labels packed in [num_images x max_num_objects x 5] tensor |
373,303 | def hierarchy_spectrum(mg, filter=True, plot=False):
real_table = [[, , , ,
, ]]
imag_table = [[, , , ,
, ]]
for i in range(len(mg.levels)):
A = mg.levels[i].A.tocsr()
if filter is True:
A.eliminate_zeros()
nnz... | Examine a multilevel hierarchy's spectrum.
Parameters
----------
mg { pyamg multilevel hierarchy }
e.g. generated with smoothed_aggregation_solver(...) or
ruge_stuben_solver(...)
Returns
-------
(1) table to standard out detailing the spectrum of each level in mg
(2) if plo... |
373,304 | def assert_image_exists(self, pattern, timeout=20.0, **kwargs):
pattern = self.d.pattern_open(pattern)
match_kwargs = kwargs.copy()
match_kwargs.pop(, None)
match_kwargs.update({
: timeout,
: True,
})
res = self.d.wait(pattern, **match_kwa... | Assert if image exists
Args:
- pattern: image filename # not support pattern for now
- timeout (float): seconds
- safe (bool): not raise assert error even throung failed. |
373,305 | def validate_unit_process_ids(self, expected, actual):
self.log.debug()
self.log.debug(.format(expected))
self.log.debug(.format(actual))
if len(actual) != len(expected):
return (
.format(len(expected), len(actual)))
for (e_sentry, e_pro... | Validate process id quantities for services on units. |
373,306 | def snmp_server_community_ipv4_acl(self, **kwargs):
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
community = ET.SubElement(snmp_server, "community")
community_key = ET.SubElement(community, "community... | Auto Generated Code |
373,307 | def convert_cifar10(directory, output_directory,
output_filename=):
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode=)
input_file = os.path.join(directory, DISTRIBUTION_FILE)
tar_file = tarfile.open(input_file, )
train_batch... | Converts the CIFAR-10 dataset to HDF5.
Converts the CIFAR-10 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR10`. The converted dataset is saved as
'cifar10.hdf5'.
It assumes the existence of the following file:
* `cifar-10-python.tar.gz`
Parameters
----------
d... |
373,308 | def functions(self):
out = {}
for key in self._func_names:
out[key[len(self._prefix):]] = getattr(self, key)
return out | Returns a dictionary containing the functions defined in this
object. The keys are function names (as exposed in templates)
and the values are Python functions. |
373,309 | def delete(self, request, key):
request.DELETE = http.QueryDict(request.body)
email_addr = request.DELETE.get()
user_id = request.DELETE.get()
if not email_addr:
return http.HttpResponseBadRequest()
try:
email = EmailAddressValidation.objects.g... | Remove an email address, validated or not. |
373,310 | def make_owner(user):
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save() | Makes the given user a owner and tutor. |
373,311 | def keystoneclient(request, admin=False):
client_version = VERSIONS.get_active_version()
user = request.user
token_id = user.token.id
if is_multi_domain_enabled():
if is_domain_admin(request):
domain_token = request.session.get()
if domain_token:
... | Returns a client connected to the Keystone backend.
Several forms of authentication are supported:
* Username + password -> Unscoped authentication
* Username + password + tenant id -> Scoped authentication
* Unscoped token -> Unscoped authentication
* Unscoped token + tenant id ->... |
373,312 | def transitive_subgraph_of_addresses_bfs(self,
addresses,
predicate=None,
dep_predicate=None):
walk = self._walk_factory(dep_predicate)
ordered_closure = OrderedSet()
to_wal... | Returns the transitive dependency closure of `addresses` using BFS.
:API: public
:param list<Address> addresses: The closure of `addresses` will be walked.
:param function predicate: If this parameter is not given, no Targets will be filtered
out of the closure. If it is given, any Target which fai... |
373,313 | def lookup(self):
if self.domain:
if self.subdomain:
self.domain_unsplit = % (self.subdomain, self.domain)
else:
self.domain_unsplit = self.domain
self.domain_requested = self.domain_unsplit
cache_key = % ... | The meat of this middleware.
Returns None and sets settings.SITE_ID if able to find a Site
object by domain and its subdomain is valid.
Returns an HttpResponsePermanentRedirect to the Site's default
subdomain if a site is found but the requested subdomain
is not supported, or i... |
373,314 | def kvlclient(self):
if self._kvlclient is None:
self._kvlclient = kvlayer.client()
return self._kvlclient | Return a thread local ``kvlayer`` client. |
373,315 | def connection_lost(self, exc=None):
if self._loop.get_debug():
self.producer.logger.debug(, self)
self.event().fire(exc=exc) | Fires the ``connection_lost`` event. |
373,316 | def _iteratively_analyze_function_features(self, all_funcs_completed=False):
changes = {
: set(),
: set()
}
while True:
new_changes = self._analyze_function_features(all_funcs_completed=all_funcs_completed)
changes[] |= set(new_changes[... | Iteratively analyze function features until a fixed point is reached.
:return: the "changes" dict
:rtype: dict |
373,317 | def read(self, size=None):
if not self._is_open:
raise IOError()
if self._current_offset < 0:
raise IOError(
.format(
self._current_offset))
if self._decrypted_stream_size is None:
self._decrypted_stream_size = self._GetDecryptedStreamSize()
if self._dec... | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
... |
373,318 | def ping():
try:
response = salt.utils.http.query(
"{0}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type=,
decode=True,
)
log.debug(
,
response,
)
if in response and response[].strip() == :
return... | Is the marathon api responding? |
373,319 | def corrcoef(time, crossf, integration_window=0.):
N = len(crossf)
cc = np.zeros(np.shape(crossf)[:-1])
tbin = abs(time[1] - time[0])
lim = int(integration_window / tbin)
if len(time)%2 == 0:
mid = len(time)/2-1
else:
mid = np.floor(len(time)/2.)
for i in rang... | Calculate the correlation coefficient for given auto- and crosscorrelation
functions. Standard settings yield the zero lag correlation coefficient.
Setting integration_window > 0 yields the correlation coefficient of
integrated auto- and crosscorrelation functions. The correlation coefficient
between a ... |
373,320 | def delete(handler, item_id, id_name):
data = {: ,
: item_id,
: id_name}
handler.invoke(data) | Delete an item |
373,321 | def _createStructure(self, linkResult, replaceParamFile):
WEIRS = (, )
CULVERTS = (, )
CURVES = (, , )
header = linkResult[]
link = StreamLink(linkNumber=header[],
type=linkResult[],
numElements=he... | Create GSSHAPY Structure Objects Method |
373,322 | def check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta_df, col_meta_df):
(row_type, row_ids) = check_id_idx_exclusivity(rid, ridx)
(col_type, col_ids) = check_id_idx_exclusivity(cid, cidx)
row_ids = check_and_convert_ids(row_type, row_ids, row_meta_df)
ordered_ridx = get_ordered_idx(row_type... | Makes sure that (if entered) id inputs entered are of one type (string id or index)
Input:
- rid (list or None): if not None, a list of rids
- ridx (list or None): if not None, a list of indexes
- cid (list or None): if not None, a list of cids
- cidx (list or None): if not None, a l... |
373,323 | def median_date(dt_list):
idx = len(dt_list)/2
if len(dt_list) % 2 == 0:
md = mean_date([dt_list[idx-1], dt_list[idx]])
else:
md = dt_list[idx]
return md | Calcuate median datetime from datetime list |
373,324 | def set_datastore_policy(self, func):
if func is None:
func = self.default_datastore_policy
elif isinstance(func, bool):
func = lambda unused_key, flag=func: flag
self._datastore_policy = func | Set the context datastore policy function.
Args:
func: A function that accepts a Key instance as argument and returns
a bool indicating if it should use the datastore. May be None. |
373,325 | def _decode_png(self, encoded_observation):
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) | Decodes a single observation from PNG. |
373,326 | def postprocess(options):
resdir = options.resdir
out_file = options.outfile
tol = options.tol
print()
file_name = os.path.join(resdir,,)
files = glob.glob(file_name)
LLR0 = []
for _file in files:
print(_file)
LLR0.append(NP.loadtxt(_file,usecols=[6]))
LLR0 = N... | perform parametric fit of the test statistics and provide permutation and test pvalues |
373,327 | def fig_height(self):
return (
4
+ len(self.data) * len(self.var_names)
- 1
+ 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator())
) | Figure out the height of this plot. |
373,328 | def abort(self):
if (self.reply and self.reply.isRunning()):
self.on_abort = True
self.reply.abort() | Handle request to cancel HTTP call |
373,329 | async def read(cls, id: int):
data = await cls._handler.read(id=id)
return cls(data) | Get `BootResource` by `id`. |
373,330 | def _gen_glob_data(dir, pattern, child_table):
dir = pathlib.Path(dir)
matched = False
used_names = set()
for filepath in sorted(dir.glob(pattern)):
if filepath.is_dir():
continue
else:
matched = True
node_table = {} if child_table is... | Generates node data by globbing a directory for a pattern |
373,331 | def getCell(self, row, width=None):
cellval = wrapply(self.getValue, row)
typedval = wrapply(self.type, cellval)
if isinstance(typedval, TypedWrapper):
if isinstance(cellval, TypedExceptionWrapper):
exc = cellval.exception
if cellval.forwar... | Return DisplayWrapper for displayable cell value. |
373,332 | def write_document(document, out, validate=True):
if validate:
messages = []
messages = document.validate(messages)
if messages:
raise InvalidDocumentError(messages)
writer = Writer(document, out)
writer.write() | Write an SPDX RDF document.
- document - spdx.document instance.
- out - file like object that will be written to.
Optionally `validate` the document before writing and raise
InvalidDocumentError if document.validate returns False. |
373,333 | def get_file_size(filename):
if os.path.isfile(filename):
return convert_size(os.path.getsize(filename))
return None | Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize |
373,334 | def ladder_length(begin_word, end_word, word_list):
if len(begin_word) != len(end_word):
return -1
if begin_word == end_word:
return 0
if sum(c1 != c2 for c1, c2 in zip(begin_word, end_word)) == 1:
return 1
begin_set = set()
end_set = set()
begin_set.add(b... | Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int |
373,335 | def get_queryset(self, request):
if not request.user.has_perm():
queryset = self.model.objects.filter(authors__pk=request.user.pk)
else:
queryset = super(EntryAdmin, self).get_queryset(request)
return queryset.prefetch_related(, , ) | Make special filtering by user's permissions. |
373,336 | def odata_converter(data, str_type):
if not str_type:
return _str(data)
if str_type in ["Edm.Single", "Edm.Double"]:
return float(data)
elif "Edm.Int" in str_type:
return int(data)
else:
return _str(data) | Convert odata type
http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem
To be completed |
373,337 | def action_log_create(sender, instance, created, **kwargs):
if created:
changes = model_instance_diff(None, instance)
log_entry = LogAction.objects.create_log_action(
instance=instance,
action=LogAction.CREATE,
changes=json.dumps(changes),
) | Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. |
373,338 | def press_button(self, value):
button = find_button(world.browser, value)
if not button:
raise AssertionError(
"Cannot find a button named .".format(value))
button.click() | Click the button with the given label. |
373,339 | def validateAuthCode(code, redirect_uri, client_id, state=None, validationEndpoint=, headers={}):
payload = {: code,
: redirect_uri,
: client_id,
}
if state is not None:
payload[] = state
authURL = None
authEndpoints = discoverAuthEndp... | Call authorization endpoint to validate given auth code.
:param code: the auth code to validate
:param redirect_uri: redirect_uri for the given auth code
:param client_id: where to find the auth endpoint for the given auth code
:param state: state for the given auth code
:param validationEndpoint: ... |
373,340 | def terminate(self):
logger.info(__(
"Terminating Resolwe listener on channel .",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
self._should_stop = True | Stop the standalone manager. |
373,341 | def get(self, name_or_klass):
if not isinstance(name_or_klass, str):
name_or_klass = name_or_klass.__name__
return self._modes[name_or_klass] | Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode |
373,342 | def reactToAMQPMessage(message, send_back):
_hnas_protection()
if _instanceof(message, SaveRequest):
if _instanceof(message.record, Tree):
tree_handler().add_tree(message.record)
return TreeInfo(
path=message.record.path,
url_by_pat... | React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
:mod:`.structures`.
send_back (fn reference)... |
373,343 | def stats_enabled(self, value):
if value:
self.statistics.enable()
else:
self.statistics.disable() | Setter method; for a description see the getter method. |
373,344 | def get_endpoint_server_root(self):
parsed = urlparse(self._endpoint)
root = parsed.scheme + "://" + parsed.hostname
if parsed.port is not None:
root += ":" + unicode(parsed.port)
return root | Parses RemoteLRS object's endpoint and returns its root
:return: Root of the RemoteLRS object endpoint
:rtype: unicode |
373,345 | def construct_txt_file(self):
textlines = [ % self.mol.pymol_name.upper(), ]
textlines.append("=" * len(textlines[0]))
textlines.append( % (time.strftime("%Y/%m/%d"), __version__))
textlines.append()
textlines.append()
textlines.append()
if len(self.exclu... | Construct the header of the txt file |
373,346 | def matrixplot(adata, var_names, groupby=None, use_raw=None, log=False, num_categories=7,
figsize=None, dendrogram=False, gene_symbols=None, var_group_positions=None, var_group_labels=None,
var_group_rotation=None, layer=None, standard_scale=None, swap_axes=False, show=None,
... | \
Creates a heatmap of the mean expression values per cluster of each var_names
If groupby is not given, the matrixplot assumes that all data belongs to a single
category.
Parameters
----------
{common_plot_args}
standard_scale : {{'var', 'group'}}, optional (default: None)
Whether ... |
373,347 | def get_forms(self):
forms = {}
objects = self.get_objects()
initial = self.get_initial()
form_kwargs = self.get_form_kwargs()
for key, form_class in six.iteritems(self.form_classes):
forms[key] = form_class(instance=objects[key], initial=initial[key], **form... | Initializes the forms defined in `form_classes` with initial data from `get_initial()`,
kwargs from get_form_kwargs() and form instance object from `get_objects()`. |
373,348 | def draw_bars(out_value, features, feature_type, width_separators, width_bar):
rectangle_list = []
separator_list = []
pre_val = out_value
for index, features in zip(range(len(features)), features):
if feature_type == :
left_bound = float(features[0])
right_boun... | Draw the bars and separators. |
373,349 | def reduce_object_file_names(self, dirn):
py_so_files = shprint(sh.find, dirn, , )
filens = py_so_files.stdout.decode().split()[:-1]
for filen in filens:
file_dirname, file_basename = split(filen)
parts = file_basename.split()
if len(parts) <= 2:
... | Recursively renames all files named XXX.cpython-...-linux-gnu.so"
to "XXX.so", i.e. removing the erroneous architecture name
coming from the local system. |
373,350 | def restore(ctx, filename):
filename = filename or background_path
if not os.path.isfile(filename):
LOG.warning("File {} does not exist. Please point to a valid file".format(filename))
ctx.abort()
call = [, , , , .format(filename)]
LOG.info(, filename)
start_time = dat... | Restore the database from a zipped file.
Default is to restore from db dump in loqusdb/resources/ |
373,351 | def get_bearing(origin_point, destination_point):
if not (isinstance(origin_point, tuple) and isinstance(destination_point, tuple)):
raise TypeError()
lat1 = math.radians(origin_point[0])
lat2 = math.radians(destination_point[0])
diff_lng = math.radians(destination_point[1] - origin_... | Calculate the bearing between two lat-long points. Each tuple should
represent (lat, lng) as decimal degrees.
Parameters
----------
origin_point : tuple
destination_point : tuple
Returns
-------
bearing : float
the compass bearing in decimal degrees from the origin point
... |
373,352 | def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->:
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if valid_pct==0.: return self.split_none()
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation... | Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed. |
373,353 | def _proxy(self):
if self._context is None:
self._context = SyncListContext(
self._version,
service_sid=self._solution[],
sid=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListContext for this SyncListInstance
:rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext |
373,354 | def scan_keys(self, match=None, count=None):
cursor = 0
while True:
cursor, keys = self.connection.scan(cursor, match=match, count=count)
for key in keys:
yield key
if not cursor or cursor == :
break | Take a pattern expected by the redis `scan` command and iter on all matching keys
Parameters
----------
match: str
The pattern of keys to look for
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
... |
373,355 | def _quote(data):
data = data.replace(b, b)
data = data.replace(b, b)
return data | Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with '"' and "\\" escaped using "\\".
:returntype: `bytes` |
373,356 | def ipv6_range_to_list(start_packed, end_packed):
new_list = list()
start = int(binascii.hexlify(start_packed), 16)
end = int(binascii.hexlify(end_packed), 16)
for value in range(start, end + 1):
high = value >> 64
low = value & ((1 << 64) - 1)
new_ip = inet_ntop(socket.AF_... | Return a list of IPv6 entries from start_packed to end_packed. |
373,357 | def ReleaseSW(self):
while self.ReadStatusBit(2) == 1:
spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1))
while self.IsBusy():
pass
self.MoveWait(10) | Go away from Limit Switch |
373,358 | def fix_e112(self, result):
line_index = result[] - 1
target = self.source[line_index]
if not target.lstrip().startswith():
return []
self.source[line_index] = self.indent_word + target | Fix under-indented comments. |
373,359 | def status(url="http://127.0.0.1/status"):
resp = _urlopen(url)
status_data = resp.read()
resp.close()
lines = status_data.splitlines()
if not len(lines) == 4:
return
active_connections = lines[0].split()[2]
accepted, handled, requests = lines[2].split()
... | Return the data from an Nginx status page as a dictionary.
http://wiki.nginx.org/HttpStubStatusModule
url
The URL of the status page. Defaults to 'http://127.0.0.1/status'
CLI Example:
.. code-block:: bash
salt '*' nginx.status |
373,360 | def fit(self, inputs=None, wait=True, logs=True, job_name=None):
self._prepare_for_training(job_name=job_name)
self.latest_training_job = _TrainingJob.start_new(self, inputs)
if wait:
self.latest_training_job.wait(logs=logs) | Train a model using the input training dataset.
The API calls the Amazon SageMaker CreateTrainingJob API to start model training.
The API uses configuration you provided to create the estimator and the
specified input training data to send the CreatingTrainingJob request to Amazon SageMaker.
... |
373,361 | def dcshift(self, shift=0.0):
if not is_number(shift) or shift < -2 or shift > 2:
raise ValueError()
effect_args = [, .format(shift)]
self.effects.extend(effect_args)
self.effects_log.append()
return self | Apply a DC shift to the audio.
Parameters
----------
shift : float
Amount to shift audio between -2 and 2. (Audio is between -1 and 1)
See Also
--------
highpass |
373,362 | def options(self, parser, env):
parser.add_option(,
action=,
dest=self.enableOpt,
default=env.get(),
help="Enable collect-only: %s [COLLECT_ONLY]" %
(self.help())) | Register commandline options. |
373,363 | def gridmake(*arrays):
if all([i.ndim == 1 for i in arrays]):
d = len(arrays)
if d == 2:
out = _gridmake2(*arrays)
else:
out = _gridmake2(arrays[0], arrays[1])
for arr in arrays[2:]:
out = _gridmake2(out, arr)
return out
e... | Expands one or more vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
*arrays : tuple/list of np.ndarray
Tuple/list of... |
373,364 | def _process_dependencies(self, anexec, contents, mode="insert"):
for dmatch in self.RE_DEPEND.finditer(contents):
isSubroutine = dmatch.group("sub") is not None
if "!" in dmatch.group("exec"):
execline = self._depend_exec_clean(dmatch.... | Extracts a list of subroutines and functions that are called from
within this executable.
:arg mode: specifies whether the matches should be added, removed
or merged into the specified executable. |
373,365 | def stop(self):
with self.synclock:
if self.syncthread is not None:
self.syncthread.cancel()
self.syncthread = None | Stops the background synchronization thread |
373,366 | def addLogicalInterfaceToDeviceType(self, typeId, logicalInterfaceId):
req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, "/draft", typeId)
body = {"id" : logicalInterfaceId}
resp = requests.post(req, auth=self.credentials, headers={"Content-Type":"application/json"}, da... | Adds a logical interface to a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
- description (string) - optional (not used)
Throws APIException on failure. |
373,367 | def create_tag(self, tags):
if isinstance(tags, str):
tags = [tags]
evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=False)
self._client._wait_and_except_if_failed(evt) | Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters
and the underscore. Tags will be stored lower-cased.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects ... |
373,368 | def joinCommissioned(self, strPSKd=, waitTime=20):
print % self.port
self.__sendCommand()
cmd = %(strPSKd, self.provisioningUrl)
print cmd
if self.__sendCommand(cmd)[0] == "Done":
maxDuration = 150
self.joinCommissionedStatus = self.joinStatus[... | start joiner
Args:
strPSKd: Joiner's PSKd
Returns:
True: successful to start joiner
False: fail to start joiner |
373,369 | def python_2_unicode_compatible(klass):
if sys.version_info[0] == 2:
if not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesnutf-8')
return klass | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
From django.utils.encoding.py in 1.4.2+, minus the dependency on Six.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class... |
373,370 | def __check(self, decorated_function, *args, **kwargs):
if len(args) >= 1:
obj = args[0]
function_name = decorated_function.__name__
if hasattr(obj, function_name) is True:
fn = getattr(obj, function_name)
if callable(fn) and fn.__self__ == obj:
return
raise RuntimeError() | Check whether function is a bounded method or not. If check fails then exception is raised
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None |
373,371 | def tokenizer(text):
stream = deque(text.split("\n"))
while len(stream) > 0:
line = stream.popleft()
if line.startswith("
yield KeyValue("
yield KeyValue("HEADER", line)
for identifier in line.split(" "):
if ":" in identifier:
... | A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple` |
373,372 | def ReadHashes(self):
len = self.ReadVarInt()
items = []
for i in range(0, len):
ba = bytearray(self.ReadBytes(32))
ba.reverse()
items.append(ba.hex())
return items | Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type. |
373,373 | def verify_leaf_hash_inclusion(self, leaf_hash: bytes, leaf_index: int,
proof: List[bytes], sth: STH):
leaf_index = int(leaf_index)
tree_size = int(sth.tree_size)
if tree_size <= leaf_index:
raise ValueError("Provided STH is for a ... | Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf_hash: The hash of the leaf for which the proof was provided.
leaf_index: Index of the leaf in the tree.
proof: A list of SHA-256 hashes representing the Merkle audit... |
373,374 | def upsert_many(col, data):
ready_to_insert = list()
for doc in data:
res = col.update({"_id": doc["_id"]}, {"$set": doc}, upsert=False)
if res["nModified"] == 0 and res["updatedExisting"] is False:
ready_to_insert.append(doc)
col.insert(ready_to_insert) | Only used when having "_id" field.
**中文文档**
要求 ``data`` 中的每一个 ``document`` 都必须有 ``_id`` 项。这样才能进行
``upsert`` 操作。 |
373,375 | def zero_pad(m, n=1):
return np.pad(m, (n, n), mode=, constant_values=[0]) | Pad a matrix with zeros, on all sides. |
373,376 | def lock(self):
url = self.reddit_session.config[]
data = {: self.fullname}
return self.reddit_session.request_json(url, data=data) | Lock thread.
Requires that the currently authenticated user has the modposts oauth
scope or has user/password authentication as a mod of the subreddit.
:returns: The json response from the server. |
373,377 | def parallel(fsms, test):
alphabet = set().union(*[fsm.alphabet for fsm in fsms])
initial = dict([(i, fsm.initial) for (i, fsm) in enumerate(fsms)])
def follow(current, symbol):
next = {}
for i in range(len(fsms)):
if symbol not in fsms[i].alphabet and anything_else in fsms[i].alphabet:
actual_sym... | Crawl several FSMs in parallel, mapping the states of a larger meta-FSM.
To determine whether a state in the larger FSM is final, pass all of the
finality statuses (e.g. [True, False, False] to `test`. |
373,378 | def theme(self, value):
if value is not None:
assert type(value) is dict, " attribute: type is not !".format("theme", value)
self.__theme = value | Setter for **self.__theme** attribute.
:param value: Attribute value.
:type value: dict |
373,379 | def delete_job(self, job_id):
if hasattr(job_id, ):
job_id = job_id.job_id
with self._sock_ctx() as socket:
self._send_message(.format(job_id), socket)
self._receive_word(socket, b) | Delete the given job id. The job must have been previously reserved by this connection |
373,380 | def Popup(*args, **_3to2kwargs):
if in _3to2kwargs: location = _3to2kwargs[]; del _3to2kwargs[]
else: location = (None, None)
if in _3to2kwargs: keep_on_top = _3to2kwargs[]; del _3to2kwargs[]
else: keep_on_top = False
if in _3to2kwargs: grab_anywhere = _3to2kwargs[]; del _3to2kwargs[]
else: g... | Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param f... |
373,381 | def to_xdr_object(self):
if self.is_native():
xdr_type = Xdr.const.ASSET_TYPE_NATIVE
return Xdr.types.Asset(type=xdr_type)
else:
x = Xdr.nullclass()
length = len(self.code)
pad_length = 4 - length if length <= 4 else 12 - length
... | Create an XDR object for this :class:`Asset`.
:return: An XDR Asset object |
373,382 | def rest_put(url, data, timeout):
try:
response = requests.put(url, headers={: , : },\
data=data, timeout=timeout)
return response
except Exception as e:
print(.format(str(e), url))
return None | Call rest put method |
373,383 | def get_listening(self, listen=[]):
if listen == []:
return listen
value = []
for network in listen:
try:
ip = get_address_in_network(network=network, fatal=True)
except ValueError:
if is_ip(network):
... | Returns a list of addresses SSH can list on
Turns input into a sensible list of IPs SSH can listen on. Input
must be a python list of interface names, IPs and/or CIDRs.
:param listen: list of IPs, CIDRs, interface names
:returns: list of IPs available on the host |
373,384 | def combineblocks(blks, imgsz, stpsz=None, fn=np.median):
def listapp(x, y):
x.append(y)
veclistapp = np.vectorize(listapp, otypes=[np.object_])
blksz = blks.shape[:-1]
if stpsz is None:
stpsz = tuple(1 for _ in blksz)
numblocks = tuple(int(np.floor((a-b)/c) +... | Combine blocks from an ndarray to reconstruct ndarray signal.
Parameters
----------
blks : ndarray
nd array of blocks of a signal
imgsz : tuple
tuple of the signal size
stpsz : tuple, optional (default None, corresponds to steps of 1)
tuple of step sizes between neighboring blocks... |
373,385 | def conditional(self, condition, requirements):
assert is_iterable_typed(condition, basestring)
assert is_iterable_typed(requirements, basestring)
c = string.join(condition, ",")
if c.find(":") != -1:
return [c + r for r in requirements]
else:
ret... | Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ... |
373,386 | def t_KEYWORD_AS_TAG(self, t):
r
t.type = self.reserved.get(t.value, )
t.value = t.value.strip()
return t | r'[a-zA-Z]+ |
373,387 | def BROKER_TYPE(self):
broker_type = get(, DEFAULT_BROKER_TYPE)
if broker_type not in SUPPORTED_BROKER_TYPES:
log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format(
broker_type, DEFAULT_BROKER_TYPE))
return DEFAULT_BROKER_TYPE
... | Custom setting allowing switch between rabbitmq, redis |
373,388 | def asDictionary(self):
return {
"type": "joinTable",
"leftTableSource": self._leftTableSource,
"rightTableSource": self._rightTableSource,
"leftTableKey": self._leftTableKey,
"rightTableKey": self._rightTableKey,
"joinType": self.... | returns the data source as a dictionary |
373,389 | def build_import_keychain( cls, keychain_dir, namespace_id, pubkey_hex ):
pubkey_addr = virtualchain.BitcoinPublicKey(str(pubkey_hex)).address()
cached_keychain = cls.get_import_keychain_path(keychain_dir, namespace_id)
if os.path.exists( cached_keychain ):
child... | Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key |
373,390 | def loaders(self):
if self.LOADERS_FOR_DYNACONF in (None, 0, "0", "false", False):
self.logger.info("No loader defined")
return []
if not self._loaders:
for loader_module_name in self.LOADERS_FOR_DYNACONF:
loader = importlib.import_module(l... | Return available loaders |
373,391 | def AUC_analysis(AUC):
try:
if AUC == "None":
return "None"
if AUC < 0.6:
return "Poor"
if AUC >= 0.6 and AUC < 0.7:
return "Fair"
if AUC >= 0.7 and AUC < 0.8:
return "Good"
if AUC >= 0.8 and AUC < 0.9:
return "... | Analysis AUC with interpretation table.
:param AUC: area under the ROC curve
:type AUC : float
:return: interpretation result as str |
373,392 | def resample_ann(resampled_t, ann_sample):
tmp = np.zeros(len(resampled_t), dtype=)
j = 0
tprec = resampled_t[j]
for i, v in enumerate(ann_sample):
while True:
d = False
if v < tprec:
j -= 1
tprec = resampled_t[j]
if j+1 =... | Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
resampled_ann_sample : numpy array
Array of resam... |
373,393 | def _safe_run_theta(input_file, out_dir, output_ext, args, data):
out_file = os.path.join(out_dir, _split_theta_ext(input_file) + output_ext)
skip_file = out_file + ".skipped"
if utils.file_exists(skip_file):
return None
if not utils.file_exists(out_file):
with file_transaction(data... | Run THetA, catching and continuing on any errors. |
373,394 | def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
if isinstance(query, Search):
search = query
elif isinstance(query, (Query, dict)):
search = Search(query)
else:
raise InvalidQuery("search() ... | Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly. |
373,395 | def junos_call(fun, *args, **kwargs):
*show system commit
prep = _junos_prep_fun(napalm_device)
if not prep[]:
return prep
if not in fun:
mod_fun = .format(fun)
else:
mod_fun = fun
if mod_fun not in __salt__:
return {
: None,
: False,
... | .. versionadded:: 2019.2.0
Execute an arbitrary function from the
:mod:`junos execution module <salt.module.junos>`. To check what ``args``
and ``kwargs`` you must send to the function, please consult the appropriate
documentation.
fun
The name of the function. E.g., ``set_hostname``.
... |
373,396 | def getTransitionUsers(obj, action_id, last_user=False):
workflow = getToolByName(obj, )
users = []
try:
review_history = list(workflow.getInfoFor(obj, ))
except WorkflowException:
logger.error(
"workflow history is inexplicably missing."
" ... | This function returns a list with the users who have done the transition.
:action_id: a sring as the transition id.
:last_user: a boolean to return only the last user triggering the
transition or all of them.
:returns: a list of user ids. |
373,397 | def get_file(path=None, content=None):
if path is None:
path = request.args.get()
if path is None:
return error()
filename = os.path.split(path.rstrip())[-1]
extension = filename.rsplit(, 1)[-1]
os_file_path = web_path_to_os_path(path)
if os.path.isdir(os_file_path):
... | :param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile |
373,398 | def register_link(self, link):
keys = tuple((ref, link.initial_hook_value) for ref in link.hook_references)
for k in keys:
if k in self._record_hooks:
link.set_target(target_record=self._record_hooks[k].target_record)
break
... | source record and index must have been set |
373,399 | def split(table, field, pattern, newfields=None, include_original=False,
maxsplit=0, flags=0):
return SplitView(table, field, pattern, newfields, include_original,
maxsplit, flags) | Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'parad1', '12'],
... ['2', 'parad2', '15'],
... ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.