text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _load_meta(path):
"""
Load meta data about this package from file pypi.json.
:param path: The path to pypi.json
:return: Dictionary of key value pairs.
"""
with open(path) as f:
meta = load(f, encoding='utf-8')
meta = {k: v.decode('utf-8') if isinstance(v, bytes) else v
... | 0.000745 |
def save(self, model, path=''):
"""Save the file model and return the model with no content."""
if model['type'] != 'notebook':
return super(TextFileContentsManager, self).save(model, path)
nbk = model['content']
try:
metadata = nbk.get('metadata')
re... | 0.003362 |
def GetFormatSpecification(self):
"""Retrieves the format specification.
Returns:
FormatSpecification: format specification or None if the format cannot
be defined by a specification object.
"""
format_specification = specification.FormatSpecification(
self.type_indicator)
... | 0.001795 |
def finish_displayhook(self):
"""Finish up all displayhook activities."""
io.stdout.write(self.shell.separate_out2)
io.stdout.flush() | 0.012739 |
def to_mask(self, method='exact', subpixels=5):
"""
Return a list of `~photutils.ApertureMask` objects, one for each
aperture position.
Parameters
----------
method : {'exact', 'center', 'subpixel'}, optional
The method used to determine the overlap of the ap... | 0.000646 |
def revoke_sudo_privileges(request):
"""
Revoke sudo privileges from a request explicitly
"""
request._sudo = False
if COOKIE_NAME in request.session:
del request.session[COOKIE_NAME] | 0.004739 |
def byte_adaptor(fbuffer):
""" provides py3 compatibility by converting byte based
file stream to string based file stream
Arguments:
fbuffer: file like objects containing bytes
Returns:
string buffer
"""
if six.PY3:
strings = fbuffer.read().decode('latin-1')
fb... | 0.002469 |
def unique_justseen(iterable, key=None):
"""Yields elements in order, ignoring serial duplicates
>>> list(unique_justseen('AAAABBBCCDAABBB'))
['A', 'B', 'C', 'D', 'A', 'B']
>>> list(unique_justseen('ABBCcAD', str.lower))
['A', 'B', 'C', 'A', 'D']
"""
return map(next, map(op... | 0.002732 |
def remove_task(cls, task):
"""
:param Task|callable task: Remove 'task' from the list of tasks to run periodically
"""
with cls._lock:
if not isinstance(task, Task):
task = cls.resolved_task(task)
if task:
cls.tasks.remove(task)
... | 0.008621 |
def computePerturbedFreeEnergies(self, u_ln, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10):
"""Compute the free energies for a new set of states.
Here, we desire the free energy differences among a set of new states, as well as the uncertainty estimates in these differences... | 0.005405 |
def fit(self, ini_betas=None, tol=1.0e-6, max_iter=200, solve='iwls'):
"""
Method that fits a model with a particular estimation routine.
Parameters
----------
ini_betas : array
k*1, initial coefficient values, including constant.
... | 0.003113 |
def list_of_all_href(self,html):
'''
It will return all hyper links found in the mr-jatt page for download
'''
soup=BeautifulSoup(html)
links=[]
a_list=soup.findAll('a','touch')
for x in xrange(len(a_list)-1):
link = a_list[x].get('href')
name = a_list[x]
name = str(name)
name=re.sub(r'<a.*/>... | 0.067511 |
def _set_all_tables(self, schema, **kwargs):
"""
You can run into a problem when you are trying to set a table and it has a
foreign key to a table that doesn't exist, so this method will go through
all fk refs and make sure the tables exist
"""
with self.transaction(**k... | 0.007692 |
def getparser(use_datetime=0):
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
to an unmarshalling object. Return both objects.
"""
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
if Fas... | 0.001087 |
def get_gradebooks(self):
"""Pass through to provider GradebookLookupSession.get_gradebooks"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('gradebook_lookup_session').get_gradebooks()
cat_list ... | 0.008197 |
def index():
""" Display productpage with normal user and test user buttons"""
global productpage
table = json2html.convert(json = json.dumps(productpage),
table_attributes="class=\"table table-condensed table-bordered table-hover\"")
return render_template('index.html', ... | 0.011799 |
def _get_values(self, rdn):
"""
Returns a dict of prepped values contained in an RDN
:param rdn:
A RelativeDistinguishedName object
:return:
A dict object with unicode strings of NameTypeAndValue value field
values that have been prepped for comparis... | 0.006536 |
def get_trending_daily_not_starred(self):
"""Gets trending repositories NOT starred by user
:return: List of daily-trending repositories which are not starred
"""
trending_daily = self.get_trending_daily() # repos trending daily
starred_repos = self.get_starred_repos() # repos ... | 0.00396 |
def _get_bounds(mapper, values):
"""
Extract first and second value from tuples of mapped bins.
"""
array = np.array([mapper.get(x) for x in values])
return array[:, 0], array[:, 1] | 0.009009 |
def _microtime():
'''
Return a Unix timestamp as a string of digits
:return:
'''
val1, val2 = math.modf(time.time())
val2 = int(val2)
return '{0:f}{1}'.format(val1, val2) | 0.005051 |
def uri(ctx, uri, touch, force):
"""
Add a new credential from URI.
Use a URI to add a new credential to your YubiKey.
"""
if not uri:
while True:
uri = click.prompt('Enter an OATH URI', err=True)
try:
uri = CredentialData.from_uri(uri)
... | 0.001475 |
def find_item_by_id(self, object_id):
"""Get item based on its id or uuid
:param object_id:
:type object_id: int | str
:return:
:rtype: alignak.objects.item.Item | None
"""
# Item id may be an item
if isinstance(object_id, Item):
return object... | 0.006061 |
def selected_indexes(self, ):
"""Return the current index
:returns: the current index in a list
:rtype: list of QtCore.QModelIndex
:raises: None
"""
i = self.model().index(self.currentIndex(), 0, self.rootModelIndex())
return [i] | 0.006993 |
def get_section_by_offset(self, offset):
"""Get the section containing the given file offset."""
sections = [s for s in self.sections if s.contains_offset(offset)]
if sections:
return sections[0]
return None | 0.007874 |
def start_slaves(slave_dir,exe_rel_path,pst_rel_path,num_slaves=None,slave_root="..",
port=4004,rel_path=None,local=True,cleanup=True,master_dir=None,
verbose=False,silent_master=False):
""" start a group of pest(++) slaves on the local machine
Parameters
----------
sl... | 0.013376 |
def run(self):
'''
Execute the salt command line
'''
import salt.client
self.parse_args()
if self.config['log_level'] not in ('quiet', ):
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
try:
... | 0.001322 |
def _execute_with_retries(conn, function, **kwargs):
'''
Retry if we're rate limited by AWS or blocked by another call.
Give up and return error message if resource not found or argument is invalid.
conn
The connection established by the calling method via _get_conn()
function
The ... | 0.002654 |
def exit(self, code=0, message=None):
"""
Exit the console program sanely.
"""
## If we have a parser, use it to exit
if self._parser:
if code > 0:
self.parser.error(message)
else:
self.parser.exit(code, message)
#... | 0.006974 |
def spline_base1d(length, nr_knots = 20, spline_order = 5, marginal = None):
"""Computes a 1D spline basis
Input:
length: int
length of each basis
nr_knots: int
Number of knots, i.e. number of basis functions.
spline_order: int
Order of the splin... | 0.016824 |
def quickRPCServer(provider, prefix, target,
maxsize=20,
workers=1,
useenv=True, conf=None, isolate=False):
"""Run an RPC server in the current thread
Calls are handled sequentially, and always in the current thread, if workers=1 (the default).
If wo... | 0.005109 |
def recomb_probability(cM, method="kosambi"):
"""
<http://statgen.ncsu.edu/qtlcart/manual/node46.html>
>>> recomb_probability(1)
0.009998666879965463
>>> recomb_probability(100)
0.48201379003790845
>>> recomb_probability(10000)
0.5
"""
assert method in ("kosambi", "haldane")
... | 0.00202 |
def _get_data(self, p_p_resource_id, start_date=None, end_date=None):
"""Get data."""
data = {
'_' + REQ_PART + '_dateDebut': start_date,
'_' + REQ_PART + '_dateFin': end_date
}
params = {
'p_p_id': REQ_PART,
'p_p_lifecycle': 2,
... | 0.00297 |
def autoscan():
"""autoscan will check all of the serial ports to see if they have
a matching VID:PID for a MicroPython board.
"""
for port in serial.tools.list_ports.comports():
if is_micropython_usb_device(port):
connect_serial(port[0]) | 0.00361 |
def get_pos_name(code, name='parent', english=True, pos_tags=POS_MAP):
"""Gets the part of speech name for *code*.
:param str code: The part of speech code to lookup, e.g. ``'nsf'``.
:param str name: Which part of speech name to include in the output. Must
be one of ``'parent'``, ``'child'``, or ``... | 0.00094 |
def add_func(self, func, *arg, **kwargs):
"""QADATASTRUCT的指标/函数apply入口
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs) | 0.007018 |
def url_quote(string, charset='utf-8', errors='strict', safe='/:'):
"""URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.
"""
if not isinstance(string, (text_type, bytes, ... | 0.001253 |
def _narrow_unichr(code_point):
"""Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds.
This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2);
ordinals above 0xFFFF would require recalcula... | 0.006402 |
def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | 0.003559 |
def Text(name, encoding=None):
"""
Match a route parameter.
`Any` is a synonym for `Text`.
:type name: `bytes`
:param name: Route parameter name.
:type encoding: `bytes`
:param encoding: Default encoding to assume if the ``Content-Type``
header is lacking one.
:return: ``ca... | 0.001802 |
def remove_hook(self, repo_id, name):
"""Remove repository hook."""
ghrepo = self.api.repository_with_id(repo_id)
if ghrepo:
hooks = (h for h in ghrepo.hooks()
if h.config.get('url', '') == self.webhook_url)
hook = next(hooks, None)
if not... | 0.003643 |
def plot_data(self, proj, ax):
"""
Creates and plots a scatter plot of the original data.
"""
x, y = proj
ax.scatter(self.ig.independent_data[x],
self.ig.dependent_data[y], c='b') | 0.008403 |
def derive_child_context(self, whence):
"""Derives a scalar context as a child of the current context."""
return _HandlerContext(
container=self.container,
queue=self.queue,
field_name=None,
annotations=None,
depth=self.depth,
whenc... | 0.00432 |
def describe_version(self):
"""
Query the Cassandra server for the version.
:returns: string -- the version tag
"""
def _vers(client):
return client.describe_version()
d = self._connection()
d.addCallback(_vers)
return d | 0.006711 |
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# Get original mean and standard deviations
mean, stddevs = sup... | 0.003968 |
def _read_page(file_obj, page_header, column_metadata):
"""Read the data page from the given file-object and convert it to raw, uncompressed bytes (if necessary)."""
bytes_from_file = file_obj.read(page_header.compressed_page_size)
codec = column_metadata.codec
if codec is not None and codec != parquet_... | 0.002146 |
def serviceResponse(self, response):
'''
Checks the response received from the I{ViewServer}.
@return: C{True} if the response received matches L{PARCEL_TRUE}, C{False} otherwise
'''
PARCEL_TRUE = "Result: Parcel(00000000 00000001 '........')\r\n"
''' The TRUE respons... | 0.008081 |
def dict_to_hdf5(dic, endpoint):
"""Dump a dict to an HDF5 file.
"""
filename = gen_filename(endpoint)
with h5py.File(filename, 'w') as handler:
walk_dict_to_hdf5(dic, handler)
print('dumped to', filename) | 0.004292 |
def create_background(bg_type, fafile, outfile, genome="hg18", width=200, nr_times=10, custom_background=None):
"""Create background of a specific type.
Parameters
----------
bg_type : str
Name of background type.
fafile : str
Name of input FASTA file.
outfile : str
Na... | 0.004292 |
def _callback(self, wType, uFmt, hConv, hsz1, hsz2, hDdeData, dwData1, dwData2):
"""DdeCallback callback function for processing Dynamic Data Exchange (DDE)
transactions sent by DDEML in response to DDE events
Parameters
----------
wType : transaction type (UINT)
uFmt... | 0.004667 |
def _ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow as tf
except ImportError:
# Print... | 0.009908 |
def on_receive(self, broker):
"""
Drain the pipe and fire callbacks. Since :attr:`_deferred` is
synchronized, :meth:`defer` and :meth:`on_receive` can conspire to
ensure only one byte needs to be pending regardless of queue length.
"""
_vv and IOLOG.debug('%r.on_receive()... | 0.002463 |
def colorize(self, colormap, band_name=None, vmin=None, vmax=None):
"""Apply a colormap on a selected band.
colormap list: https://matplotlib.org/examples/color/colormaps_reference.html
Parameters
----------
colormap : str
Colormap name from this list https://matplotlib... | 0.003882 |
async def from_client(cls, client, *, shard_id=None, session=None, sequence=None, resume=False):
"""Creates a main websocket for Discord from a :class:`Client`.
This is for internal use only.
"""
gateway = await client.http.get_gateway()
ws = await websockets.connect(gateway, lo... | 0.003439 |
def add_vrf(self, auth, attr):
""" Add a new VRF.
* `auth` [BaseAuth]
AAA options.
* `attr` [vrf_attr]
The news VRF's attributes.
Add a VRF based on the values stored in the `attr` dict.
Returns a dict describing the VRF which wa... | 0.004318 |
def _facet_counts(items):
"""Returns facet counts as dict.
Given the `items()` on the raw dictionary from Elasticsearch this processes
it and returns the counts keyed on the facet name provided in the original
query.
"""
facets = {}
for name, data in items:
facets[name] = FacetResu... | 0.002841 |
def check_docstring(cls):
"""
Asserts that the class has a docstring, returning it if successful.
"""
docstring = inspect.getdoc(cls)
if not docstring:
breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1])
msg = "docstring required ... | 0.004405 |
def parse_file_entities(filename, entities=None, config=None,
include_unmatched=False):
""" Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity values
entities (list): An optional list of Entity instances to use in
... | 0.000604 |
def _sort_labels(label_data):
"""Returns the labels in `label_data` sorted in descending order
according to the 'size' (total token count) of their referent
corpora.
:param label_data: labels (with their token counts) to sort
:type: `dict`
:rtype: `list`
"""
... | 0.004695 |
def format_rpc(data):
"""Format an RPC call and response.
Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.
Returns:
str: The formated RPC string.
"""
address, rpc_id, args, resp, _status = data
name = r... | 0.004202 |
def _get_hanging_wall_coeffs_rx(self, C, rup, r_x):
"""
Returns the hanging wall r-x caling term defined in equation 7 to 12
"""
# Define coefficients R1 and R2
r_1 = rup.width * cos(radians(rup.dip))
r_2 = 62.0 * rup.mag - 350.0
fhngrx = np.zeros(len(r_x))
... | 0.00313 |
def get(self, key, default_val=None, require_value=False):
""" Returns a dictionary value
"""
val = dict.get(self, key, default_val)
if val is None and require_value:
raise KeyError('key "%s" not found' % key)
if isinstance(val, dict):
return AttributeDict... | 0.005814 |
def set_element_attributes(elem_to_parse, **attrib_kwargs):
"""
Adds the specified key/value pairs to the element's attributes, and
returns the updated set of attributes.
If the element already contains any of the attributes specified in
attrib_kwargs, they are updated accordingly.
"""
ele... | 0.001996 |
def _get_coarse_dataset(self, key, info):
"""Get the coarse dataset refered to by `key` from the XML data."""
angles = self.root.find('.//Tile_Angles')
if key in ['solar_zenith_angle', 'solar_azimuth_angle']:
elts = angles.findall(info['xml_tag'] + '/Values_List/VALUES')
... | 0.004233 |
def delete(self):
"""
Deletes record, and removes it from database.
"""
# workflow
# --------
# (methods belonging to create/update/delete framework:
# epm._dev_populate_from_json_data, table.batch_add, record.update, queryset.delete, record.delete)
# ... | 0.003654 |
def _render_list(data):
""" Helper to render a list of objects as an HTML list object. """
return IPython.core.display.HTML(google.datalab.utils.commands.HtmlBuilder.render_list(data)) | 0.021277 |
def query_ball_point(self, x, r, p=2., eps=0):
"""
Find all points within distance r of point(s) x.
Parameters
----------
x : array_like, shape tuple + (self.m,)
The point or points to search for neighbors of.
r : positive float
The radius of poin... | 0.001649 |
def trun_setup(conf):
"""
Setup the testrunner data-structure, embedding the parsed environment
variables and command-line arguments and continues with setup for testplans,
testsuites, and testcases
"""
declr = None
try:
with open(conf["TESTPLAN_FPATH"]) as declr_fd:
dec... | 0.001456 |
def _surfdens(self,R,z,phi=0.,t=0.):
"""
NAME:
_surfdens
PURPOSE:
evaluate the surface density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | 0.018341 |
def step_I_create_logrecord_with_table(context):
"""
Create an log record by using a table to provide the parts.
.. seealso: :func:`step_I_create_logrecords_with_table()`
"""
assert context.table, "REQUIRE: context.table"
assert len(context.table.rows) == 1, "REQUIRE: table.row.size == 1"
s... | 0.002755 |
def view_portfolio_loss(token, dstore):
"""
The mean and stddev loss for the full portfolio for each loss type,
extracted from the event loss table, averaged over the realizations
"""
data = portfolio_loss(dstore) # shape (R, L)
loss_types = list(dstore['oqparam'].loss_dt().names)
header = ... | 0.001957 |
def getlist(self, section, option):
"""Read a list of strings.
The value of `section` and `option` is treated as a comma- and newline-
separated list of strings. Each value is stripped of whitespace.
Returns the list of strings.
"""
value_list = self.get(section, opti... | 0.003521 |
def build(site, tagdata):
""" Returns the tag cloud for a list of tags.
"""
tagdata.sort()
# we get the most popular tag to calculate the tags' weigth
tagmax = 0
for tagname, tagcount in tagdata:
if tagcount > tagmax:
tagmax = tagcount
steps = getsteps(site.tagcloud_levels, tagmax)
tags = []
for tagnam... | 0.041176 |
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
configuration = self._configuration.to_api_repr()
resource = {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
configuration["query"]["query"] = self.... | 0.005714 |
def uniqify(func):
"""Make sure that a method returns a unique name."""
@six.wraps(func)
def unique(self, *args, **kwargs):
return self.unique(func(self, *args, **kwargs))
return unique | 0.025381 |
def instantiate(config):
"""
instantiate all registered vodka applications
Args:
config (dict or MungeConfig): configuration object
"""
for handle, cfg in list(config["apps"].items()):
if not cfg.get("enabled", True):
continue
app = get_application(handle)
... | 0.002809 |
def queries2alignments(cfg):
"""
All the processes in alignannoted detection are here.
:param cfg: Configuration settings provided in .yml file
"""
from rohan.dandage.align import get_genomes
get_genomes(cfg)
cfg['datad']=cfg['prjd']
cfg['plotd']=cfg['datad']
dalignannotedp... | 0.025444 |
def filter_tag(arg):
""" Parses a --filter-tag argument """
try:
strip_len = len('Key=')
key, value = arg[strip_len:].split(',Value=', 1)
return key, value
except:
msg = 'Invalid --filter-tag argument: {}'
raise argparse.ArgumentTypeError(msg.format(arg)) | 0.006515 |
def _get_options_for_model(self, model, opts_class=None, **options):
"""
Returns an instance of translation options with translated fields
defined for the ``model`` and inherited from superclasses.
"""
if model not in self._registry:
# Create a new type for backwards ... | 0.001765 |
def drop_duplicates(self, subset=None, keep='first', inplace=False):
"""
Return DataFrame with duplicate rows removed, optionally only
considering certain columns. Indexes, including time indexes
are ignored.
Parameters
----------
subset : column label or sequenc... | 0.00158 |
def _http_headers(self):
"""Return dictionary of http headers necessary for making an http
connection to the endpoint of this Connection.
:return: Dictionary of headers
"""
if not self.usertag:
return {}
creds = u'{}:{}'.format(
self.usertag,
... | 0.004016 |
def append_to_arg_count(self, data):
"""
Add digit to the input argument.
:param data: the typed digit as string
"""
assert data in '-0123456789'
current = self._arg
if data == '-':
assert current is None or current == '-'
result = data
... | 0.004193 |
def p_expression(self, p):
"""expression : jsonpath
| jsonpath FILTER_OP ID
| jsonpath FILTER_OP FLOAT
| jsonpath FILTER_OP NUMBER
| jsonpath FILTER_OP BOOL
"""
if len(p) == 2:
left, op, right = p... | 0.004587 |
def _quilc_compile(self, quil_program, isa, specs):
"""
Sends a quilc job to Forest.
Users should use :py:func:`LocalCompiler.quil_to_native_quil` instead of calling this
directly.
"""
payload = quilc_compile_payload(quil_program, isa, specs)
response = post_json... | 0.006726 |
def import_or_die(module_name, entrypoint_names):
'''
Import user code; return reference to usercode function.
(str) -> function reference
'''
log_debug("Importing {}".format(module_name))
module_name = os.path.abspath(module_name)
if module_name.endswith('.py'):
module_name,ext = o... | 0.003772 |
def set_updated(self):
"""
Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status.
"""
# get latest output
output = []
for method in self.methods.values():
data = method["last_output"]... | 0.001488 |
def isFits(input):
"""
Returns
--------
isFits: tuple
An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and
``fitstype`` are specified as:
- ``isfits``: True|False
- ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None
Notes
-----
... | 0.002892 |
def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord:
"""Handle error while trying to do something."""
self.lerror(f"Got an error! {e}")
# Handle errors if we know how.
try:
code = e[0]["code"]
if code in self.handled_errors:
... | 0.006383 |
def split_every(n, iterable):
"""Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377."""
items = iter(iterable)
return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in iter... | 0.008955 |
def parse(self, text, fn=None):
"""
Parse the Mapfile
"""
if PY2 and not isinstance(text, unicode):
# specify Unicode for Python 2.7
text = unicode(text, 'utf-8')
if self.expand_includes:
text = self.load_includes(text, fn=fn)
try:
... | 0.002442 |
def set_common_attributes(span):
"""Set the common attributes."""
common = {
attributes_helper.COMMON_ATTRIBUTES.get('AGENT'): AGENT,
}
common_attrs = Attributes(common)\
.format_attributes_json()\
.get('attributeMap')
_update_attr_map(span, common_attrs) | 0.003333 |
def chdir(method):
"""Decorator executing method in directory 'dir'.
"""
def wrapper(self, dir, *args, **kw):
dirstack = ChdirStack()
dirstack.push(dir)
try:
return method(self, dir, *args, **kw)
finally:
dirstack.pop()
return functools.wraps(meth... | 0.003012 |
def add_parameters(self, **params):
"""
Add URL parameters
Also ensure that only valid format/content combinations are requested
"""
self.url_params = None
# we want JSON by default
if not params.get("format"):
params["format"] = "json"
# non-s... | 0.001992 |
def make_count_grid(data):
"""
Takes a 2 or 3d grid of strings representing binary numbers.
Returns a grid of the same dimensions in which each binary number has been
replaced by an integer indicating the number of ones that were in that
number.
"""
data = deepcopy(data)
for i in range... | 0.004283 |
def diff_with_models(self):
"""
Return a dict stating the differences between current state of models
and the configuration itself.
TODO: Detect fields that are in conf, but not in models
"""
missing_from_conf = defaultdict(set)
for model in get_models():
... | 0.00271 |
def delete(self):
""" Deletes this instance """
self.__dmlquery__(self.__class__, self,
batch=self._batch,
timestamp=self._timestamp,
consistency=self.__consistency__,
timeout=self._timeout).delete() | 0.00627 |
def prt_data(self, name, vals, prt=sys.stdout):
"""Print stats data in markdown style."""
fld2val = self.get_fld2val(name, vals)
prt.write(self.fmt.format(**fld2val))
return fld2val | 0.00939 |
def chown(self, path, uid, gid):
"""
Change the owner (``uid``) and group (``gid``) of a file. As with
Python's `os.chown` function, you must pass both arguments, so if you
only want to change one, use `stat` first to retrieve the current
owner and group.
:param str pat... | 0.002869 |
async def _get_full_user(self) -> Dict:
"""
Sometimes Telegram does not provide all the user info with the message.
In order to get the full profile (aka the language code) you need to
call this method which will make sure that the full User object is
loaded.
The result ... | 0.00206 |
def _metadata_unit(unit):
"""Given the name of a unit (e.g. apache2/0), get the unit charm's
metadata.yaml. Very similar to metadata() but allows us to inspect
other units. Unit needs to be co-located, such as a subordinate or
principal/primary.
:returns: metadata.yaml as a python object.
"""
... | 0.001582 |
def save(self, commit=True):
""" Save model to database """
db.session.add(self)
if commit:
db.session.commit()
return self | 0.011905 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.