Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
381,800 | def cache_control_expires(num_hours):
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *args, **kwargs)
patch_response_headers(response, num_seconds)
return response
... | Set the appropriate Cache-Control and Expires headers for the given
number of hours. |
381,801 | def to_meshpoint(meshcode, lat_multiplier, lon_multiplier):
def mesh_cord(func_higher_cord, func_unit_cord, func_multiplier):
return func_higher_cord() + func_unit_cord() * func_multiplier()
lat_multiplier_lv = lambda: lat_multiplier
lon_multiplier_lv = lambda: lon_multiplier
lat_multip... | 地域メッシュコードから緯度経度を算出する。
下記のメッシュに対応している。
1次(80km四方):1
40倍(40km四方):40000
20倍(20km四方):20000
16倍(16km四方):16000
2次(10km四方):2
8倍(8km四方):8000
5倍(5km四方):5000
4倍(4km四方):4000
2.5倍(... |
381,802 | def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None):
print()
print()
if N_clusters_max == None:
N_clusters_max = int(np.nanmax(cluster_runs)) + 1
N_runs = cluster_runs.shape[0]
N_samples = cluster_runs.shape[1]
print("INFO: Cluster_Ensembles: MCLA: pre... | Meta-CLustering Algorithm for a consensus function.
Parameters
----------
hdf5_file_name : file handle or string
cluster_runs : array of shape (n_partitions, n_samples)
verbose : bool, optional (default = False)
N_clusters_max : int, optional (default = None)
Returns... |
381,803 | def restore_data(self, data_dict):
session[self._base_key] = data_dict
self._data_dict = session[self._base_key] | Restore the data dict - update the flask session and this object |
381,804 | def add_copies(self, node, parent, elem, minel):
rep = 0 if minel is None else int(minel.arg) - 1
for i in range(rep):
parent.append(copy.deepcopy(elem)) | Add appropriate number of `elem` copies to `parent`. |
381,805 | def get_service_status(service):
dbs = db.get_session()
srvs = dbs.query(db.ServiceStates).filter(db.ServiceStates.type == service)
if srvs.count():
return srvs[0].status
return db.ServiceStatus.STOPPED | Update the status of a particular service in the database. |
381,806 | def incr(self, field, by=1):
return self._client.hincrby(self.key_prefix, field, by) | :see::meth:RedisMap.incr |
381,807 | def decode_address(self, addr):
if _debug: Address._debug("decode_address %r (%s)", addr, type(addr))
self.addrType = Address.localStationAddr
self.addrNet = None
if addr == "*":
if _debug: Address._debug(" - localBroadcast")
self.addrType ... | Initialize the address from a string. Lots of different forms are supported. |
381,808 | def get_config_from_file(conf_properties_files):
config = ExtendedConfigParser()
logger = logging.getLogger(__name__)
found = False
files_list = conf_properties_files.split()
for conf_properties_file in files_list:
result = config.read(conf... | Reads properties files and saves them to a config object
:param conf_properties_files: comma-separated list of properties files
:returns: config object |
381,809 | def write_th(self, s, header=False, indent=0, tags=None):
if header and self.fmt.col_space is not None:
tags = (tags or "")
tags += (
.format(colspace=self.fmt.col_space))
return self._write_cell(s, kind=, indent=indent, tags=tags) | Method for writting a formatted <th> cell.
If col_space is set on the formatter then that is used for
the value of min-width.
Parameters
----------
s : object
The data to be written inside the cell.
header : boolean, default False
Set to True if ... |
381,810 | def callback(self):
if self._callback_func and callable(self._callback_func):
self._callback_func(self) | Run callback. |
381,811 | def _retrieve_session(self, session_key):
session_id = session_key.session_id
if (session_id is None):
msg = ("Unable to resolve session ID from SessionKey [{0}]."
"Returning null to indicate a session could not be "
"found.".format(session_key)... | :type session_key: SessionKey
:returns: SimpleSession |
381,812 | def messages(self):
offset = self.LENGTH
while offset < len(self.mmap):
yield Message(mm=self.mmap, offset=offset)
offset += Message.LENGTH | a generator yielding the :class:`Message` structures in the index |
381,813 | def from_yaml(cls, yaml_str=None, str_or_buffer=None):
cfg = yamlio.yaml_to_dict(yaml_str, str_or_buffer)
default_model_expr = cfg[][]
default_ytransform = cfg[][]
seg = cls(
cfg[], cfg[],
cfg[], default_model_expr,
YTRANSFORM_MAPPING[defaul... | Create a SegmentedRegressionModel instance from a saved YAML
configuration. Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
str_or_buffer : str or file like, optional
File name or buf... |
381,814 | def Barr_1981(Re, eD):
r
fd = (-2*log10(eD/3.7 + 4.518*log10(Re/7.)/(Re*(1+Re**0.52/29*eD**0.7))))**-2
return fd | r'''Calculates Darcy friction factor using the method in Barr (1981) [2]_
as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = -2\log\left\{\frac{\epsilon}{3.7D} +
\frac{4.518\log(\frac{Re}{7})}{Re\left[1+\frac{Re^{0.52}}{29}
\left(\frac{\epsilon}{D}\right)^{0.7}\right]}\right\}
Para... |
381,815 | def block_idxmat_shuffle(numdraws, numblocks, random_state=None):
import numpy as np
blocksize = int(numdraws / numblocks)
if random_state:
np.random.seed(random_state)
obsidx = np.random.permutation(numdraws)
numdrop = numdraws % numblocks
dropped = obsidx[:n... | Create K columns with unique random integers from 0 to N-1
Purpose:
--------
- Create K blocks for k-fold cross-validation
Parameters:
-----------
numdraws : int
number of observations N or sample size N
numblocks : int
number of blocks K
Example:
--------
... |
381,816 | def do_mo(self):
log.debug("Start updating mo files ...")
for po_dir_path in self._iter_po_dir():
po_path = (po_dir_path / self._basename).with_suffix(".po")
lc_path = self._mo_path / po_dir_path.name / "LC_MESSAGES"
lc_path.mkdir(parents=True, exist_ok=True)... | Generate mo files for all po files. |
381,817 | def ndfrom2d(xtr, rsi):
xts = rsi[0]
prm = rsi[1]
xt = xtr.reshape(xts)
x = np.transpose(xt, np.argsort(prm))
return x | Undo the array shape conversion applied by :func:`ndto2d`,
returning the input 2D array to its original shape.
Parameters
----------
xtr : array_like
Two-dimensional input array
rsi : tuple
A tuple containing the shape of the axis-permuted array and the
permutation order applied ... |
381,818 | def mktime_tz(data):
if data[9] is None:
return time.mktime(data[:8] + (-1,))
else:
t = calendar.timegm(data)
return t - data[9] | Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp. |
381,819 | def validated_value(self, raw_value):
value = self.value(raw_value)
try:
for validator in self.validators:
validator(value)
except:
raise
else:
return value | Return parsed parameter value and run validation handlers.
Error message included in exception will be included in http error
response
Args:
value: raw parameter value to parse validate
Returns:
None
Note:
Concept of validation for params i... |
381,820 | def inject_settings(mixed: Union[str, Settings],
context: MutableMapping[str, Any],
fail_silently: bool = False) -> None:
if isinstance(mixed, str):
try:
mixed = import_module(mixed)
except Exception:
if fail_silently:
... | Inject settings values to given context.
:param mixed:
Settings can be a string (that it will be read from Python path),
Python module or dict-like instance.
:param context:
Context to assign settings key values. It should support dict-like item
assingment.
:param fail_silen... |
381,821 | def get_posts_with_limits(self, include_draft=False, **limits):
filter_funcs = []
for attr in (, , ,
, , ):
if limits.get(attr):
filter_set = set(to_list(limits.get(attr)))
def get_filter_func(filter_set_, attr_):
... | Get all posts and filter them as needed.
:param include_draft: return draft posts or not
:param limits: other limits to the attrs of the result,
should be a dict with string or list values
:return: an iterable of Post objects |
381,822 | def fol_fc_ask(KB, alpha):
while True:
new = {}
for r in KB.clauses:
ps, q = parse_definite_clause(standardize_variables(r))
raise NotImplementedError | Inefficient forward chaining for first-order logic. [Fig. 9.3]
KB is a FolKB and alpha must be an atomic sentence. |
381,823 | def validate_schema(schema_name):
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
instance.validator(instance.schemas[schema_name]).validate(request.get_json())
except ValidationError, e:
ret_dict ... | Validate the JSON against a required schema_name. |
381,824 | def release():
with settings(warn_only=True):
r = local(clom.git[](, , ))
if r.return_code != 0:
abort()
version = open().read().strip()
existing_tag = local(clom.git.tag(, version), capture=True)
if not existing_tag.strip():
print( % version)
local(clom.git.... | Release current version to pypi |
381,825 | def _iupac_ambiguous_equal(ambig_base, unambig_base):
iupac_translation = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
:
}
for i in (ambig_base, ... | Tests two bases for equality, accounting for IUPAC ambiguous DNA
ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT |
381,826 | def predict_epitopes_from_args(args):
mhc_model = mhc_binding_predictor_from_args(args)
variants = variant_collection_from_args(args)
gene_expression_dict = rna_gene_expression_dict_from_args(args)
transcript_expression_dict = rna_transcript_expression_dict_from_args(args)
predictor = TopiaryP... | Returns an epitope collection from the given commandline arguments.
Parameters
----------
args : argparse.Namespace
Parsed commandline arguments for Topiary |
381,827 | def set_h264_frm_ref_mode(self, mode=1, callback=None):
params = {: mode}
return self.execute_command(, params, callback) | Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode |
381,828 | def get_fun(fun):
conn = _get_conn(ret=None)
cur = conn.cursor()
sql =
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, retval in data:
ret[minion] = salt.utils.json.loads(retval)
_close_conn(conn)
return ret | Return a dict of the last function called for all minions |
381,829 | def find_pattern_on_line(lines, n, max_wrap_lines):
for typ, regexes in COMPILED_PATTERN_MAP.items():
for regex in regexes:
for m in range(max_wrap_lines):
match_line = join_wrapped_lines(lines[n:n+1+m])
if match_line.startswith():
match_l... | Finds a forward/reply pattern within the given lines on text on the given
line number and returns a tuple with the type ('reply' or 'forward') and
line number of where the pattern ends. The returned line number may be
different from the given line number in case the pattern wraps over
multiple lines.
... |
381,830 | def get_nested_schema_object(self, fully_qualified_parent_name: str,
nested_item_name: str) -> Optional[]:
return self.get_schema_object(
self.get_fully_qualified_name(fully_qualified_parent_name, nested_item_name)) | Used to generate a schema object from the given fully_qualified_parent_name
and the nested_item_name.
:param fully_qualified_parent_name: The fully qualified name of the parent.
:param nested_item_name: The nested item name.
:return: An initialized schema object of the nested item. |
381,831 | def _set_fcoe_intf_enode_bind_type(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 2}, u... | Setter method for fcoe_intf_enode_bind_type, mapped from YANG variable /brocade_fcoe_ext_rpc/fcoe_get_interface/output/fcoe_intf_list/fcoe_intf_enode_bind_type (fcoe-binding-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_intf_enode_bind_type is considered as a privat... |
381,832 | def validate_blob_uri_contents(contents: bytes, blob_uri: str) -> None:
blob_path = parse.urlparse(blob_uri).path
blob_hash = blob_path.split("/")[-1]
contents_str = to_text(contents)
content_length = len(contents_str)
hashable_contents = "blob " + str(content_length) + "\0" + contents_str
... | Raises an exception if the sha1 hash of the contents does not match the hash found in te
blob_uri. Formula for how git calculates the hash found here:
http://alblue.bandlem.com/2011/08/git-tip-of-week-objects.html |
381,833 | def modify_target(self, to_state, to_outcome=None):
if not (to_state is None and (to_outcome is not int and to_outcome is not None)):
if not isinstance(to_state, string_types):
raise ValueError("Invalid transition target port: to_state must be a string")
if not i... | Set both to_state and to_outcome at the same time to modify transition target
:param str to_state: State id of the target state
:param int to_outcome: Outcome id of the target port
:raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid |
381,834 | def set_attribute_mapping(resource_attr_a, resource_attr_b, **kwargs):
user_id = kwargs.get()
ra_1 = get_resource_attribute(resource_attr_a)
ra_2 = get_resource_attribute(resource_attr_b)
mapping = ResourceAttrMap(resource_attr_id_a = resource_attr_a,
resource_attr_id_... | Define one resource attribute from one network as being the same as
that from another network. |
381,835 | def color(out_string, color=):
c = {
: Fore.BLACK,
: Fore.BLUE,
: Fore.CYAN,
: Fore.GREEN,
: Fore.MAGENTA,
: Fore.RED,
: Fore.WHITE,
: Fore.YELLOW,
}
try:
init()
return (c[color] + Style.BRIGHT + out_string + Fore.RESET + S... | Highlight string for terminal color coding.
Purpose: We use this utility function to insert a ANSI/win32 color code
| and Bright style marker before a string, and reset the color and
| style after the string. We then return the string with these
| codes inserted.
@param out_st... |
381,836 | def get_endpoint_descriptor(self, dev, ep, intf, alt, config):
r
_not_implemented(self.get_endpoint_descriptor) | r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not ... |
381,837 | def trainingDataLink(data_1, data_2, common_key, training_size=50000):
identified_records = collections.defaultdict(lambda: [[], []])
matched_pairs = set()
distinct_pairs = set()
for record_id, record in data_1.items():
identified_records[record[common_key]][0].append(record_id)
fo... | Construct training data for consumption by the ActiveLearning
markPairs method from already linked datasets.
Arguments :
data_1 -- Dictionary of records from first dataset, where the keys
are record_ids and the values are dictionaries with the
keys being fie... |
381,838 | def css( self, filelist ):
if isinstance( filelist, basestring ):
self.link( href=filelist, rel=, type=, media= )
else:
for file in filelist:
self.link( href=file, rel=, type=, media= ) | This convenience function is only useful for html.
It adds css stylesheet(s) to the document via the <link> element. |
381,839 | def check_token(self, respond):
if respond.status_code == 401:
self.credential.obtain_token(config=self.config)
return False
return True | Check is the user's token is valid |
381,840 | def find_studies(self, query_dict=None, exact=False, verbose=False, **kwargs):
if self.use_v1:
uri = .format(p=self.query_prefix)
else:
uri = .format(p=self.query_prefix)
return self._do_query(uri,
query_dict=query_dict,
... | Query on study properties. See documentation for _OTIWrapper class. |
381,841 | def html_path(builder, pagename=None):
return builder.get_relative_uri(
pagename or builder.current_docname,
os.path.join(
builder.app.config.slide_html_relative_path,
pagename or builder.current_docname,
)) | Calculate the relative path to the Slides for pagename. |
381,842 | def copy_SRM_file(destination=None, config=):
conf = read_configuration()
src = pkgrs.resource_filename(, conf[])
if destination is None:
destination = + conf[] +
if os.path.isdir(destination):
destination += + conf[] +
copyfile(src, destination)
print... | Creates a copy of the default SRM table at the specified location.
Parameters
----------
destination : str
The save location for the SRM file. If no location specified,
saves it as 'LAtools_[config]_SRMTable.csv' in the current working
directory.
config : str
It's poss... |
381,843 | def create_label(self, label, doc=None, callback=dummy_progress_cb):
if doc:
clone = doc.clone()
r = self.index.create_label(label, doc=clone)
return r | Create a new label
Arguments:
doc --- first document on which the label must be added (required
for now) |
381,844 | def get_operation_full_job_id(op):
job_id = op.get_field()
task_id = op.get_field()
if task_id:
return % (job_id, task_id)
else:
return job_id | Returns the job-id or job-id.task-id for the operation. |
381,845 | def log_once(key):
global _last_logged
if _disabled:
return False
elif key not in _logged:
_logged.add(key)
_last_logged = time.time()
return True
elif _periodic_log and time.time() - _last_logged > 60.0:
_logged.clear()
_last_logged = time.time()
... | Returns True if this is the "first" call for a given key.
Various logging settings can adjust the definition of "first".
Example:
>>> if log_once("some_key"):
... logger.info("Some verbose logging statement") |
381,846 | def OnNodeSelected(self, event):
try:
node = self.sorted[event.GetIndex()]
except IndexError, err:
log.warn(_(),
index=event.GetIndex())
else:
if node is not self.selected_node:
wx.PostEvent(
se... | We have selected a node with the list control, tell the world |
381,847 | def parallel_map(func, *arg_iterable, **kwargs):
chunksize = kwargs.pop(, 1)
func_pre_args = kwargs.pop(, ())
func_kwargs = kwargs.pop(, {})
max_workers = kwargs.pop(, None)
parallel = kwargs.pop(, True)
parallel_warning = kwargs.pop(, True)
if kwargs:
raise TypeError(.format(kw... | Apply function to iterable with parallel map, and hence returns
results in order. functools.partial is used to freeze func_pre_args and
func_kwargs, meaning that the iterable argument must be the last positional
argument.
Roughly equivalent to
>>> [func(*func_pre_args, x, **func_kwargs) for x in a... |
381,848 | def on_sdl_keydown ( self, event ):
"press ESCAPE to quit the application"
key = event.key.keysym.sym
if key == SDLK_ESCAPE:
self.running = False | press ESCAPE to quit the application |
381,849 | def folderitem(self, obj, item, index):
url = item.get("url")
title = item.get("Title")
creator = obj.Creator()
item["replace"]["Title"] = get_link(url, value=title)
item["created"] = self.localize_date(obj.created())
item["getType"] = _(obj.getType()[0])
... | Augment folder listing item |
381,850 | def clear(self, payload):
self.logger.rotate(self.queue)
self.queue.clear()
self.logger.write(self.queue)
answer = {: , : }
return answer | Clear queue from any `done` or `failed` entries.
The log will be rotated once. Otherwise we would loose all logs from
thoes finished processes. |
381,851 | def get_all_items_of_credit_note(self, credit_note_id):
return self._iterate_through_pages(
get_function=self.get_items_of_credit_note_per_page,
resource=CREDIT_NOTE_ITEMS,
**{: credit_note_id}
) | Get all items of credit note
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param credit_note_id: the credit note id
:return: list |
381,852 | def findAllBycolumn(self, target):
column_matches = []
for column_index in range(self._raster[1]):
column = self.getRow(column_index)
column_matches[column_index] = column.findAll(target)
return column_matches | Returns an array of columns in the region (defined by the raster), each
column containing all matches in that column for the target pattern. |
381,853 | def enable_branching_model(self, project, repository):
default_model_data = {: {: None, : True},
: [{: ,
: True,
: ,
: },
... | Enable branching model by setting it with default configuration
:param project:
:param repository:
:return: |
381,854 | def nla_put_nested(msg, attrtype, nested):
_LOGGER.debug(, id(msg), attrtype, id(nested))
return nla_put(msg, attrtype, nlmsg_datalen(nested.nm_nlh), nlmsg_data(nested.nm_nlh)) | Add nested attributes to Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L772
Takes the attributes found in the `nested` message and appends them to the message `msg` nested in a container of
the type `attrtype`. The `nested` message may not have a family specific header.
... |
381,855 | def export_html(html, filename, image_tag = None, inline = True):
if image_tag is None:
image_tag = default_image_tag
else:
image_tag = ensure_utf8(image_tag)
if inline:
path = None
else:
root,ext = os.path.splitext(filename)
path = root + "_files"
i... | Export the contents of the ConsoleWidget as HTML.
Parameters:
-----------
html : str,
A utf-8 encoded Python string containing the Qt HTML to export.
filename : str
The file to be saved.
image_tag : callable, optional (default None)
Used to convert images. See ``default_im... |
381,856 | def cancel_all_linking(self):
self.logger.info("Cancel_all_linking for device %s", self.device_id)
self.hub.direct_command(self.device_id, , ) | Cancel all linking |
381,857 | def switch_from_external_to_main_wf(self):
self.run() | Main workflow switcher.
This method recreates main workflow from `main wf` dict which
was set by external workflow swicther previously. |
381,858 | def which(name,
env_path=ENV_PATH,
env_path_ext=ENV_PATHEXT,
is_executable_fnc=isexec,
path_join_fnc=os.path.join,
os_name=os.name):
for path in env_path:
for suffix in env_path_ext:
exe_file = path_join_fnc(path, name) + suffix
... | Get command absolute path.
:param name: name of executable command
:type name: str
:param env_path: OS environment executable paths, defaults to autodetected
:type env_path: list of str
:param is_executable_fnc: callable will be used to detect if path is
executable, de... |
381,859 | def fit(self, X, y):
word_vector_transformer = WordVectorTransformer(padding=)
X = word_vector_transformer.fit_transform(X)
X = LongTensor(X)
self.word_vector_transformer = word_vector_transformer
y_transformer = LabelEncoder()
y = y_t... | Fit KimCNNClassifier according to X, y
Parameters
----------
X : list of string
each item is a raw text
y : list of string
each item is a label |
381,860 | def dispatch(self):
parser = argparse.ArgumentParser(description=)
parser.add_argument(, metavar=, type=str, help=)
parser.add_argument(, metavar=, type=int, help=)
args = parser.parse_args()
self.serve(port=args.port, address=args.addr) | Command-line dispatch. |
381,861 | def draw(self):
self.ax.plot(self.k_values_, self.k_scores_, marker="D")
if self.locate_elbow and self.elbow_value_!=None:
elbow_label = "$elbow\ at\ k={}, score={:0.3f}$".format(self.elbow_value_, self.elbow_score_)
self.ax.axvline(self.elbow_value_, c=LINE_COL... | Draw the elbow curve for the specified scores and values of K. |
381,862 | def print(*a):
try:
_print(*a)
return a[0] if len(a) == 1 else a
except:
_print(*a) | print just one that returns what you give it instead of None |
381,863 | def _get (self, timeout):
if timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError(" must be a positive number")
endtime = _time() + timeout
while self._empty():
... | Non thread-safe utility function of self.get() doing the real
work. |
381,864 | def snapshot(self, name):
return self.get_data(
"volumes/%s/snapshots/" % self.id,
type=POST,
params={"name": name}
) | Create a snapshot of the volume.
Args:
name: string - a human-readable name for the snapshot |
381,865 | def cmp(self, other):
if isinstance(other, Range):
start = self.start.replace(tzinfo=other.start.tz) if other.start.tz and self.start.tz is None else self.start
end = self.end.replace(tzinfo=other.end.tz) if other.end.tz and self.end.tz is None else self.end
... | *Note: checks Range.start() only*
Key: self = [], other = {}
* [ {----]----} => -1
* {---[---} ] => 1
* [---] {---} => -1
* [---] same as {---} => 0
* [--{-}--] => -1 |
381,866 | def cli(wio, send):
s AP.
\b
EXAMPLE:
wio udp --send [command], send UPD command
'
command = send
click.echo("UDP command: {}".format(command))
result = udp.common_send(command)
if result is None:
return debug_error()
else:
click.echo(result) | Sends a UDP command to the wio device.
\b
DOES:
Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0"
"APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n",
Note:
1. Ensure your device is Configure Mode.
2. Change your computer n... |
381,867 | def code(self):
def uniq(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
data_set = uniq(i for i in self.autos if i is not None)
error_list = uniq(i for i in self.errors i... | Removes duplicates values in auto and error list.
parameters. |
381,868 | def get_name(self, tag):
s output can be controlled through
keyword arguments that are provided when initializing a
TagProcessor. For instance, a member of a class or namespace can have
its parent scope included in the name by passing
include_parent_scopes=True to __init__().
... | Extract and return a representative "name" from a tag.
Override as necessary. get_name's output can be controlled through
keyword arguments that are provided when initializing a
TagProcessor. For instance, a member of a class or namespace can have
its parent scope included in the name b... |
381,869 | def keep_negative_mask(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.keep_mask, X, y, model_generator, method_name, -1, num_fcounts, __mean_pred) | Keep Negative (mask)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 5 |
381,870 | def query_cached_package_list(self):
if self.debug:
self.logger.debug("DEBUG: reading pickled cache file")
return cPickle.load(open(self.pkg_cache_file, "r")) | Return list of pickled package names from PYPI |
381,871 | def check_parallel_run(self):
if os.name == :
logger.warning("The parallel daemon check is not available on Windows")
self.__open_pidfile(write=True)
return
self.__open_pidfile()
try:
pid_var = self.fpid.readline().s... | Check (in pid file) if there isn't already a daemon running.
If yes and do_replace: kill it.
Keep in self.fpid the File object to the pid file. Will be used by writepid.
:return: None |
381,872 | def size(ctx, dataset, kwargs):
"Show dataset size"
kwargs = parse_kwargs(kwargs)
(print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size) | Show dataset size |
381,873 | def all(self):
tests = list()
for testclass in self.classes:
tests.extend(self.classes[testclass].cases)
return tests | Return all testcases
:return: |
381,874 | def _build_zmat(self, construction_table):
c_table = construction_table
default_cols = [, , , , , , ]
optional_cols = list(set(self.columns) - {, , , })
zmat_frame = pd.DataFrame(columns=default_cols + optional_cols,
dtype=, index=c_table.index... | Create the Zmatrix from a construction table.
Args:
Construction table (pd.DataFrame):
Returns:
Zmat: A new instance of :class:`Zmat`. |
381,875 | def fetch(self, **kwargs) -> :
GETGET
assert self.method in self._allowed_methods, \
.format(self.method)
self.date = datetime.now(tzutc())
self.headers[] = self.date.isoformat()
if self.content_type is not None:
self.headers[] = self.content_type
... | Sends the request to the server and reads the response.
You may use this method either with plain synchronous Session or
AsyncSession. Both the followings patterns are valid:
.. code-block:: python3
from ai.backend.client.request import Request
from ai.backend.client.sess... |
381,876 | def get_geo_info(filename, band=1):
sourceds = gdal.Open(filename, GA_ReadOnly)
ndv = sourceds.GetRasterBand(band).GetNoDataValue()
xsize = sourceds.RasterXSize
ysize = sourceds.RasterYSize
geot = sourceds.GetGeoTransform()
projection = osr.SpatialReference()
projection.ImportFromWkt(so... | Gets information from a Raster data set |
381,877 | def face_adjacency_radius(self):
radii, span = graph.face_adjacency_radius(mesh=self)
self._cache[] = span
return radii | The approximate radius of a cylinder that fits inside adjacent faces.
Returns
------------
radii : (len(self.face_adjacency),) float
Approximate radius formed by triangle pair |
381,878 | def sibling(self, offs=1):
indx = self.pindex + offs
if indx < 0:
return None
if indx >= len(self.parent.kids):
return None
return self.parent.kids[indx] | Return sibling node by relative offset from self. |
381,879 | def image(
self,
url,
title="",
width=800):
title = title.strip()
caption = title
now = datetime.now()
figId = now.strftime("%Y%m%dt%H%M%S.%f")
if len(title):
figId = "%(title)s %(figId)s" % locals()
... | *create MMD image link*
**Key Arguments:**
- ``title`` -- the title for the image
- ``url`` -- the image URL
- ``width`` -- the width in pixels of the image. Default *800*
**Return:**
- ``imageLink`` -- the MMD image link
**Usage:**
... |
381,880 | def create_identity(user_id, curve_name):
result = interface.Identity(identity_str=, curve_name=curve_name)
result.identity_dict[] = user_id
return result | Create GPG identity for hardware device. |
381,881 | def compare_mean_curves(calc_ref, calc, nsigma=3):
dstore_ref = datastore.read(calc_ref)
dstore = datastore.read(calc)
imtls = dstore_ref[].imtls
if dstore[].imtls != imtls:
raise RuntimeError(
% (calc_ref, calc))
sitecol_ref = dstore_ref[]
sitecol = dsto... | Compare the hazard curves coming from two different calculations. |
381,882 | def create_from_request_pdu(pdu):
_, address, value = struct.unpack(, pdu)
value = 1 if value == 0xFF00 else value
instance = WriteSingleCoil()
instance.address = address
instance.value = value
return instance | Create instance from request PDU.
:param pdu: A response PDU. |
381,883 | def execute_wait(self, cmd, walltime=2, envs={}):
stdin, stdout, stderr = self.ssh_client.exec_command(
self.prepend_envs(cmd, envs), bufsize=-1, timeout=walltime
)
exit_status = stdout.channel.recv_exit_status()
return exit_status, stdout.read().d... | Synchronously execute a commandline string on the shell.
Args:
- cmd (string) : Commandline string to execute
- walltime (int) : walltime in seconds
Kwargs:
- envs (dict) : Dictionary of env variables
Returns:
- retcode : Return code from the ex... |
381,884 | def stop_sync(self):
if self.scanning:
self.stop_scan()
for connection_id in list(self.connections.get_connections()):
self.disconnect_sync(connection_id)
self.bable.stop()
self.connections.stop()
self.stoppe... | Safely stop this BLED112 instance without leaving it in a weird state |
381,885 | def personByEmailAddress(self, address):
email = self.store.findUnique(EmailAddress,
EmailAddress.address == address,
default=None)
if email is not None:
return email.person | Retrieve the L{Person} item for the given email address
(or return None if no such person exists)
@type name: C{unicode} |
381,886 | async def write_and_drain(self, data: bytes, timeout: NumType = None) -> None:
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
self._stream_writer.write(data)
async with self._io_lock:
await self._drain_writer(timeout) | Format a command and send it to the server. |
381,887 | def get_requests_request_name(self, request_name):
query_parameters = {}
if request_name is not None:
query_parameters[] = self._serialize.query(, request_name, )
response = self._send(http_method=,
location_id=,
ve... | GetRequestsRequestName.
[Preview API] Get a symbol request by request name.
:param str request_name:
:rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>` |
381,888 | def logSumExp(A, B, out=None):
if out is None:
out = numpy.zeros(A.shape)
indicator1 = A >= B
indicator2 = numpy.logical_not(indicator1)
out[indicator1] = A[indicator1] + numpy.log1p(numpy.exp(B[indicator1]-A[indicator1]))
out[indicator2] = B[indicator2] + numpy.log1p(numpy.exp(A[indicator2]-B[indic... | returns log(exp(A) + exp(B)). A and B are numpy arrays |
381,889 | def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
local_DecodeVarint = _DecodeVarint
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
tag_len = len(tag_bytes)
def DecodeR... | Returns a decoder for a bytes field. |
381,890 | def graph_query(kind, source, target=None, neighbor_limit=1,
database_filter=None):
default_databases = [, , , , , ,
, , , , ,
, , , ,
, , ]
if not database_filter:
query_databases = default_databases
el... | Perform a graph query on PathwayCommons.
For more information on these queries, see
http://www.pathwaycommons.org/pc2/#graph
Parameters
----------
kind : str
The kind of graph query to perform. Currently 3 options are
implemented, 'neighborhood', 'pathsbetween' and 'pathsfromto'.
... |
381,891 | def add_parameter(self, name, value, meta=None):
parameter = Parameter(name, value)
if meta: parameter.meta = meta
self.parameters.append(parameter) | Add a parameter to the parameter list.
:param name: New parameter's name.
:type name: str
:param value: New parameter's value.
:type value: float
:param meta: New parameter's meta property.
:type meta: dict |
381,892 | def open_file(self, info):
if not info.initialized: return
dlg = FileDialog( action = "open",
wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|"
"*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|"
"All Files (*.*)|*.*|")
if dlg.open() == OK:
... | Handles the open action. |
381,893 | def _connect(self, database=None):
conn_args = {
: self.config[],
: self.config[],
: self.config[],
: self.config[],
: self.config[],
}
if database:
conn_args[] = database
else:
conn_args[] =
... | Connect to given database |
381,894 | def insert_before(self, text):
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
original_cursor_position=selection_state.original_cursor_position + len(text),
type=selection_state.type)
return Document(
... | Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync. |
381,895 | def trigger_event(self, event, client, args, force_dispatch=False):
self.controller.process_event(event, client, args, force_dispatch=force_dispatch) | Trigger a new event that will be dispatched to all modules. |
381,896 | def rand_bytes(length):
if not isinstance(length, int_types):
raise TypeError(pretty_message(
,
type_name(length)
))
if length < 1:
raise ValueError()
if length > 1024:
raise ValueError()
buffer = buffer_from_bytes(length)
result = Sec... | Returns a number of random bytes suitable for cryptographic purposes
:param length:
The desired number of bytes
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of the parameters are of the wrong type
OSError - when an error is retu... |
381,897 | def ntowfv2(domain, user, password):
md4 = hashlib.new()
md4.update(password)
hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend())
hmac_context.update(user.upper().encode())
hmac_context.update(domain.encode())
return hmac_context.final... | NTOWFv2() Implementation
[MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol
3.3.2 NTLM v2 Authentication
:param domain: The windows domain name
:param user: The windows username
:param password: The users password
:return: Hash Data |
381,898 | def clear(self):
not_removed = []
for fn in os.listdir(self.base):
fn = os.path.join(self.base, fn)
try:
if os.path.islink(fn) or os.path.isfile(fn):
os.remove(fn)
elif os.path.isdir(fn):
shutil.rmtr... | Clear the cache. |
381,899 | def store_drop(cls, resource: str, session: Optional[Session] = None) -> :
action = cls.make_drop(resource)
_store_helper(action, session=session)
return action | Store a "drop" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_drop('hgnc') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.