text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def hash32(data: Any, seed=0) -> int:
"""
Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 32-bit integer
"""
with MultiTimerContext(timer, TIMING_HASH):
c_data = to_str(data)
if mmh3:
return mm... | 0.002012 |
def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={}):
"""
Checks parameters for pairwise alignment, returns alignment.
Code from Greg Caporaso.
"""
seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False)
try:
s1, s2 = seqs.values()
except ValueError:
... | 0.001188 |
def get_pltpat(self, plt_ext="svg"):
"""Return png pattern: {BASE}.png {BASE}_pruned.png {BASE}_upper_pruned.png"""
if self.ntplt.desc == "":
return ".".join(["{BASE}", plt_ext])
return "".join(["{BASE}_", self.ntplt.desc, ".", plt_ext]) | 0.010989 |
def run(func):
"""Execute the provided function if there are no subcommands"""
@defaults.command(help='Run the service')
@click.pass_context
def runserver(ctx, *args, **kwargs):
if (ctx.parent.invoked_subcommand and
ctx.command.name != ctx.parent.invoked_subcommand):
... | 0.001718 |
def list_jobs(config, *, status=JobStatus.Active,
filter_by_type=None, filter_by_worker=None):
""" Return a list of Celery jobs.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
status (JobStatus): The status of the jo... | 0.002132 |
def render_children(self, element):
"""
Recursively renders child elements. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between elements, add them
in their respective templates, or override this function
in the renderer subclass, ... | 0.003378 |
def query(self, w, ed=1): # Can only handle ed=1
"""
Finds the fuzzy matches (within edit distance 1) of w from words
"""
assert ed <= self._ed
if ed == 0:
return [w] if w in self._L else ['']
w = str(w)
n = len(w)
prefix, suffix = w[:n // 2]... | 0.006061 |
def delete(config, username, type):
"""Delete an LDAP user."""
client = Client()
client.prepare_connection()
user_api = API(client)
user_api.delete(username, type) | 0.009852 |
def comment_unvote(self, comment_id):
"""Lets you unvote a specific comment (Requires login).
Parameters:
comment_id (int):
"""
return self._get('posts/{0}/unvote.json'.format(comment_id),
method='POST', auth=True) | 0.007042 |
def lower_band(close_data, high_data, low_data, period):
"""
Lower Band.
Formula:
LB = CB - BW
"""
cb = center_band(close_data, high_data, low_data, period)
bw = band_width(high_data, low_data, period)
lb = cb - bw
return lb | 0.003831 |
def checkReference(self, reference):
"""
Check the reference for security. Tries to avoid any characters
necessary for doing a script injection.
"""
pattern = re.compile(r'[\s,;"\'&\\]')
if pattern.findall(reference.strip()):
return False
return True | 0.006289 |
def intervalsubtract(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False):
"""
Subtract intervals in the right hand table from intervals in the left hand
table.
"""
assert (lkey is None) == (rkey is None), \
... | 0.005 |
def binPack(self, jobShapes):
"""Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times."""
# TODO: Check for redundancy with batchsystems.mesos.JobQueue() sorting
logger.debug('Running bin packing for node shapes %s and %s job(s).',
self.nodeSh... | 0.005961 |
def string_avg(strings, binary=True):
"""
Takes a list of strings of equal length and returns a string containing
the most common value from each index in the string.
Optional argument: binary - a boolean indicating whether or not to treat
strings as binary numbers (fill in leading zeros if lengths... | 0.001149 |
def get_steam():
"""
Returns a Steam object representing the current Steam installation on the
users computer. If the user doesn't have Steam installed, returns None.
"""
# Helper function which checks if the potential userdata directory exists
# and returns a new Steam instance with that userdata directory... | 0.014946 |
def connect(*, dsn, autocommit=False, ansi=False, timeout=0, loop=None,
executor=None, echo=False, after_created=None, **kwargs):
"""Accepts an ODBC connection string and returns a new Connection object.
The connection string can be passed as the string `str`, as a list of
keywords,or a combina... | 0.000656 |
def lindbladR(self,OmegaP,m=2,**kwargs):
"""
NAME:
lindbladR
PURPOSE:
calculate the radius of a Lindblad resonance
INPUT:
OmegaP - pattern speed (can be Quantity)
m= order of the resonance... | 0.026936 |
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
"""Writes MNIST image/label vectors into parallelized files on HDFS"""
# load MNIST gzip into memory
with open(input_images, 'rb') as f:
images = numpy.array(mnist.extract_images(f))
with open(input_labels, 'rb') as f:
if f... | 0.01451 |
def get_utc_iso_date(date_str):
"""Convert date str into a iso-formatted UTC date str, i.e.:
yyyymmddhhmmss
:type date_str: str
:param date_str: date string to be parsed.
:rtype: str
:returns: iso-formatted UTC date str.
"""
try:
utc_tuple = dateutil.parser.parse(date_str).utc... | 0.002372 |
def sc_dist(self, viewer, event, msg=True):
"""Interactively change the color distribution algorithm
by scrolling.
"""
direction = self.get_direction(event.direction)
self._cycle_dist(viewer, msg, direction=direction)
return True | 0.00722 |
def aggregate(self):
""" Aggregate all merges into the target branch
If the target_dir doesn't exist, create an empty git repo otherwise
clean it, add all remotes , and merge all merges.
"""
logger.info('Start aggregation of %s', self.cwd)
target_dir = self.cwd
i... | 0.002137 |
def from_variant_and_transcript(
cls,
variant,
transcript,
context_size):
"""
Extracts the reference sequence around a variant locus on a particular
transcript and determines the reading frame at the start of that
sequence context.
... | 0.001603 |
def channels_twitter_ticket_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/twitter_channel#create-ticket-from-tweet"
api_path = "/api/v2/channels/twitter/tickets.json"
return self.call(api_path, method="POST", data=data, **kwargs) | 0.010453 |
def com_google_fonts_check_repo_dirname_match_nameid_1(fonts,
gfonts_repo_structure):
"""Directory name in GFonts repo structure must
match NameID 1 of the regular."""
from fontTools.ttLib import TTFont
from fontbakery.utils import (get_name_entry_string... | 0.013321 |
def needsquoting(c, quotetabs, header):
"""Decide whether a particular character needs to be quoted.
The 'quotetabs' flag indicates whether embedded tabs and spaces should be
quoted. Note that line-ending tabs and spaces are always encoded, as per
RFC 1521.
"""
if c in ' \t':
return qu... | 0.002062 |
def get_belapi_handle(client, username=None, password=None):
"""Get BEL API arango db handle"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belapi"
try:
if username and passwor... | 0.002846 |
def handle_error(self, error: Exception) -> None:
"""
Populates :data:`chess.pgn.Game.errors` with encountered errors and
logs them.
"""
LOGGER.exception("error during pgn parsing")
self.game.errors.append(error) | 0.007692 |
def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Performs SNMP GETNEXT query.
Based on passed parameters, prepares SNMP GETNEXT packet
(:RFC:`1905#section-4.2.2`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time... | 0.001945 |
def gen_front_term(self, x, dmp_num):
"""Generates the front term on the forcing term.
For rhythmic DMPs it's non-diminishing, so this
function is just a placeholder to return 1.
x float: the current value of the canonical system
dmp_num int: the index of the current dmp
... | 0.009412 |
def read(self, nrml_file, validate=False,
simple_fault_spacing=1.0, complex_mesh_spacing=5.0,
mfd_spacing=0.1):
"""
Build the source model from nrml format
"""
self.source_file = nrml_file
if validate:
converter = SourceConverter(1.0, simple_... | 0.003636 |
def find_method_params(self):
"""Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs
"""
req = self.request
args = req.controller_info["method_args"]
kwargs = req.controller_info["method_kwargs"]
return args, kwargs | 0.006349 |
def auto_set_dir(action=None, name=None):
"""
Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running"""
mod = sys.modules['__main__']
basename = os.path.basename(mod.__file__)
auto_dirname = ... | 0.003906 |
def participant_names(self):
'''The names of the RTObjects participating in this context.'''
with self._mutex:
return [obj.get_component_profile().instance_name \
for obj in self._participants] | 0.012448 |
def sweHouses(jd, lat, lon, hsys):
""" Returns lists of houses and angles. """
hsys = SWE_HOUSESYS[hsys]
hlist, ascmc = swisseph.houses(jd, lat, lon, hsys)
# Add first house to the end of 'hlist' so that we
# can compute house sizes with an iterator
hlist += (hlist[0],)
houses = [
{... | 0.005391 |
def make_python_xref_nodes_for_type(py_type, state, hide_namespace=False):
"""Make docutils nodes containing a cross-reference to a Python object,
given the object's type.
Parameters
----------
py_type : `obj`
Type of an object. For example ``mypackage.mymodule.MyClass``. If you
hav... | 0.000753 |
def toggle_keyboard(cls, flag=HIDE_IMPLICIT_ONLY):
""" Toggle the keyboard on and off
Parameters
----------
flag: int
Flag to send to toggleSoftInput
Returns
--------
result: future
Resolves when the togg... | 0.008591 |
def angsep2(lon_1, lat_1, lon_2, lat_2):
"""
Angular separation (deg) between two sky coordinates.
"""
import healpy
v10, v11, v12 = healpy.ang2vec(np.radians(90. - lat_1), np.radians(lon_1)).transpose()
v20, v21, v22 = healpy.ang2vec(np.radians(90. - lat_2), np.radians(lon_2)).transpose()
... | 0.006897 |
def unregister(self, bucket, name):
"""
Remove the function from the registry by name
"""
assert bucket in self, 'Bucket %s is unknown' % bucket
if not name in self[bucket]:
raise NotRegistered('The function %s is not registered' % name)
del self[bucket][name] | 0.009375 |
def process_seq(seq, material):
'''Validate and process sequence inputs.
:param seq: input sequence
:type seq: str
:param material: DNA, RNA, or peptide
:type: str
:returns: Uppercase version of `seq` with the alphabet checked by
check_alphabet().
:rtype: str
'''
chec... | 0.002618 |
def close(self):
'''Stop running timers.'''
if self._call_later_handle:
self._call_later_handle.cancel()
self._running = False | 0.01227 |
def scan(cls, result_key, func):
"""
Define computed fields based on a string to "grep for". This is
preferred to utilizing raw log lines in plugins because computed fields
will be serialized, whereas raw log lines will not.
"""
if result_key in cls.scanner_keys:
... | 0.005137 |
def not_present(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up accor... | 0.001332 |
def restore_layout(self, name, *args):
"""
Restores given layout.
:param name: Layout name.
:type name: unicode
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
"""
layout = self.__layouts.get(name)
... | 0.008339 |
def _initialize_workflow(self):
"""
**Purpose**: Initialize the PST of the workflow with a uid and type checks
"""
try:
self._prof.prof('initializing workflow', uid=self._uid)
for p in self._workflow:
p._assign_uid(self._sid)
self._... | 0.005758 |
def express_route_cross_connections(self):
"""Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionsOperations>`
* 2018-04-01: :class:`ExpressRouteCrossConnectionsOperations<a... | 0.007715 |
def parseXRDS(text):
"""Parse the given text as an XRDS document.
@return: ElementTree containing an XRDS document
@raises XRDSError: When there is a parse error or the document does
not contain an XRDS.
"""
try:
element = ElementTree.XML(text)
except XMLError, why:
exc... | 0.001761 |
def make_catalog_sources(catalog_roi_model, source_names):
"""Construct and return dictionary of sources that are a subset of sources
in catalog_roi_model.
Parameters
----------
catalog_roi_model : dict or `fermipy.roi_model.ROIModel`
Input set of sources
source_names : list
N... | 0.001776 |
def configure_logging(self, context):
"""
Configure logging for the application.
:param context:
The guacamole context object.
This method attaches a :py:class:logging.StreamHandler` with a
subclass of :py:class:`logging.Formatter` to the root logger. The
sp... | 0.002706 |
def note(name, source=None, contents=None, **kwargs):
'''
Add content to a document generated using `highstate_doc.render`.
This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers
to include extra documents.
.. code-block:: yaml
{{sls}} exa... | 0.002967 |
def adjust_tuning(input_file, output_file):
'''Load audio, estimate tuning, apply pitch correction, and save.'''
print('Loading ', input_file)
y, sr = librosa.load(input_file)
print('Separating harmonic component ... ')
y_harm = librosa.effects.harmonic(y)
print('Estimating tuning ... ')
#... | 0.001387 |
def PathToComponents(path):
"""Converts a canonical path representation to a list of components.
Args:
path: A canonical MySQL path representation.
Returns:
A sequence of path components.
"""
precondition.AssertType(path, Text)
if path and not path.startswith("/"):
raise ValueError("Path '{}' ... | 0.014218 |
def _get_question(self, qcount):
"""Read the next I{qcount} records from the wire data and add them to
the question section.
@param qcount: the number of questions in the message
@type qcount: int"""
if self.updating and qcount > 1:
raise dns.exception.FormError
... | 0.00385 |
def draw(self):
"""
Draw the figure using the renderer
"""
if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying')
self.renderer = self.get_renderer(cleared=True)
# acquire a lock on the shared font cache
RendererAgg.lock.acquire()
try:
... | 0.007194 |
def projection(self, plain_src_name):
"""Return the projection for the given source namespace."""
mapped = self.lookup(plain_src_name)
if not mapped:
return None
fields = mapped.include_fields or mapped.exclude_fields
if fields:
include = 1 if mapped.inclu... | 0.004785 |
def register_id(self, cmd_type, obj):
"""Registers an object (through its integration id) to receive update
notifications. This is the core mechanism how Output and Keypad objects get
notified when the controller sends status updates."""
ids = self._ids.setdefault(cmd_type, {})
if obj.id in ids:
... | 0.005115 |
def get_matrix(self, x1=None, x2=None, include_diagonal=None,
include_general=None):
"""
Get the covariance matrix at given independent coordinates
Args:
x1 (Optional[array[n1]]): The first set of independent coordinates.
If this is omitted, ``x1``... | 0.001665 |
def _load_credentials(self):
"""(Re-)loads the credentials from the file."""
if not self._file:
return
loaded_credentials = _load_credentials_file(self._file)
self._credentials.update(loaded_credentials)
logger.debug('Read credential file') | 0.006803 |
def plot_xtf(fignum, XTF, Fs, e, b):
"""
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
"""
plt.figure(num=fignum)
plt.xlabel('Temperature (K)')
plt.ylabel('Susceptibility (m^3/kg)')
k = 0
Flab = []
for freq in X... | 0.003257 |
def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwargs: typing.Any,
) -> None:
"""Start up the... | 0.000929 |
def xadd(self, name, fields, id='*', maxlen=None, approximate=True):
"""
Add to a stream.
name: name of the stream
fields: dict of field/value pairs to insert into the stream
id: Location to insert this record. By default it is appended.
maxlen: truncate old stream member... | 0.001862 |
def step(self, x):
r"""perform a single Brownian dynamics step"""
return x - self.coeff_A * self.gradient(x) \
+ self.coeff_B * np.random.normal(size=self.dim) | 0.015789 |
def eleventh(note):
"""Build an eleventh chord on note.
Example:
>>> eleventh('C')
['C', 'G', 'Bb', 'F']
"""
return [note, intervals.perfect_fifth(note), intervals.minor_seventh(note),
intervals.perfect_fourth(note)] | 0.003953 |
def _apply_to_sets(self, func, operation, keys, *args):
"""Helper function for sdiff, sinter, and sunion"""
keys = self._list_or_args(keys, args)
if not keys:
raise TypeError("{} takes at least two arguments".format(operation.lower()))
left = self._get_set(keys[0], operation)... | 0.006329 |
def _is_epsilon_nash(x, g, epsilon, indptr=None):
"""
Determine whether `x` is an `epsilon`-Nash equilibrium of `g`.
Parameters
----------
x : array_like(float, ndim=1)
Array of flattened mixed action profile of length equal to n_0 +
... + n_N-1, where `out[indptr[i]:indptr[i+1]]` c... | 0.001112 |
def _stmt_location_to_agents(stmt, location):
"""Apply an event location to the Agents in the corresponding Statement.
If a Statement is in a given location we represent that by requiring all
Agents in the Statement to be in that location.
"""
if location is None:
return
agents = stmt.a... | 0.002427 |
def get_facet_serializer_class(self):
"""
Return the class to use for serializing facets.
Defaults to using ``self.facet_serializer_class``.
"""
if self.facet_serializer_class is None:
raise AttributeError(
"%(cls)s should either include a `facet_seria... | 0.005682 |
def _process_rval_components(self):
"""This is suspiciously similar to _process_macro_default_arg, probably
want to figure out how to merge the two.
Process the rval of an assignment statement or a do-block
"""
while True:
match = self._expect_match(
... | 0.001386 |
def vectors(self, direction="all", failed=False):
"""Get vectors that connect at this node.
Direction can be "incoming", "outgoing" or "all" (default).
Failed can be True, False or all
"""
# check direction
if direction not in ["all", "incoming", "outgoing"]:
... | 0.001087 |
def jsonify_status_code(status_code, *args, **kw):
"""Returns a jsonified response with the specified HTTP status code.
The positional and keyword arguments are passed directly to the
:func:`flask.jsonify` function which creates the response.
"""
is_batch = kw.pop('is_batch', False)
if is_batch... | 0.001684 |
def _cwl_workflow_template(inputs, top_level=False):
"""Retrieve CWL inputs shared amongst different workflows.
"""
ready_inputs = []
for inp in inputs:
cur_inp = copy.deepcopy(inp)
for attr in ["source", "valueFrom", "wf_duplicate"]:
cur_inp.pop(attr, None)
if top_le... | 0.002137 |
def get_current_branch():
"""
Return the current branch
"""
cmd = ["git", "rev-parse", "--abbrev-ref", "HEAD"]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
return output.strip().decode("utf-8") | 0.004237 |
def get_source_variable(self, source_id, variable):
""" Get the current value of a source variable. If the variable is not
in the cache it will be retrieved from the controller. """
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
... | 0.004149 |
def run_toy_DistilledSGLD(gpu_id):
"""Run DistilledSGLD on toy dataset"""
X, Y, X_test, Y_test = load_toy()
minibatch_size = 1
teacher_noise_precision = 1.0
teacher_net = get_toy_sym(True, teacher_noise_precision)
student_net = get_toy_sym(False)
data_shape = (minibatch_size,) + X.shape[1::]... | 0.005042 |
def get_link_url(self, datum=None):
"""Returns the final URL based on the value of ``url``.
If ``url`` is callable it will call the function.
If not, it will then try to call ``reverse`` on ``url``.
Failing that, it will simply return the value of ``url`` as-is.
When called for... | 0.001741 |
def matrix(mat):
"""Convert a ROOT TMatrix into a NumPy matrix.
Parameters
----------
mat : ROOT TMatrixT
A ROOT TMatrixD or TMatrixF
Returns
-------
mat : numpy.matrix
A NumPy matrix
Examples
--------
>>> from root_numpy import matrix
>>> from ROOT import ... | 0.001098 |
def prepare_message(self, message_data, delivery_mode, priority=None,
content_type=None, content_encoding=None):
"""Encapsulate data into a AMQP message."""
properties = pika.BasicProperties(priority=priority,
content_type=content_type,
... | 0.006073 |
def is_modified(self) -> bool:
"""
Find whether the files on the left and right are different. Note,
modified implies the contents of the file have changed, which is
predicated on the file existing on both the left and right. Therefore
this will be false if the file on the left h... | 0.003584 |
def target_group_exists(name,
region=None,
key=None,
keyid=None,
profile=None):
'''
Check to see if an target group exists.
CLI example:
.. code-block:: bash
salt myminion boto_elbv2.target_group_e... | 0.002959 |
def is_parseable (self):
"""
Check if content is parseable for recursion.
@return: True if content is parseable
@rtype: bool
"""
if not self.valid:
return False
# some content types must be validated with the page content
if self.content_type ... | 0.005457 |
def read(filename,ext=None,swapyz=False):
"""
NAME:
read
PURPOSE:
read a NEMO snapshot file consisting of mass,position,velocity
INPUT:
filename - name of the file
ext= if set, 'nemo' for NEMO binary format, otherwise assumed ASCII; if not set, gleaned from extension
s... | 0.025675 |
def get_server(self, key, **kwds):
"""
Get a new or existing server for this key.
:param int key: key for the server to use
"""
kwds = dict(self.kwds, **kwds)
server = self.servers.get(key)
if server:
# Make sure it's the right server.
ser... | 0.003745 |
def parseString(txt, cip=True):
"""
Parse string `txt` and return DOM tree consisting of single linked
:class:`.HTMLElement`.
Args:
txt (str): HTML/XML string, which will be parsed to DOM.
cip (bool, default True): Case Insensitive Parameters. Use special
dictionary to store... | 0.000871 |
def check_filemode(filepath, mode):
"""Return True if 'file' matches ('permission') which should be entered in octal.
"""
filemode = stat.S_IMODE(os.stat(filepath).st_mode)
return (oct(filemode) == mode) | 0.009091 |
def parse_glob(path, included):
"""Parse a glob."""
files = glob.glob(path, recursive=True)
array = []
for file in files:
file = os.path.abspath(file)
if file not in included:
array.append(file)
included += array
return array | 0.041494 |
def guest_register(self, userid, meta, net_set):
"""DB operation for migrate vm from another z/VM host in same SSI
:param userid: (str) the userid of the vm to be relocated or tested
:param meta: (str) the metadata of the vm to be relocated or tested
:param net_set: (str) the net_set of ... | 0.001223 |
def from_path_by_size(dir_path, min_size=0, max_size=1 << 40):
"""Create a new FileCollection, and select all files that size in
a range::
dir_path = "your/path"
# select by file size larger than 100MB
fc = FileCollection.from_path_by_size(
... | 0.006667 |
def get_crystal_system(self):
"""
Get the crystal system for the structure, e.g., (triclinic,
orthorhombic, cubic, etc.).
Returns:
(str): Crystal system for structure or None if system cannot be detected.
"""
n = self._space_group_data["number"]
f = ... | 0.005442 |
def _sanitize_instance_name(name, max_length):
"""Instance names must start with a lowercase letter.
All following characters must be a dash, lowercase letter,
or digit.
"""
name = str(name).lower() # make all letters lowercase
name = re.sub(r'[^-a-z0-9]', '', name) # remove inva... | 0.001825 |
def close_socket(self):
"""
Correctly closes the socket
:return:
"""
try:
self.docker_py_sock._sock.close() # pylint: disable=protected-access
except AttributeError:
pass
self.docker_py_sock.close() | 0.010753 |
def DbPutDeviceAttributeProperty(self, argin):
""" Create/Update device attribute property(ies) in database
:param argin: Str[0] = Device name
Str[1] = Attribute number
Str[2] = Attribute name
Str[3] = Property number
Str[4] = Property name
Str[5] = Property valu... | 0.004688 |
def config(self, body):
"""Configure the email provider.
Args:
body (dict): Please see: https://auth0.com/docs/api/v2#!/Emails/post_provider
"""
return self.client.post(self._url(), data=body) | 0.012658 |
def watch(limit):
"""watch scan rates across the cluster"""
period = 5.0
prev = db.db()
prev_totals = None
while True:
click.clear()
time.sleep(period)
cur = db.db()
cur.data['gkrate'] = {}
progress = []
prev_buckets = {b.bucket_id: b for b in prev.bu... | 0.001295 |
def _init():
"""Dynamically import engines that initialize successfully."""
import importlib
import os
import re
filenames = os.listdir(os.path.dirname(__file__))
module_names = set()
for filename in filenames:
match = re.match(r'^(?P<name>[A-Z_a-z]\w*)\.py[co]?$', filename)
... | 0.000906 |
def ask(question, default=True, exact=False):
"""Ask the question in y/n form and return True/False.
If you don't want a default 'yes', set default to None (or to False if you
want a default 'no').
With exact=True, we want to get a literal 'yes' or 'no', at least
when it does not match the default... | 0.00064 |
def rename_agents(self, stmts):
"""Return a list of mapped statements with updated agent names.
Creates a new list of statements without modifying the original list.
The agents in a statement should be renamed if the grounding map has
updated their db_refs. If an agent contains a FamPl... | 0.001575 |
async def get_xy_address(self, xy):
'''Get address of the agent residing in *xy* coordinate, or ``None``
if no such agent is in this multi-environment.
'''
manager_addr = self.get_xy_environment(xy)
if manager_addr is None:
return None
else:
r_agen... | 0.004515 |
def delete_room(room, reason=''):
"""Deletes a MUC room from the XMPP server."""
if room.custom_server:
return
def _delete_room(xmpp):
muc = xmpp.plugin['xep_0045']
muc.destroy(room.jid, reason=reason)
current_plugin.logger.info('Deleting room %s', room.jid)
_execute_xmpp(... | 0.002817 |
def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbose
(msg, start_time) = tt
ellapsed = (default_timer() - start_time)
if (not return_msg) and write_msg and msg is not None:
... | 0.004202 |
def write_new_config(self, updates):
"""
Given a list of updates, write the updates out to the provided
configuartion file.
Args:
updates (list): List of Update objects.
"""
with open(self._new_config, 'w') as config_file:
for update in updates:
... | 0.003509 |
def get_api_publisher(self, social_user):
"""
and other https://vk.com/dev.php?method=wall.post
"""
def _post(**kwargs):
api = self.get_api(social_user)
from pudb import set_trace; set_trace()
# api.group.getInfo('uids'='your_group_id', 'fields'='... | 0.011547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.