code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def get_signatures(self):
signatures = self.request_list('GetSignatures')
return [zobjects.Signature.from_dict(i) for i in signatures] | Get all signatures for the current user
:returns: a list of zobjects.Signature |
def authenticate_credentials(self, token):
msg = _('Invalid token.')
token = token.decode("utf-8")
for auth_token in AuthToken.objects.filter(
token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
if self._cleanup_token(auth_token):
continue
try:
... | Due to the random nature of hashing a salted value, this must inspect
each auth_token individually to find the correct one.
Tokens that have expired will be deleted and skipped |
async def pull(
self,
from_image: str,
*,
auth: Optional[Union[MutableMapping, str, bytes]] = None,
tag: str = None,
repo: str = None,
stream: bool = False
) -> Mapping:
image = from_image
params = {"fromImage": image}
headers = {}
... | Similar to `docker pull`, pull an image locally
Args:
fromImage: name of the image to pull
repo: repository name given to an image when it is imported
tag: if empty when pulling an image all tags
for the given image to be pulled
auth: special {'a... |
def _text_io_wrapper(stream, mode, encoding, errors, newline):
if "t" in mode and not hasattr(stream, 'encoding'):
text_stream = TextIOWrapper(
stream, encoding=encoding, errors=errors, newline=newline)
yield text_stream
text_stream.flush()
else:
yield stream | Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines |
def point(self, x, y):
return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y)) | construct a point from 2 values |
def mse(predicted, actual):
diff = predicted - actual
return np.average(diff * diff, axis=0) | Mean squared error of predictions.
.. versionadded:: 0.5.0
Parameters
----------
predicted : ndarray
Predictions on which to measure error. May
contain a single or multiple column but must
match `actual` in shape.
actual : ndarray
Actual values against which to mea... |
def clear():
utils.check_for_local_server()
click.confirm(
"Are you sure you want to do this? It will delete all of your data",
abort=True
)
server = Server(config["local_server"]["url"])
for db_name in all_dbs:
del server[db_name] | Clear all data on the local server. Useful for debugging purposed. |
def pop_cell(self, idy=None, idx=None, tags=False):
idy = idy if idy is not None else len(self.body) - 1
idx = idx if idx is not None else len(self.body[idy]) - 1
cell = self.body[idy].pop(idx)
return cell if tags else cell.childs[0] | Pops a cell, default the last of the last row |
def _get_ssl_context(self, req: 'ClientRequest') -> Optional[SSLContext]:
if req.is_ssl():
if ssl is None:
raise RuntimeError('SSL is not supported.')
sslcontext = req.ssl
if isinstance(sslcontext, ssl.SSLContext):
return sslcontext
... | Logic to get the correct SSL context
0. if req.ssl is false, return None
1. if ssl_context is specified in req, use it
2. if _ssl_context is specified in self, use it
3. otherwise:
1. if verify_ssl is not specified in req, use self.ssl_context
(will generate ... |
def nlargest(n, mapping):
try:
it = mapping.iteritems()
except AttributeError:
it = iter(mapping.items())
pq = minpq()
try:
for i in range(n):
pq.additem(*next(it))
except StopIteration:
pass
try:
while it:
pq.pushpopitem(*next(it))... | Takes a mapping and returns the n keys associated with the largest values
in descending order. If the mapping has fewer than n items, all its keys
are returned.
Equivalent to:
``next(zip(*heapq.nlargest(mapping.items(), key=lambda x: x[1])))``
Returns
-------
list of up to n keys from ... |
def fit(self, X, y):
self._word_vocab.add_documents(X)
self._label_vocab.add_documents(y)
if self._use_char:
for doc in X:
self._char_vocab.add_documents(doc)
self._word_vocab.build()
self._char_vocab.build()
self._label_vocab.build()
r... | Learn vocabulary from training set.
Args:
X : iterable. An iterable which yields either str, unicode or file objects.
Returns:
self : IndexTransformer. |
def build_source_files(self):
from .files import BuildSourceFileAccessor
return BuildSourceFileAccessor(self, self.dataset, self.source_fs) | Return acessors to the build files |
def json(self):
self.pendingvalidation()
jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations() }
if self.version:
jsondoc['version'] = self.version
else:
jsondoc['version'] = FOLIAVERSION
jsondoc['generator'] = 'pynlpl.formats.f... | Serialise the document to a ``dict`` ready for serialisation to JSON.
Example::
import json
jsondoc = json.dumps(doc.json()) |
def data(self, buffer_index):
expired = self.time - self.max_time
exp = self.buffer_expire[buffer_index]
j = 0
while j < len(exp):
if exp[j] >= expired:
self.buffer_expire[buffer_index] = exp[j:].copy()
self.buffer[buffer_index] = self.buf... | Return the data vector for a given ring buffer |
def tofile(self, fobj, format):
if format == 'hex':
self.write_hex_file(fobj)
elif format == 'bin':
self.tobinfile(fobj)
else:
raise ValueError('format should be either "hex" or "bin";'
' got %r instead' % format) | Write data to hex or bin file. Preferred method over tobin or tohex.
@param fobj file name or file-like object
@param format file format ("hex" or "bin") |
def writeln (self, s=u"", **args):
self.write(u"%s%s" % (s, unicode(os.linesep)), **args) | Write string to output descriptor plus a newline. |
def _finalize_cwl_in(data, work_dir, passed_keys, output_cwl_keys, runtime):
data["dirs"] = {"work": work_dir}
if not tz.get_in(["config", "algorithm"], data):
if "config" not in data:
data["config"] = {}
data["config"]["algorithm"] = {}
if "rgnames" not in data and "description"... | Finalize data object with inputs from CWL. |
def publish(self, *args, **kwargs):
user_cb = kwargs.pop('cb', None)
channel = self._get_channel()
if channel and not channel.active:
inactive_channels = set()
while channel and not channel.active:
inactive_channels.add(channel)
channel = s... | Publish a message. Caller can supply an optional callback which will
be fired when the transaction is committed. Tries very hard to avoid
closed and inactive channels, but a ChannelError or ConnectionError
may still be raised. |
def segment_array(arr, length, overlap=.5):
arr = N.array(arr)
offset = float(overlap) * length
total_segments = int((N.shape(arr)[0] - length) / offset) + 1
other_shape = N.shape(arr)[1:]
out_shape = [total_segments, length]
out_shape.extend(other_shape)
out = N.empty(out_shape)
for i i... | Segment array into chunks of a specified length, with a specified
proportion overlap.
Operates on axis 0.
:param integer length: Length of each segment
:param float overlap: Proportion overlap of each frame |
def expandEntitiesFromEmail(e):
email = {}
email["type"] = "i3visio.email"
email["value"] = e
email["attributes"] = []
alias = {}
alias["type"] = "i3visio.alias"
alias["value"] = e.split("@")[0]
alias["attributes"] = []
domain= {}
domain["type"] = "i3visio.domain"
domain["val... | Method that receives an email an creates linked entities
Args:
-----
e: Email to verify.
Returns:
--------
Three different values: email, alias and domain in a list. |
def _normalize_for_correlation(data, axis, return_nans=False):
shape = data.shape
data = zscore(data, axis=axis, ddof=0)
if not return_nans:
data = np.nan_to_num(data)
data = data / math.sqrt(shape[axis])
return data | normalize the data before computing correlation
The data will be z-scored and divided by sqrt(n)
along the assigned axis
Parameters
----------
data: 2D array
axis: int
specify which dimension of the data should be normalized
return_nans: bool, default:False
If False, retu... |
def get_md_header(header_text_line: str,
header_duplicate_counter: dict,
keep_header_levels: int = 3,
parser: str = 'github',
no_links: bool = False) -> dict:
r
result = get_atx_heading(header_text_line, keep_header_levels, parser,
... | r"""Build a data structure with the elements needed to create a TOC line.
:parameter header_text_line: a single markdown line that needs to be
transformed into a TOC line.
:parameter header_duplicate_counter: a data structure that contains the
number of occurrencies of each header anchor link... |
def get_error_message(status_code):
errmsg = ctypes.create_string_buffer(1024)
nican.ncStatusToString(status_code, len(errmsg), errmsg)
return errmsg.value.decode("ascii") | Convert status code to descriptive string. |
def authenticated(
method: Callable[..., Optional[Awaitable[None]]]
) -> Callable[..., Optional[Awaitable[None]]]:
@functools.wraps(method)
def wrapper(
self: RequestHandler, *args, **kwargs
) -> Optional[Awaitable[None]]:
if not self.current_user:
if self.request.method in (... | Decorate methods with this to require that the user be logged in.
If the user is not logged in, they will be redirected to the configured
`login url <RequestHandler.get_login_url>`.
If you configure a login url with a query parameter, Tornado will
assume you know what you're doing and use it as-is. I... |
def apply_defaults(self, instance):
for field, spec in self.doc_spec.iteritems():
field_type = spec['type']
if field not in instance:
if 'default' in spec:
default = spec['default']
if callable(default):
inst... | Applies the defaults described by the this schema to the given
document instance as appropriate. Defaults are only applied to
fields which are currently unset. |
def find_keyword_in_context(tokens, keyword, contextsize=1):
if isinstance(keyword,tuple) and isinstance(keyword,list):
l = len(keyword)
else:
keyword = (keyword,)
l = 1
n = l + contextsize*2
focuspos = contextsize + 1
for ngram in Windower(tokens,n,None,None):
if ngr... | Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list |
def get_tp_from_file(file_path):
match = TP_FROM_FILE_REGEX.match(file_path)
if not match:
print("File path is not valid: " + file_path)
sys.exit(1)
return match.group(1) | Return the name of the topic-partition given the path to the file.
:param file_path: the path to the log file
:type file_path: str
:returns: the name of the topic-partition, ex. "topic_name-0"
:rtype: str |
def cursor(self, *cursors):
self._ensure_alive()
self._last_usage = self._loop.time()
try:
if cursors and \
any(not issubclass(cursor, Cursor) for cursor in cursors):
raise TypeError('Custom cursor must be subclass of Cursor')
except TypeEr... | Instantiates and returns a cursor
By default, :class:`Cursor` is returned. It is possible to also give a
custom cursor through the cursor_class parameter, but it needs to
be a subclass of :class:`Cursor`
:param cursor: custom cursor class.
:returns: instance of cursor, by defa... |
def query_fetch_one(self, query, values):
self.cursor.execute(query, values)
retval = self.cursor.fetchone()
self.__close_db()
return retval | Executes a db query, gets the first value, and closes the connection. |
def rpc_get_names(self, filename, source, offset):
names = jedi.api.names(source=source,
path=filename, encoding='utf-8',
all_scopes=True,
definitions=True,
references=True)
result... | Return the list of possible names |
def set_terminal(self, terminal):
if self.terminal is not None:
raise RuntimeError("TerminalBox: terminal already set")
self.terminal = terminal
self.terminal.connect("grab-focus", self.on_terminal_focus)
self.terminal.connect("button-press-event", self.on_button_press, None)... | Packs the terminal widget. |
def queuedb_append(path, queue_id, name, data):
sql = "INSERT INTO queue VALUES (?,?,?);"
args = (name, queue_id, data)
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cur = db.cursor()
res = queuedb_query_execute(cur, sql, args)
db.commit()
db.... | Append an element to the back of the queue.
Return True on success
Raise on error |
def returner(ret):
log.debug('sqlite3 returner <returner> called with data: %s', ret)
conn = _get_conn(ret)
cur = conn.cursor()
sql =
cur.execute(sql,
{'fun': ret['fun'],
'jid': ret['jid'],
'id': ret['id'],
'fun_args': six.text_type(... | Insert minion return data into the sqlite3 database |
def _connect(self, database=None):
conn_args = {
'host': self.config['host'],
'user': self.config['user'],
'password': self.config['password'],
'port': self.config['port'],
'sslmode': self.config['sslmode'],
}
if database:
c... | Connect to given database |
def transform_non_affine(self, x, mask_out_of_range=True):
if mask_out_of_range:
x_masked = np.ma.masked_where((x < self._xmin) | (x > self._xmax),
x)
else:
x_masked = x
return np.interp(x_masked, self._x_range, self._s_range) | Transform a Nx1 numpy array.
Parameters
----------
x : array
Data to be transformed.
mask_out_of_range : bool, optional
Whether to mask input values out of range.
Return
------
array or masked array
Transformed data. |
def compute_merkletree_with(
merkletree: MerkleTreeState,
lockhash: LockHash,
) -> Optional[MerkleTreeState]:
result = None
leaves = merkletree.layers[LEAVES]
if lockhash not in leaves:
leaves = list(leaves)
leaves.append(Keccak256(lockhash))
result = MerkleTreeState(... | Register the given lockhash with the existing merkle tree. |
def generate(env):
M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')
bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4')
env['BUILDERS']['M4'] = bld
env['M4'] = 'm4'
env['M4FLAGS'] = SCons.Util.CLVar('-E')
env['M4COM'] = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS < ${SOURCE.... | Add Builders and construction variables for m4 to an Environment. |
def persist_checksum(self, requirement, cache_file):
if not self.config.trust_mod_times:
checksum_file = '%s.txt' % cache_file
with AtomicReplace(checksum_file) as temporary_file:
with open(temporary_file, 'w') as handle:
handle.write('%s\n' % requirem... | Persist the checksum of the input used to generate a binary distribution.
:param requirement: A :class:`.Requirement` object.
:param cache_file: The pathname of a cached binary distribution (a string).
.. note:: The checksum is only calculated and persisted when
:attr:`~.Conf... |
def erode_edge(dem, iterations=1):
import scipy.ndimage as ndimage
print('Eroding pixels near nodata: %i iterations' % iterations)
mask = np.ma.getmaskarray(dem)
mask_dilate = ndimage.morphology.binary_dilation(mask, iterations=iterations)
out = np.ma.array(dem, mask=mask_dilate)
return out | Erode pixels near nodata |
def run(args, shell=False, exit=True):
if "GH_TOKEN" in os.environ:
token = get_token()
else:
token = b''
if not shell:
command = ' '.join(map(shlex.quote, args))
else:
command = args
command = command.replace(token.decode('utf-8'), '~'*len(token))
print(blue(comm... | Run the command ``args``.
Automatically hides the secret GitHub token from the output.
If shell=False (recommended for most commands), args should be a list of
strings. If shell=True, args should be a string of the command to run.
If exit=True, it exits on nonzero returncode. Otherwise it returns the... |
def _iterate_through_class(self, class_dict):
output_dict = {}
for key in class_dict:
val = class_dict[key]
try:
val = val.__dict__
except AttributeError:
pass
if type(val) is dict:
val = self._iterate_throug... | Recursive function for output dictionary creation.
Function will check each value in a dictionary to see if it is a
class, list, or dictionary object. The idea is to turn all class objects into
dictionaries. If it is a class object it will pass its ``class.__dict__``
recursively through... |
def etree_to_dict(tree):
d = {tree.tag.split('}')[1]: map(
etree_to_dict, tree.iterchildren()
) or tree.text}
return d | Translate etree into dictionary.
:param tree: etree dictionary object
:type tree: <http://lxml.de/api/lxml.etree-module.html> |
def secure(view):
AUTH = getattr(
settings,
'SLACKCHAT_AUTH_DECORATOR',
'django.contrib.admin.views.decorators.staff_member_required'
)
auth_decorator = import_class(AUTH)
return method_decorator(auth_decorator, name='dispatch')(view) | Set an auth decorator applied for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator. |
def parse_singular_int(t, tag_name):
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
v = pos.childNodes[0].data
assert(v.isdigit())
return int(v) | Parses the sole integer value with name tag_name in tag t. Heavy-handed with the asserts. |
def set_record(self, record, **kw):
if isstring(record):
card = FITSCard(record)
self.update(card)
self.verify()
else:
if isinstance(record, FITSRecord):
self.update(record)
elif isinstance(record, dict):
if 'nam... | check the record is valid and set keys in the dict
parameters
----------
record: string
Dict representing a record or a string representing a FITS header
card |
def gradient_log_joint(self, x):
T, D = self.T, self.D_latent
assert x.shape == (T, D)
_, h_init, _ = self.info_init_params
_, _, _, h1, h2, _ = self.info_dynamics_params
H_diag, H_upper_diag = self.sparse_J_prior
g = -1 * symm_block_tridiag_matmul(H_diag, H_upper_diag, x... | The gradient of the log joint probability.
For the Gaussian terms, this is
d/dx [-1/2 x^T J x + h^T x] = -Jx + h.
For the likelihood terms, we have for each time t
d/dx log p(yt | xt) |
def getShocks(self):
IndShockConsumerType.getShocks(self)
PrefShkNow = np.zeros(self.AgentCount)
for t in range(self.T_cycle):
these = t == self.t_cycle
N = np.sum(these)
if N > 0:
PrefShkNow[these] = self.RNG.permutation(approxMeanOneLognormal... | Gets permanent and transitory income shocks for this period as well as preference shocks.
Parameters
----------
None
Returns
-------
None |
def _handle_final_metric_data(self, data):
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
self.tuner.receive_trial_result(id_, _trial_params[id_... | Call tuner to process final results |
def parse_docstring(docstring):
short_desc = long_desc = ''
if docstring:
docstring = trim(docstring.lstrip('\n'))
lines = docstring.split('\n\n', 1)
short_desc = lines[0].strip().replace('\n', ' ')
if len(lines) > 1:
long_desc = lines[1].strip()
return short_desc... | Parse a PEP-257 docstring.
SHORT -> blank line -> LONG |
def print_all() -> None:
for code in sorted(term2hex_map):
print(' '.join((
'\033[48;5;{code}m{code:<3}:{hexval:<6}\033[0m',
'\033[38;5;{code}m{code:<3}:{hexval:<6}\033[0m'
)).format(code=code, hexval=term2hex_map[code])) | Print all 256 xterm color codes. |
def add_url(self, *args, **kwargs):
if len(args) == 1 and not kwargs and isinstance(args[0], UrlEntry):
self.urls.append(args[0])
else:
self.urls.append(UrlEntry(*args, **kwargs)) | Add a new url to the sitemap.
This function can either be called with a :class:`UrlEntry`
or some keyword and positional arguments that are forwarded to
the :class:`UrlEntry` constructor. |
def restore_grid(func):
@wraps(func)
def wrapped_func(self, *args, **kwargs):
grid = (self.xaxis._gridOnMinor, self.xaxis._gridOnMajor,
self.yaxis._gridOnMinor, self.yaxis._gridOnMajor)
try:
return func(self, *args, **kwargs)
finally:
self.xaxis.gr... | Wrap ``func`` to preserve the Axes current grid settings. |
def bind_type(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype, lifetime_manager: hexdi.core.ltype):
hexdi.core.get_root_container().bind_type(type_to_bind, accessor, lifetime_manager) | shortcut for bind_type on root container
:param type_to_bind: type that will be resolved by accessor
:param accessor: accessor for resolving object
:param lifetime_manager: type of lifetime manager for this binding |
def get_station_board(
self,
crs,
rows=17,
include_departures=True,
include_arrivals=False,
destination_crs=None,
origin_crs=None
):
if include_departures and include_arrivals:
query_type = 'GetArrivalDepartureBoard'
elif include_de... | Query the darwin webservice to obtain a board for a particular station
and return a StationBoard instance
Positional arguments:
crs -- the three letter CRS code of a UK station
Keyword arguments:
rows -- the number of rows to retrieve (default 10)
include_departures -- ... |
def add_child(self, child):
if self.type.lower() != "directory":
raise ValueError("Only directory objects can have children")
if child is self:
raise ValueError("Cannot be a child of itself!")
if child not in self._children:
self._children.append(child)
... | Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
... |
def recCopyElement(oldelement):
newelement = ETREE.Element(oldelement.tag, oldelement.attrib)
if len(oldelement.getchildren()) > 0:
for childelement in oldelement.getchildren():
newelement.append(recCopyElement(childelement))
return newelement | Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements |
def to_int(self):
num = self.to_uint()
if num and self._items[-1].unbox():
return num - (1 << self.size)
else:
return num | Convert vector to an integer, if possible.
This is only useful for arrays filled with zero/one entries. |
def plot_obsseries(self, **kwargs: Any) -> None:
self.__plot_series([self.sequences.obs], kwargs) | Plot the |IOSequence.series| of the |Obs| sequence object.
See method |Node.plot_allseries| for further information. |
def handle_channel_disconnected(self):
for namespace in self.app_namespaces:
if namespace in self._handlers:
self._handlers[namespace].channel_disconnected()
self.app_namespaces = []
self.destination_id = None
self.session_id = None | Handles a channel being disconnected. |
def parse_event(data, attendees=None, photos=None):
return MeetupEvent(
id=data.get('id', None),
name=data.get('name', None),
description=data.get('description', None),
time=parse_datetime(data.get('time', None),
data.get('utc_offset', None)),
stat... | Parse a ``MeetupEvent`` from the given response data.
Returns
-------
A ``pythonkc_meetups.types.MeetupEvent``. |
def get_definition(self, stmt: Statement,
sctx: SchemaContext) -> Tuple[Statement, SchemaContext]:
if stmt.keyword == "uses":
kw = "grouping"
elif stmt.keyword == "type":
kw = "typedef"
else:
raise ValueError("not a 'uses' or 'type' stat... | Find the statement defining a grouping or derived type.
Args:
stmt: YANG "uses" or "type" statement.
sctx: Schema context where the definition is used.
Returns:
A tuple consisting of the definition statement ('grouping' or
'typedef') and schema context o... |
def _get_avaliable_tasks(self):
base_task = posixpath.join(self._queue_path, self.TASK_PREFIX)
tasks = self._client.kv.find(prefix=base_task)
return sorted(tasks.items()) | Get all tasks present in the queue. |
def get_interleave_mask():
nodemask = nodemask_t()
bitmask = libnuma.numa_get_interleave_mask()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask) | Get interleave mask for current thread.
@return: node mask
@rtype: C{set} |
def get_event(self):
if not self.is_event_message:
return None
query = self.q().select('subject').expand('event')
url = self.build_url(self._endpoints.get('get_message').format(id=self.object_id))
response = self.con.get(url, params=query.as_params())
if not response:... | If this is a EventMessage it should return the related Event |
def delete(self):
session = self._session
url = session._build_url(self._resource_path(), self.id)
return session.delete(url, CB.boolean(204)) | Delete the resource.
Returns:
True if the delete is successful. Will throw an error if
other errors occur |
def generate(env,**kw):
import SCons.Util
from SCons.Tool.GettextCommon import _detect_msginit
try:
env['MSGINIT'] = _detect_msginit(env)
except:
env['MSGINIT'] = 'msginit'
msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \
+ ' $MSGINITFLAGS -i $SOURCE -o $TARGET'... | Generate the `msginit` tool |
def scan_results(self):
bsses = self._wifi_ctrl.scan_results(self._raw_obj)
if self._logger.isEnabledFor(logging.INFO):
for bss in bsses:
self._logger.info("Find bss:")
self._logger.info("\tbssid: %s", bss.bssid)
self._logger.info("\tssid: %s",... | Return the scan result. |
def getTextualNode(self, subreference=None):
if isinstance(subreference, URN):
urn = str(subreference)
elif isinstance(subreference, CtsReference):
urn = "{0}:{1}".format(self.urn, str(subreference))
elif isinstance(subreference, str):
if ":" in subreference:
... | Retrieve a passage and store it in the object
:param subreference: CtsReference of the passage (Note : if given a list, this should be a list of string that \
compose the reference)
:type subreference: Union[CtsReference, URN, str, list]
:rtype: CtsPassage
:returns: Object repre... |
def create_config_map(self, name, data):
config_data_file = os.path.join(self.os_conf.get_build_json_store(), 'config_map.json')
with open(config_data_file) as f:
config_data = json.load(f)
config_data['metadata']['name'] = name
data_dict = {}
for key, value in data.i... | Create an ConfigMap object on the server
Raises exception on error
:param name: str, name of configMap
:param data: dict, dictionary of data to be stored
:returns: ConfigMapResponse containing the ConfigMap with name and data |
def greedy_mapping(self, reference, hypothesis, uem=None):
if uem:
reference, hypothesis = self.uemify(reference, hypothesis, uem=uem)
return self.mapper_(hypothesis, reference) | Greedy label mapping
Parameters
----------
reference : Annotation
hypothesis : Annotation
Reference and hypothesis diarization
uem : Timeline
Evaluation map
Returns
-------
mapping : dict
Mapping between hypothesis (ke... |
def create_ssl_certs(self):
for key, file in self.ssl.items():
file["file"] = self.create_temp_file(file["suffix"], file["content"]) | Creates SSL cert files |
def lstsq(A, b):
r
A = asarray(A, float)
b = asarray(b, float)
if A.ndim == 1:
A = A[:, newaxis]
if A.shape[1] == 1:
return dot(A.T, b) / squeeze(dot(A.T, A))
rcond = finfo(double).eps * max(*A.shape)
return npy_lstsq(A, b, rcond=rcond)[0] | r"""Return the least-squares solution to a linear matrix equation.
Args:
A (array_like): Coefficient matrix.
b (array_like): Ordinate values.
Returns:
:class:`numpy.ndarray`: Least-squares solution. |
def get_eargs():
settings = {}
zmq = os.environ.get("ZMQ_PREFIX", None)
if zmq is not None:
debug("Found environ var ZMQ_PREFIX=%s" % zmq)
settings['zmq_prefix'] = zmq
return settings | Look for options in environment vars |
def parse_hosted_zones(self, hosted_zone, params):
hosted_zone_id = hosted_zone.pop('Id')
hosted_zone['name'] = hosted_zone.pop('Name')
api_client = params['api_client']
record_sets = handle_truncated_response(api_client.list_resource_record_sets, {'HostedZoneId': hosted_zone_id}, ['Reso... | Parse a single Route53hosted_zoness hosted_zones |
def switch_schema(task, kwargs, **kw):
from .compat import get_public_schema_name, get_tenant_model
old_schema = (connection.schema_name, connection.include_public_schema)
setattr(task, '_old_schema', old_schema)
schema = (
get_schema_name_from_task(task, kwargs) or
get_public_schema_nam... | Switches schema of the task, before it has been run. |
def _fetch_channels(self):
json = requests.get(self._channels_url).json()
self._channels = {c['channel']['code']: c['channel']['name']
for c in json['channels']} | Retrieve Ziggo channel information. |
def create_organizations_parser(stream):
import sortinghat.parsing as parsing
for p in parsing.SORTINGHAT_ORGS_PARSERS:
klass = parsing.SORTINGHAT_ORGS_PARSERS[p]
parser = klass()
if parser.check(stream):
return parser
raise InvalidFormatError(cause=INVALID_FORMAT_MSG) | Create an organizations parser for the given stream.
Factory function that creates an organizations parser for the
given stream. The stream is only used to guess the type of the
required parser.
:param stream: stream used to guess the type of the parser
:returns: an organizations parser
:rai... |
def get_parent(self, level=1):
try:
parent_path = self.path.get_parent(level)
except ValueError:
return None
assert parent_path
return DirectoryInfo(parent_path) | get parent dir as a `DirectoryInfo`.
return `None` if self is top. |
def clean(self):
for _, item in self.queue.items():
if item['status'] in ['paused', 'running', 'stopping', 'killing']:
item['status'] = 'queued'
item['start'] = ''
item['end'] = '' | Clean queue items from a previous session.
In case a previous session crashed and there are still some running
entries in the queue ('running', 'stopping', 'killing'), we clean those
and enqueue them again. |
def _deposit_payload(to_deposit):
pubsub = to_deposit['pubsub']
id = to_deposit['id']
with r_client.pipeline() as pipe:
pipe.set(id, json.dumps(to_deposit), ex=REDIS_KEY_TIMEOUT)
pipe.publish(pubsub, json.dumps({"update": [id]}))
pipe.execute() | Store job info, and publish an update
Parameters
----------
to_deposit : dict
The job info |
def get_fitness(self, solution):
return self._fitness_function(solution, *self._fitness_args,
**self._fitness_kwargs) | Return fitness for the given solution. |
def metabolites_per_compartment(model, compartment_id):
return [met for met in model.metabolites
if met.compartment == compartment_id] | Identify all metabolites that belong to a given compartment.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
compartment_id : string
Model specific compartment identifier.
Returns
-------
list
List of metabolites belonging to a giv... |
def get_each_choice(self, cls=None, **kwargs):
defaults = {attr: kwargs[attr][0] for attr in kwargs}
for set_of_values in izip_longest(*kwargs.values()):
case = cls() if cls else self._CasesClass()
for attr, value in izip(kwargs.keys(), set_of_values):
if value is... | Returns a generator that generates positive cases by
"each choice" algorithm. |
def clear(self):
super(SuperChange, self).clear()
for c in self.changes:
c.clear()
self.changes = tuple() | clears all child changes and drops the reference to them |
def split_code(cls, code, PS1, PS2):
processed_lines = []
for line in textwrap.dedent(code).splitlines():
if not line or line.startswith(PS1) or line.startswith(PS2):
processed_lines.append(line)
continue
assert len(processed_lines) > 0, 'code impr... | Splits the given string of code based on the provided PS1 and PS2
symbols.
PARAMETERS:
code -- str; lines of interpretable code, using PS1 and PS2 prompts
PS1 -- str; first-level prompt symbol
PS2 -- str; second-level prompt symbol
RETURN:
list; a processed se... |
def _set_env(self, env):
for callback in self.callbacks:
if callable(getattr(callback, '_set_env', None)):
callback._set_env(env) | Set environment for each callback in callbackList |
def color_diffs(string):
string = string.replace('--- ', color('--- ', 'red'))
string = string.replace('\n+++ ', color('\n+++ '))
string = string.replace('\n-', color('\n-', 'red'))
string = string.replace('\n+', color('\n+'))
string = string.replace('\n@@ ', color('\n@@ ', 'yel'))
return string | Add color ANSI codes for diff lines.
Purpose: Adds the ANSI/win32 color coding for terminal output to output
| produced from difflib.
@param string: The string to be replacing
@type string: str
@returns: The new string with ANSI codes injected.
@rtype: str |
def is_duplicate_edge(data, data_other):
is_dupe = False
osmid = set(data['osmid']) if isinstance(data['osmid'], list) else data['osmid']
osmid_other = set(data_other['osmid']) if isinstance(data_other['osmid'], list) else data_other['osmid']
if osmid == osmid_other:
if ('geometry' in data) and ... | Check if two edge data dictionaries are the same based on OSM ID and
geometry.
Parameters
----------
data : dict
the first edge's data
data_other : dict
the second edge's data
Returns
-------
is_dupe : bool |
def get_user_matches(session, user_id, from_timestamp=None, limit=None):
return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format(
session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit) | Get recent matches by user. |
def compile_output(self, input_sample, num_samples, num_params,
maximum_combo, num_groups=None):
if num_groups is None:
num_groups = num_params
self.check_input_sample(input_sample, num_groups, num_samples)
index_list = self._make_index_list(num_samples, num_pa... | Picks the trajectories from the input
Arguments
---------
input_sample : numpy.ndarray
num_samples : int
num_params : int
maximum_combo : list
num_groups : int |
def request_error_header(exception):
from .conf import options
header = "Bearer realm=\"%s\"" % (options.realm, )
if hasattr(exception, "error"):
header = header + ", error=\"%s\"" % (exception.error, )
if hasattr(exception, "reason"):
header = header + ", error_description=\"%s\"" % (ex... | Generates the error header for a request using a Bearer token based on a given OAuth exception. |
def _get_kvc(kv_arg):
if isinstance(kv_arg, Mapping):
return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)
assert 2 <= len(kv_arg) <= 3, \
'Argument must be a mapping or a sequence (keys, values, [len])'
return (
kv_arg[0],
kv_arg[1],
kv_arg[2] if len(kv_a... | Returns a tuple keys, values, count for kv_arg (which can be a dict or a
tuple containing keys, values and optinally count. |
def decode_pdf_date(s: str) -> datetime:
if isinstance(s, String):
s = str(s)
if s.startswith('D:'):
s = s[2:]
if s.endswith("Z00'00'"):
s = s.replace("Z00'00'", '+0000')
elif s.endswith('Z'):
s = s.replace('Z', '+0000')
s = s.replace("'", "")
try:
return ... | Decode a pdfmark date to a Python datetime object
A pdfmark date is a string in a paritcular format. See the pdfmark
Reference for the specification. |
def chown(self, uid=-1, gid=-1):
if hasattr(os, 'chown'):
if 'pwd' in globals() and isinstance(uid, str):
uid = pwd.getpwnam(uid).pw_uid
if 'grp' in globals() and isinstance(gid, str):
gid = grp.getgrnam(gid).gr_gid
os.chown(self, uid, gid)
... | Change the owner and group by names rather than the uid or gid numbers.
.. seealso:: :func:`os.chown` |
def _check_existing_logger(loggername, short_name):
if loggername in LOGGERS:
if isinstance(LOGGERS[loggername], BenchLoggerAdapter):
if ("source" not in LOGGERS[loggername].extra or
LOGGERS[loggername].extra["source"] != short_name):
LOGGERS[loggername].extra... | Check if logger with name loggername exists.
:param loggername: Name of logger.
:param short_name: Shortened name for the logger.
:return: Logger or None |
def get_client_key_exchange_record(
cls,
robot_payload_enum: RobotPmsPaddingPayloadEnum,
tls_version: TlsVersionEnum,
modulus: int,
exponent: int
) -> TlsRsaClientKeyExchangeRecord:
pms_padding = cls._compute_pms_padding(modulus)
tls_versio... | A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding. |
def format(self, fmt):
_fmt_params = {
'base': self.base,
'bin': self.bin,
'binary': self.binary,
'bits': self.bits,
'bytes': self.bytes,
'power': self.power,
'system': self.system,
'unit': self.unit,
'un... | Return a representation of this instance formatted with user
supplied syntax |
def _resolve_method(self, request):
try:
return getattr(requests, request.method.lower())
except AttributeError:
raise ApiClientException(
"Invalid request method: {}".format(request.method)) | Resolve the method from request object to `requests` http
call.
:param request: Request to dispatch to the ApiClient
:type request: ApiClientRequest
:return: The HTTP method that maps to the request call.
:rtype: Callable
:raises :py:class:`ask_sdk_core.exceptions.ApiCli... |
async def handle(self, record):
if (not self.disabled) and self.filter(record):
await self.callHandlers(record) | Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied. |
def load_devices(self):
self._devices = []
if os.path.exists(self._devices_filename):
log.debug(
"loading devices from '{}'...".format(self._devices_filename)
)
with codecs.open(self._devices_filename, "rb", "utf-8") as f:
self._devices... | load stored devices from the local file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.