text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def obtain_hosting_device_credentials_from_config():
"""Obtains credentials from config file and stores them in memory.
To be called before hosting device templates defined in the config file
are created.
"""
cred_dict = get_specific_config('cisco_hosting_device_credential')
attr_info = {
... | 0.000693 |
def remove_range(self, start, end):
'''Remove a range by score.
'''
return self._sl.remove_range(
start, end, callback=lambda sc, value: self._dict.pop(value)) | 0.010256 |
def _win32_strerror(err):
""" expand a win32 error code into a human readable message """
# FormatMessage will allocate memory and assign it here
buf = ctypes.c_char_p()
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
... | 0.002128 |
def __get_overall_data(self, x):
"""
(recursive) Collect all "sensorGenus" and "sensorSpecies" fields, set data to self
:param any x: Any data type
:return none:
"""
if isinstance(x, dict):
if "sensorGenus" in x:
if x["sensorGenus"] and x["sens... | 0.004525 |
def drawdown_recov(self, return_int=False):
"""Length of drawdown recovery in days.
This is the duration from trough to recovery date.
Parameters
----------
return_int : bool, default False
If True, return the number of days as an int.
If False, return a... | 0.003597 |
def config(self):
"""Get a Configuration object from the file contents."""
conf = config.Configuration()
for namespace in self.namespaces:
if not hasattr(conf, namespace):
if not self._strict:
continue
raise exc.NamespaceNotRegi... | 0.002291 |
def to_csv(data, field_names=None, filename='data.csv',
overwrite=True,
write_headers=True, append=False, flat=True,
primary_fields=None, sort_fields=True):
"""
DEPRECATED Write a list of dicts to a csv file
:param data: List of dicts
:param field_names: The ... | 0.00043 |
async def _init_writer(self):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
"""
async with self._initialization_lock:
if not self.initialized:
self.stream = await aiofiles.open(
f... | 0.004149 |
def GetClosestPoint(x, a, b):
"""
Returns the point on the great circle segment ab closest to x.
"""
assert(x.IsUnitLength())
assert(a.IsUnitLength())
assert(b.IsUnitLength())
a_cross_b = a.RobustCrossProd(b)
# project to the great circle going through a and b
p = x.Minus(
a_cross_b.Times(
... | 0.022617 |
def run_shell_command(commands, **kwargs):
"""Run a shell command."""
p = subprocess.Popen(commands,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs)
output, error = p.communicate()
return p.returncode, output, error | 0.003165 |
def register(self, classes=[]):
"""
Registers new plugins.
The registration only creates a new entry for a plugin inside the _classes dictionary.
It does not activate or even initialise the plugin.
A plugin must be a class, which inherits directly or indirectly from GwBasePatte... | 0.005488 |
def get_species(species_id):
''' Return a single species '''
result = _get(species_id, settings.SPECIES)
return Species(result.content) | 0.006803 |
def open_target_group_for_form(self, form):
"""
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
"""
target = se... | 0.003221 |
def dfs_grid(grid, i, j, mark='X', free='.'):
"""DFS on a grid, mark connected component, iterative version
:param grid: matrix, 4-neighborhood
:param i,j: cell in this matrix, start of DFS exploration
:param free: symbol for walkable cells
:param mark: symbol to overwrite visited vertices
:com... | 0.001277 |
def append(self, content, encoding='utf8'):
"""
add a line to file
"""
if not self.parent.exists:
self.parent.create()
with open(self._filename, "ab") as output_file:
if not is_text(content):
Log.error(u"expecting to write unicode only")
... | 0.004878 |
def delete(self, service, path, **kwargs):
""" Make a delete requests (this returns a coroutine)"""
return self.make_request(Methods.DELETE, service, path, **kwargs) | 0.01105 |
def parse(self, src):
"""Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets."""
self.cssBuilder.beginStylesheet()
try:
# XXX Some simple preprocessing
src = cssSpecial.cleanupCSS(src)
try:
src, styles... | 0.003656 |
def assign_method(stochastic, scale=None, verbose=-1):
"""
Returns a step method instance to handle a
variable. If several methods have the same competence,
it picks one arbitrarily (using set.pop()).
"""
# Retrieve set of best candidates
best_candidates = pick_best_methods(stochastic)
... | 0.002712 |
def enable_capture_state(self, state, writeToHw=False):
"""
Enable/Disable capture on resource group
"""
if state:
activePorts = self.rePortInList.findall(self.activePortList)
self.activeCapturePortList = "{{" + activePorts[0] + "}}"
else:
self... | 0.004831 |
def _make_outputnode(self, frequency):
"""
Generates an output node for the given frequency. It also adds implicit
file format conversion nodes to the pipeline.
Parameters
----------
frequency : str
The frequency (i.e. 'per_session', 'per_visit', 'per_subject... | 0.00091 |
def make_checksum_validation_script(stats_list):
"""Make batch files required for checking checksums from another machine."""
if not os.path.exists('./hash_check'):
os.mkdir('./hash_check')
with open('./hash_check/curl.sh', 'w') as curl_f, open(
'./hash_check/md5.txt', 'w'
) as md5_f, o... | 0.003652 |
def parameters(self) -> List['Parameter']:
"""Return a list of parameter objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Parameter(_lststr, _type_to_spans, span, 'Parameter')
for span in self._subspans('Parameter')] | 0.006579 |
def loadJSON(self, jdata):
"""
Initializes the information for this class from the given JSON data blob.
:param jdata: <dict>
"""
# required params
self.__name = jdata['name']
self.__field = jdata['field']
# optional fields
self.__display = jdata... | 0.005415 |
def _get_unit_factor(cls, unit):
"""
Returns the unit factor depending on the unit constant
:param int unit: the unit of the factor requested
:returns: a function to convert the raw sensor value to the given unit
:rtype: lambda function
:raises Unsu... | 0.005102 |
def remove_translation(self, context_id, translation_id):
"""Removes a translation entry from a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int translation_id: The id-value representing the translation.
:return bool: True if translation ... | 0.004016 |
def inverse_kinematics(self, target, initial_position=None, **kwargs):
"""Computes the inverse kinematic on the specified target
Parameters
----------
target: numpy.array
The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix
initi... | 0.006104 |
def mpub(self, topic, *messages):
'''Publish multiple messages to a topic'''
return self.send(constants.MPUB + ' ' + topic, messages) | 0.013423 |
def build_circles(self, circles):
""" Process data to construct rectangles
This method is built from the assumption that the circles parameter
is a list of:
lists : a list with 3 elements indicating
[center_latitude, center_longitude, radius]
tuples : a t... | 0.001186 |
def read_envvar_file(name, extension):
"""
Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigu... | 0.001712 |
def update_kwargs(kwargs, **keyvalues):
"""Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True
"""
for key, value in keyvalues.items():
if key not in kwargs:
... | 0.002882 |
def fast_ordering(self, structure, num_remove_dict, num_to_return=1):
"""
This method uses the matrix form of ewaldsum to calculate the ewald
sums of the potential structures. This is on the order of 4 orders of
magnitude faster when there are large numbers of permutations to
con... | 0.000921 |
def t_HEXCONSTANT(self, t):
r'0x[0-9A-Fa-f]+'
t.value = int(t.value, 16)
t.type = 'INTCONSTANT'
return t | 0.014706 |
def kill_window(self):
"""Kill the current :class:`Window` object. ``$ tmux kill-window``."""
proc = self.cmd(
'kill-window',
# '-t:%s' % self.id
'-t%s:%s' % (self.get('session_id'), self.index),
)
if proc.stderr:
raise exc.LibTmuxExcepti... | 0.005348 |
def get_time(self):
"""Time of the TIFF file
Currently, only the file modification time is supported.
Note that the modification time of the TIFF file is
dependent on the file system and may have temporal
resolution as low as 3 seconds.
"""
if isinstance(self.pat... | 0.004435 |
def idctii(x, axes=None):
"""
Compute a multi-dimensional inverse DCT-II over specified array axes.
This function is implemented by calling the one-dimensional inverse
DCT-II :func:`scipy.fftpack.idct` with normalization mode 'ortho'
for each of the specified axes.
Parameters
----------
... | 0.001431 |
def operation_list(uploader):
"""List file on target"""
files = uploader.file_list()
for f in files:
log.info("{file:30s} {size}".format(file=f[0], size=f[1])) | 0.005587 |
def deaccent(text):
"""
Remove accentuation from the given string.
"""
norm = unicodedata.normalize("NFD", text)
result = "".join(ch for ch in norm if unicodedata.category(ch) != 'Mn')
return unicodedata.normalize("NFC", result) | 0.003968 |
def add_item_to_sonos_playlist(self, queueable_item, sonos_playlist):
"""Adds a queueable item to a Sonos' playlist.
Args:
queueable_item (DidlObject): the item to add to the Sonos' playlist
sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to
which the... | 0.001536 |
def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache) | 0.004525 |
def convertLatLngToPixelXY(self, lat, lng, level):
'''
returns the x and y values of the pixel corresponding to a latitude
and longitude.
'''
mapSize = self.getMapDimensionsByZoomLevel(level)
lat = self.clipValue(lat, self.min_lat, self.max_lat)
lng = self.clipVa... | 0.002928 |
def get(self, key, fallback=None):
"""
look up global config values from alot's config
:param key: key to look up
:type key: str
:param fallback: fallback returned if key is not present
:type fallback: str
:returns: config value with type as specified in the spec... | 0.003472 |
def _element_append_path(
start_element, # type: ET.Element
element_names # type: Iterable[Text]
):
# type: (...) -> ET.Element
"""
Append the list of element names as a path to the provided start element.
:return: The final element along the path.
"""
end_element = start_elem... | 0.001972 |
def setup_xrates(base, rates):
"""
If using the Python money package, this will set up the xrates exchange
rate data.
:param base:
The string currency code to use as the base
:param rates:
A dict with keys that are string currency codes and values that are
a Decimal of the ... | 0.001965 |
def is_running(self):
"""
Return true if the node is running
"""
self.__update_status()
return self.status == Status.UP or self.status == Status.DECOMMISSIONED | 0.01005 |
def _display_progress(data, stream):
"""
expecting the following data scheme:
{
u'status': u'Pushing',
u'progressDetail': {
u'current': 655337,
u'start': 1413994898,
u'tota... | 0.003287 |
def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF or EWIF file
:param path: Path to WIF of EWIF file
:param password: Password needed for EWIF file
"""
with open(path, 'r') as fh:
... | 0.004202 |
def defBoroCnst(self,BoroCnstArt):
'''
Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self. Uses the artificial and natural borrowing constraints.
Parameters
----------
BoroCnstArt : float or None
Borrowing const... | 0.006989 |
def _parse_response_body_from_xml_node(node, return_type):
'''
parse the xml and fill all the data into a class of return_type
'''
return_obj = return_type()
_MinidomXmlToObject._fill_data_to_return_object(node, return_obj)
return return_obj | 0.006897 |
def onStart(self, event):
"""
Display the environment of a started container
"""
c = event.container
print '+' * 5, 'started:', c
kv = lambda s: s.split('=', 1)
env = {k: v for (k, v) in (kv(s) for s in c.attrs['Config']['Env'])}
print env | 0.009901 |
def invalidate_cache(self, klass, extra=None, **kwargs):
"""
Invalidate a cache for a specific class.
This will loop through all registered groups that have registered
the given model class and call their invalidate_cache method.
All keyword arguments will be directly passed th... | 0.001775 |
def document_type(self, key, value):
"""Populate the ``document_type`` key.
Also populates the ``_collections``, ``citeable``, ``core``, ``deleted``,
``refereed``, ``publication_type``, and ``withdrawn`` keys through side
effects.
"""
schema = load_schema('hep')
publication_type_schema = sc... | 0.001072 |
def __serializedDot(self):
"""
DOT format:
digraph graphname {
a -> b [label=instanceOf];
b -> d [label=isA];
}
"""
temp = ""
for x,y,z in self.rdflib_graph.triples((None, None, None)):
temp += """"%s" -> "%s" [label="%s"];\n""" % (self.namespace_manager.normalizeUri(x), self.namespace_manager... | 0.046083 |
def parse_headers(content_disposition, location=None, relaxed=False):
"""Build a ContentDisposition from header values.
"""
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=location)
... | 0.000379 |
def _preprocess_successor(self, state, add_guard=True): #pylint:disable=unused-argument
"""
Preprocesses the successor state.
:param state: the successor state
"""
# Next, simplify what needs to be simplified
if o.SIMPLIFY_EXIT_STATE in state.options:
state.... | 0.004926 |
def _determine_stream_track(self,nTrackChunks):
"""Determine the track of the stream in real space"""
#Determine how much orbital time is necessary for the progenitor's orbit to cover the stream
if nTrackChunks is None:
#default is floor(self._deltaAngleTrack/0.15)+1
self... | 0.02026 |
def add_sub_directory(self, key, path):
"""Adds a sub-directory to the results directory.
Parameters
----------
key: str
A look-up key for the directory path.
path: str
The relative path from the root of the results directory to the sub-directory.
... | 0.00495 |
def _get_interpretation_function(interpretation, dtype):
"""
Retrieves the interpretation function used.
"""
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
global _interpretations
if not hasattr(_interpretations, name):
raise ValueError("No transform ... | 0.004237 |
def dtpool(name):
"""
Return the data about a kernel pool variable.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html
:param name: Name of the variable whose value is to be returned.
:type name: str
:return:
Number of values returned for name,
Type o... | 0.001464 |
def encode_multipart(data, files):
"""Encode multipart.
:arg dict data: Data to be encoded
:arg dict files: Files to be encoded
:returns: Encoded binary string
:raises: :class:`UrlfetchException`
"""
body = BytesIO()
boundary = choose_boundary()
part_boundary = b('--%s\r\n' % bounda... | 0.000424 |
def _parse_topic_table(self, xml, tds='title,created,comment,group', selector='//table[@class="olt"]//tr'):
"""
解析话题列表
:internal
:param xml: 页面XML
:param tds: 每列的含义,可以是title, created, comment, group, updated, author, time, rec
:param selector: 表在页面中的位置
:... | 0.006329 |
def trigger_all_change_callbacks(self):
"""Trigger all callbacks that were set with on_change()."""
return [
ret
for key in DatastoreLegacy.store[self.domain].keys()
for ret in self.trigger_change_callbacks(key)
] | 0.007326 |
def exit(self):
"""Stop the simple WSGI server running the appliation."""
if self._server is not None:
self._server.shutdown()
self._server.server_close()
self._server = None | 0.00885 |
def set_encryption_passphrases(self, encryption_passphrases):
'''Set encryption passphrases'''
self.encryption_passphrases = self._update_dict(encryption_passphrases,
{}, replace_data=True) | 0.007663 |
def set_published_date(self, published_date=None):
"""Sets the published date.
:param published_date: the new published date
:type published_date: ``osid.calendaring.DateTime``
:raise: ``InvalidArgument`` -- ``published_date`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isRead... | 0.003348 |
def viewTs(ts):
"""
View the contents of one time series entry in a nicely formatted way
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. viewTs(ts[0])
:param dict ts: One time series entry
:return none:
"""
_ts = ts
if isinstance(ts, list):
_ts =... | 0.003792 |
def get_registered(option_hooks=None, event_hooks=None,
command_hooks=None, root_access=None,
task_active=True):
""" Returns a generator of registered plugins matching filters.
`option_hooks`
Boolean to include or exclude plugins using option hooks.
... | 0.003215 |
def ortholog(args):
"""
%prog ortholog species_a species_b
Run a sensitive pipeline to find orthologs between two species a and b.
The pipeline runs LAST and generate .lifted.anchors.
`--full` mode would assume 1-to-1 quota synteny blocks as the backbone of
such predictions. Extra orthologs wi... | 0.001476 |
def openOrders(self) -> List[Order]:
"""
List of all open orders.
"""
return [trade.order for trade in self.wrapper.trades.values()
if trade.orderStatus.status not in OrderStatus.DoneStates] | 0.008403 |
def cudnnSoftmaxForward(handle, algorithm, mode, alpha, srcDesc, srcData, beta, destDesc, destData):
""""
This routing computes the softmax function
Parameters
----------
handle : cudnnHandle
Handle to a previously created cuDNN context.
algorithm : cudnnSoftmaxAlgorithm
Enumera... | 0.004376 |
def wait_for_at_least(self, new_state):
"""
Wait for a state to be entered which is greater than or equal to
`new_state` and return.
"""
if not (self._state < new_state):
return
fut = asyncio.Future(loop=self.loop)
self._least_waiters.append((new_stat... | 0.005698 |
def generate_mavlink(directory, xml):
'''generate MVMavlink header and implementation'''
f = open(os.path.join(directory, "MVMavlink.h"), mode='w')
t.write(f,'''
//
// MVMavlink.h
// MAVLink communications protocol built from ${basename}.xml
//
// Created on ${parse_time} by mavgen_objc.py
// http://qgr... | 0.002048 |
def list_exports(exports='/etc/exports'):
'''
List configured exports
CLI Example:
.. code-block:: bash
salt '*' nfs.list_exports
'''
ret = {}
with salt.utils.files.fopen(exports, 'r') as efl:
for line in salt.utils.stringutils.to_unicode(efl.read()).splitlines():
... | 0.000752 |
def get_config(self, budget):
"""
Function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration
... | 0.029508 |
def _assign_funcs(self, by_name=False, inst_module=None):
"""Assign all external science instrument methods to Instrument object.
"""
import importlib
# set defaults
self._list_rtn = self._pass_func
self._load_rtn = self._pass_func
self._default_rtn = self... | 0.002693 |
def close(*args, **kwargs):
r"""Close last created figure, alias to ``plt.close()``."""
_, plt, _ = _import_plt()
plt.close(*args, **kwargs) | 0.006579 |
def replace(self, **kwargs):
""" Return a :class:`.Date` with one or more components replaced
with new values.
"""
return Date(kwargs.get("year", self.__year),
kwargs.get("month", self.__month),
kwargs.get("day", self.__day)) | 0.006734 |
def calculate_text_coords(rectangle_coords):
"""Calculate Canvas text coordinates based on rectangle coords"""
return (int(rectangle_coords[0] + (rectangle_coords[2] - rectangle_coords[0]) / 2),
int(rectangle_coords[1] + (rectangle_coords[3] - rectangle_coords[1]) / 2)) | 0.013245 |
def gdate(self):
"""Return the Gregorian date for the given Hebrew date object."""
if self._last_updated == "gdate":
return self._gdate
return conv.jdn_to_gdate(self._jdn) | 0.009662 |
def load_umatrix(self, filename):
"""Load the umatrix from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str.
"""
self.umatrix = np.loadtxt(filename, comments='%')
if self.umatrix.shape != (self._n_rows, self._n_columns):
... | 0.00463 |
def d2logpdf_dlink2_dvar(self, link_f, y, Y_metadata=None):
"""
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:param Y_metadata: Y_metadata not used in gaussian
:returns: derivative of log likelihood evaluated at... | 0.014363 |
def getSlicedArray(self, copy=True):
""" Slice the rti using a tuple of slices made from the values of the combo and spin boxes.
:param copy: If True (the default), a copy is made so that inspectors cannot
accidentally modify the underlying of the RTIs. You can set copy=False as a
... | 0.006283 |
def bcftools_stats_genstats_headers(self):
""" Add key statistics to the General Stats table """
stats_headers = OrderedDict()
stats_headers['number_of_records'] = {
'title': 'Vars',
'description': 'Variations total',
'min': 0, 'format': '{:,.0f}',
}
... | 0.001365 |
def col_frequencies(col, weights=None, gap_chars='-.'):
"""Frequencies of each residue type (totaling 1.0) in a single column."""
counts = col_counts(col, weights, gap_chars)
# Reduce to frequencies
scale = 1.0 / sum(counts.values())
return dict((aa, cnt * scale) for aa, cnt in counts.iteritems()) | 0.003145 |
def element_to_unicode(element):
"""Serialize an XML element into a unicode string.
This should work the same on Python2 and Python3 and with all
:etree:`ElementTree` implementations.
:Parameters:
- `element`: the XML element to serialize
:Types:
- `element`: :etree:`ElementTree.El... | 0.004808 |
def add_config(self, config):
"""
:param config:
:type config: dict
"""
self.pre_configure()
self.config = config
if not self.has_revision_file():
#: Create new revision file.
touch_file(self.revfile_path)
self.history.load(self.... | 0.003053 |
def windspeed(self, t):
"""Return the wind speed list at time `t`"""
ws = [0] * self.n
for i in range(self.n):
q = ceil(t / self.dt[i])
q_prev = 0 if q == 0 else q - 1
r = t % self.dt[i]
r = 0 if abs(r) < 1e-6 else r
if r == 0:
... | 0.003413 |
def close(self):
"""
Close the file.
"""
if not self.closed:
self.closed = True
retval = self.f.close()
if self.base_mode != "r":
self.__size = self.fs.get_path_info(self.name)["size"]
return retval | 0.006803 |
def monte_carlo_csiszar_f_divergence(
f,
p_log_prob,
q,
num_draws,
use_reparametrization=None,
seed=None,
name=None):
"""Monte-Carlo approximation of the Csiszar f-Divergence.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar f-Divergenc... | 0.002293 |
def _is_multiframe_diffusion_imaging(dicom_input):
"""
Use this function to detect if a dicom series is a philips multiframe dti dataset
NOTE: We already assue this is a 4D dataset as input
"""
header = dicom_input[0]
if "PerFrameFunctionalGroupsSequence" not in header:
return False
... | 0.003082 |
def pad_position_w(self, i):
"""
Determines the position of the ith pad in the width direction.
Assumes equally spaced pads.
:param i: ith number of pad in width direction (0-indexed)
:return:
"""
if i >= self.n_pads_w:
raise ModelError("pad index out... | 0.007075 |
def create_histogram(df):
""" create a mg line plot
Args:
df (pandas.DataFrame): data to plot
"""
fig = Figure("/mg/histogram/", "mg_histogram")
fig.layout.set_size(width=450, height=200)
fig.layout.set_margin(left=40, right=40)
fig.graphics.animate_on_load()
# Make a h... | 0.00241 |
def record_participation(self, client, dt=None):
"""Record a user's participation in a test along with a given variation"""
if dt is None:
date = datetime.now()
else:
date = dt
experiment_key = self.experiment.name
pipe = self.redis.pipeline()
p... | 0.008785 |
def set_my_info(self, message, contact_info=""):
"""set my contact info to ____: Set your emergency contact info."""
contacts = self.load("contact_info", {})
contacts[message.sender.handle] = {
"info": contact_info,
"name": message.sender.name,
}
self.save... | 0.005115 |
def split_predicate(ex: Extraction) -> Extraction:
"""
Ensure single word predicate
by adding "before-predicate" and "after-predicate"
arguments.
"""
rel_toks = ex.toks[char_to_word_index(ex.rel.span[0], ex.sent) \
: char_to_word_index(ex.rel.span[1], ex.sent) + 1]
if ... | 0.007782 |
def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Substitution structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... | 0.010717 |
def getvar(root, name, vtype='', dimensions=(), digits=0, fill_value=None,
source=None):
"""
Return a variable from a NCFile or NCPackage instance. If the variable
doesn't exists create it.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
name -- the nam... | 0.001266 |
def list_names(cls):
"""Retrieve paas id and names."""
ret = dict([(item['id'], item['name'])
for item in cls.list({'items_per_page': 500})])
return ret | 0.010204 |
def list_remote(local_root):
"""Get remote branch/tag latest SHAs.
:raise GitError: When git ls-remote fails.
:param str local_root: Local path to git root directory.
:return: List of tuples containing strings. Each tuple is sha, name, kind.
:rtype: list
"""
command = ['git', 'ls-remote',... | 0.002577 |
def guess_codec(file, errors="strict", require_char=False):
"""Look at file contents and guess its correct encoding.
File must be open in binary mode and positioned at offset 0. If BOM
record is present then it is assumed to be UTF-8 or UTF-16 encoded
file. GEDCOM header is searched for CHAR record and... | 0.00033 |
def pull(self, repository, tag=None, stream=False, auth_config=None,
decode=False, platform=None):
"""
Pulls an image. Similar to the ``docker pull`` command.
Args:
repository (str): The repository to pull
tag (str): The tag to pull
stream (bool)... | 0.001105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.