code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with open(inventory_path, "w") as f:
f.write(_generate_inventory(roles))
if check_networks:
discover_networks(
roles,
networks,
fake_interfaces=fake_interfaces,
fake_networks=fake_networks
)
with open(inventory_path, "w") as ... | def generate_inventory(roles, networks, inventory_path, check_networks=False,
fake_interfaces=None, fake_networks=None) | Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function will try to discover which networks
interfaces are available and map them to one network of the ``networks``
parameters. Note that this auto-d... | 2.196727 | 2.375843 | 0.92461 |
logger.debug('Checking the constraints')
if not output_dir:
output_dir = os.path.join(os.getcwd(), TMP_DIRNAME)
if not extra_vars:
extra_vars = {}
output_dir = os.path.abspath(output_dir)
_check_tmpdir(output_dir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
... | def validate_network(roles=None,
inventory_path=None,
output_dir=None,
extra_vars=None) | Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Reports are available in the tmp directory used
by enos.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra... | 4.150815 | 3.977327 | 1.043619 |
logger.debug('Reset the constraints')
if not extra_vars:
extra_vars = {}
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'tc_reset',
'tc_output_dir': tmpdir}
... | def reset_network(roles, extra_vars=None) | Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (str): path to the inventory | 5.969086 | 6.361617 | 0.938297 |
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'ping'}
for i in range(0, retries):
try:
run_ansible([utils_playbook],
roles=roles,
extra_vars=options,
on_error_continue=False)... | def wait_ssh(roles, retries=100, interval=30) | Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
interval (int): Interval to wait in seconds between t... | 4.959722 | 5.35672 | 0.925888 |
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P<end>\d+)\]")
m = p.match(grp)
if m is not None:
s = int(m.group('start'))
e = int(m.group('end'))
n = m.group('name')
return list(map(lambda x: n + str(x), range(s, e + 1)))
else:
return [grp] | def expand_groups(grp) | Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1] | 2.175782 | 2.527505 | 0.860842 |
srcs = expand_groups(desc['src'])
dsts = expand_groups(desc['dst'])
descs = []
for src in srcs:
for dst in dsts:
local_desc = desc.copy()
local_desc['src'] = src
local_desc['dst'] = dst
descs.append(local_desc)
return descs | def _expand_description(desc) | Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions | 2.317345 | 2.301163 | 1.007032 |
default_delay = network_constraints.get('default_delay')
default_rate = network_constraints.get('default_rate')
default_loss = network_constraints.get('default_loss', 0)
except_groups = network_constraints.get('except', [])
grps = network_constraints.get('groups', roles.keys())
# expand eac... | def _generate_default_grp_constraints(roles, network_constraints) | Generate default symetric grp constraints. | 3.074555 | 3.109373 | 0.988802 |
if 'constraints' not in network_constraints:
return []
constraints = network_constraints['constraints']
actual = []
for desc in constraints:
descs = _expand_description(desc)
for desc in descs:
actual.append(desc)
if 'symetric' in desc:
... | def _generate_actual_grp_constraints(network_constraints) | Generate the user specified constraints | 2.974578 | 2.94133 | 1.011304 |
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
break
i = i + 1 | def _merge_constraints(constraints, overrides) | Merge the constraints avoiding duplicates
Change constraints in place. | 3.145711 | 2.963353 | 1.061538 |
# generate defaults constraints
constraints = _generate_default_grp_constraints(roles,
network_constraints)
# Updating the constraints if necessary
if 'constraints' in network_constraints:
actual = _generate_actual_grp_constraints(network_... | def _build_grp_constraints(roles, network_constraints) | Generate constraints at the group level,
It expands the group names and deal with symetric constraints. | 6.105862 | 5.916802 | 1.031953 |
local_ips = copy.deepcopy(ips)
for constraint in constraints:
gsrc = constraint['src']
gdst = constraint['dst']
gdelay = constraint['delay']
grate = constraint['rate']
gloss = constraint['loss']
for s in roles[gsrc]:
# one possible source
... | def _build_ip_constraints(roles, ips, constraints) | Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules. | 4.177855 | 3.986875 | 1.047902 |
networks = copy.deepcopy(provider_nets)
for network in networks:
for device in devices:
network.setdefault('device', None)
ip_set = IPSet([network['cidr']])
if 'ipv4' not in device:
continue
ips = device['ipv4']
if not isin... | def _map_device_on_host_networks(provider_nets, devices) | Decorate each networks with the corresponding nic name. | 3.020397 | 2.953705 | 1.022579 |
tz = pytz.timezone(tz)
freq = getattr(rrule, freq.upper()) # get frequency enumeration from rrule
return [tz.localize(dt) for dt in rrule.rrule(freq, *args, **kwargs)] | def f_daterange(freq, tz='UTC', *args, **kwargs) | Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: https://dateutil.readthedocs.org/en/latest/rrule.html
:pa... | 3.707333 | 3.90667 | 0.948975 |
dt = np.diff(times) # calculate timesteps
# convert timedeltas to quantities
dt = dt.astype('timedelta64[s]').astype('float') / sc_const.hour
# energy accumulate during timestep
energy = dt * (ac_power[:-1] + ac_power[1:]) / 2
return energy, times[1:] | def f_energy(ac_power, times) | Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times | 6.507592 | 6.075636 | 1.071096 |
timeseries = zip(times, items) # timeseries map of items
# create a key lambda to group timeseries by
if freq.upper() == 'DAILY':
def key(ts_): return ts_[0].day
elif freq.upper() == 'WEEKLY':
weekday = getattr(rrule, wkst.upper()) # weekday start
# generator that searches... | def groupby_freq(items, times, freq, wkst='SU') | Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:param items: items in timeseries
:param times: times corr... | 4.932688 | 4.791562 | 1.029453 |
rollup = [np.sum(item for __, item in ts)
for _, ts in groupby_freq(items, times, freq)]
return np.array(rollup) | def f_rollup(items, times, freq) | Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str | 5.960652 | 8.010196 | 0.744133 |
self.name = data["name"]
add = self.__additional
add["filetype"] = "other"
for filetype in ("book", "image", "video", "audio", "archive"):
if filetype in data:
add["filetype"] = filetype
break
if add["filetype"] in ("image", "... | def fileupdate(self, data) | Method to update extra metadata fields with dict obtained
through `fileinfo` | 4.099101 | 3.935061 | 1.041687 |
if self.filetype not in ("video", "image", "audio"):
raise RuntimeError("Only video, audio and image files can have thumbnails")
thumb_srv = self.thumb.get("server")
url = f"https://{thumb_srv}" if thumb_srv else None
return f"{url}/asset/{self.fid}/thumb" if url el... | def thumbnail(self) | Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail | 6.32765 | 5.216304 | 1.213052 |
if self.filetype not in ("video", "audio"):
raise RuntimeError("Only videos and audio have durations")
return self.info.get("length") or self.info.get("duration") | def duration(self) | Returns the duration in seconds of this audio or video file | 7.046391 | 5.199407 | 1.35523 |
self.room.check_owner()
self.conn.make_call("deleteFiles", [self.fid]) | def delete(self) | Remove this file | 25.572262 | 23.718672 | 1.078149 |
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | def timeout(self, duration=3600) | Timeout the uploader of this file | 27.578194 | 19.267883 | 1.431304 |
if self.group:
gid = getgrnam(self.group).gr_gid
try:
os.setgid(gid)
except Exception:
message = ("Unable to switch ownership to {0}:{1}. " +
"Did you start the daemon as root?")
print(message... | def set_gid(self) | Change the group of the running process | 3.526668 | 3.643497 | 0.967935 |
if self.user:
uid = getpwnam(self.user).pw_uid
try:
os.setuid(uid)
except Exception:
message = ('Unable to switch ownership to {0}:{1}. ' +
'Did you start the daemon as root?')
print(message.f... | def set_uid(self) | Change the user of the running process | 3.743008 | 3.448348 | 1.08545 |
self.logger = logging.getLogger()
if os.path.exists('/dev/log'):
handler = SysLogHandler('/dev/log')
else:
handler = SysLogHandler()
self.logger.addHandler(handler) | def setup_logging(self) | Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else. | 3.101631 | 2.687317 | 1.154174 |
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as e:
sys.stderr.write('fork #1 failed: %d (%s)\n' %
(e.errno, e.strerror))
sys.exit(1)
os.chdir('/')
os.setsid()
os.u... | def daemonize(self) | Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 | 2.754116 | 2.791212 | 0.98671 |
if self._already_running():
message = 'pid file %s already exists. Daemon already running?\n'
sys.stderr.write(message % self.pid_file)
return 0
self.set_gid()
self.set_uid()
# Create log files (if configured) with the new user/group. Creating... | def start(self) | Start the daemon | 5.608416 | 5.09176 | 1.101469 |
if self._already_running():
return self.reliable_kill()
else:
# FIXME: misleading error message
message = 'Daemon not running, nothing to do.\n'
sys.stderr.write(message)
return 0 | def stop(self) | Stop the daemon | 9.573799 | 8.323638 | 1.150194 |
my_name = os.path.basename(sys.argv[0])
if self._already_running():
message = "{0} (pid {1}) is running...\n".format(my_name, self.pid)
sys.stdout.write(message)
return 0
sys.stdout.write("{0} is stopped\n".format(my_name))
return 3 | def status(self) | Determine the status of the daemon | 3.814695 | 3.471509 | 1.098858 |
if settings.STATIC_URL and uri.startswith(settings.STATIC_URL):
path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
elif settings.MEDIA_URL and uri.startswith(settings.MEDIA_URL):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
e... | def fetch_resources(uri, rel) | Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException` | 2.16579 | 2.072129 | 1.045201 |
src = BytesIO(content.encode(encoding))
dest = BytesIO()
pdf = pisa.pisaDocument(src, dest, encoding=encoding,
link_callback=link_callback, **kwargs)
if pdf.err:
logger.error("Error rendering PDF document")
for entry in pdf.log:
if entry[0] =... | def html_to_pdf(content, encoding="utf-8",
link_callback=fetch_resources, **kwargs) | Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError` | 2.81144 | 2.956652 | 0.950886 |
response = HttpResponse(content, content_type=content_type)
if filename is not None:
response["Content-Disposition"] = "attachment; %s" % encode_filename(filename)
return response | def make_response(content, filename=None, content_type="application/pdf") | Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: response content
:param str filename: optional filename for file download
:param str ... | 2.515449 | 3.262098 | 0.771114 |
content = loader.render_to_string(template, context, request=request, using=using)
return html_to_pdf(content, encoding, **kwargs) | def render_to_pdf(template, context, using=None, request=None, encoding="utf-8", **kwargs) | Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:returns: rendered PDF
:rtype:... | 2.529629 | 4.699731 | 0.53825 |
try:
pdf = render_to_pdf(template, context, using=using, encoding=encoding, **kwargs)
return make_response(pdf, filename)
except PDFRenderingError as e:
logger.exception(e.message)
return HttpResponse(e.message) | def render_to_pdf_response(request, template, context, using=None, filename=None,
encoding="utf-8", **kwargs) | Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header will be set to ``attachment`` making the browser display
a "Save as.." dialog.
:param request: Django HTTP request
:type request: :class... | 2.911653 | 3.303286 | 0.881441 |
return render_to_pdf_response(
request=self.request,
template=self.get_template_names(),
context=context,
using=self.template_engine,
filename=self.get_pdf_filename(),
**self.get_pdf_kwargs()
) | def get_pdf_response(self, context, **response_kwargs) | Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse` | 2.433045 | 2.77174 | 0.877804 |
for key, value in dictionary.items():
if isinstance(value, str):
dictionary[key] = re.compile(value)
elif isinstance(value, dict):
compile_patterns_in_dictionary(value)
return dictionary | def compile_patterns_in_dictionary(dictionary) | Replace all strings in dictionary with compiled
version of themselves and return dictionary. | 1.725502 | 1.753269 | 0.984163 |
super().validate_options(k, v)
if k == 'delimiters':
for d in v:
if not isinstance(d, (dict, OrderedDict)):
raise ValueError("{}: 'delimters' entries must be of dict type.".format(self.__class__.__name__))
for key, value in d.item... | def validate_options(self, k, v) | Validate options. | 3.18365 | 3.125159 | 1.018716 |
self.context_visible_first = self.config['context_visible_first']
self.delimiters = []
self.escapes = None
self.line_endings = self.config['normalize_line_endings']
escapes = []
for delimiter in self.config['delimiters']:
if not isinstance(delimiter,... | def setup(self) | Setup. | 3.814983 | 3.753335 | 1.016425 |
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, 'context')] | def filter(self, source_file, encoding): # noqa A001
with codecs.open(source_file, 'r', encoding=encoding) as f | Parse file. | 18.351826 | 16.807596 | 1.091877 |
return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'context')] | def sfilter(self, source) | Filter. | 24.825714 | 23.154797 | 1.072163 |
if self.line_endings:
text = self.norm_nl(text)
new_text = []
index = 0
last = 0
end = len(text)
while index < end:
m = self.escapes.match(text, pos=index) if self.escapes else None
if m:
index = m.end(0)
... | def _filter(self, text) | Context delimiter filter. | 2.657435 | 2.5621 | 1.03721 |
self._state = _State.CLOSED
try:
self._protocol.connection_lost(exc)
finally:
self._rawsock.close()
if self._tls_conn is not None:
self._tls_conn.set_app_data(None)
self._tls_conn = None
self._rawsock = Non... | def _call_connection_lost_and_clean_up(self, exc) | Clean up all resources and call the protocols connection lost method. | 3.067478 | 2.748474 | 1.116066 |
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | def abort(self) | Immediately close the stream, without sending remaining buffers or
performing a proper shutdown. | 12.277668 | 10.392499 | 1.181397 |
if self._state == _State.CLOSED:
self._invalid_state("close() called")
return
if self._state == _State.TLS_HANDSHAKING:
# hard-close
self._force_close(None)
elif self._state == _State.TLS_SHUTTING_DOWN:
# shut down in progres... | def close(self) | Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitted. | 6.224706 | 5.604629 | 1.110637 |
if self._state != _State.RAW_OPEN or self._closing:
raise self._invalid_state("starttls() called")
if ssl_context is not None:
self._ssl_context = ssl_context
self._extra.update(
sslcontext=ssl_context
)
else:
... | def starttls(self, ssl_context=None,
post_handshake_callback=None) | Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructor. If `post_handshake_callback` is set, it overrides the
`post_handshake_callback` passed to the ... | 2.925808 | 2.90478 | 1.007239 |
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError('data argument must be byte-ish (%r)',
type(data))
if not self._state.is_writable or self._closing:
raise self._invalid_state("write() called")
if not data:
... | def write(self, data) | Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered. | 4.117228 | 3.906358 | 1.053981 |
def _app(i, e=None):
if i is not None:
return {k: v for (k, v) in iter_fields(i)}, None
return i, e
def iter_fields(event_field: Union[dict, list]):
if type(event_field) is dict:
for key, val in event_field.items():
yield (key, val)
e... | def explode(prefix: str) | given an array of objects de-normalized into fields | 3.816294 | 3.624297 | 1.052975 |
encode = None
m = RE_XML_START.match(content)
if m:
if m.group(1):
m2 = RE_XML_ENCODE.match(m.group(1))
if m2:
enc = m2.group(2).decode('ascii')
try:
codecs.getencoder(enc)
... | def _has_xml_encode(self, content) | Check XML encoding. | 2.155557 | 2.052232 | 1.050348 |
name = el.name
return name in self.break_tags or name in self.user_break_tags | def is_break_tag(self, el) | Check if tag is an element we should break on. | 6.960432 | 5.538605 | 1.256712 |
if force_root or el.parent is None or self.is_break_tag(el):
content = ''.join(text)
if content:
blocks.append((content, self.construct_selector(el)))
text = []
return text | def store_blocks(self, el, blocks, text, force_root) | Store the text as desired. | 5.482789 | 5.487695 | 0.999106 |
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancestor.name
prefix = ancestor.prefix
sel = ''
... | def construct_selector(self, el, attr='') | Construct an selector for context. | 3.723666 | 3.519296 | 1.058071 |
self.extract_tag_metadata(tree)
text = []
attributes = []
comments = []
blocks = []
if not (self.ignores.match(tree) if self.ignores else None):
# The root of the document is the BeautifulSoup object
capture = self.captures.match(tree) ... | def to_text(self, tree, force_root=False) | Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either. | 3.595865 | 3.582929 | 1.00361 |
content = []
blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser))
if self.comments:
for c, desc in comments:
content.append(filters.SourceText(c, context + ': ' + desc, encoding, self.type + 'comment'))
if self.attributes... | def _filter(self, text, context, encoding) | Filter the source text. | 3.527483 | 3.406781 | 1.03543 |
return self._filter(source.text, source.context, source.encoding) | def sfilter(self, source) | Filter. | 18.42226 | 15.802963 | 1.165747 |
try:
f = sys._getframe(1)
except Exception: # pragma: no cover
namespace = None
else:
namespace = f.f_locals
return _LazyImport(func.__name__, func, namespace) | def lazy_import(func) | Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports like this:
@lazy_imp... | 3.664571 | 4.865957 | 0.753104 |
def _csv_to_list(csv_input):
io_file = io.StringIO(csv_input)
return next(csv.reader(io_file, delimiter=delimiter))
def _app(current_tuple, e=None):
if current_tuple is None or len(current_tuple) == 0:
return None, "no input"
csv_list = _csv_to_list(cu... | def csv_to_map(fields, delimiter=',') | Convert csv to dict
:param delimiter:
:param fields:
:return: | 3.92826 | 4.00927 | 0.979794 |
def _list_to_csv(l):
io_file = io.StringIO()
writer = csv.writer(io_file, quoting=csv.QUOTE_NONNUMERIC, lineterminator='', delimiter=delimiter)
writer.writerow(l)
return io_file.getvalue()
def _app(current_tuple, e=None):
if e is not None:
retu... | def map_to_csv(fields, delimiter=",") | Convert dict to csv
:param fields:
:return: | 3.729002 | 3.731243 | 0.9994 |
@wraps(func)
def wrapper(*args, **kwargs):
if any(isinstance(arg, xr.DataArray) for arg in args):
newargs = []
for arg in args:
if isinstance(arg, xr.DataArray):
newargs.append(arg.values)
else:
newargs.... | def xarrayfunc(func) | Make a function compatible with xarray.DataArray.
This function is intended to be used as a decorator like::
>>> @dc.xarrayfunc
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array)
Args:
func (function): Funct... | 1.934535 | 2.301339 | 0.840613 |
def _chunk(func):
depth = [s.function for s in stack()].index('<module>')
f_globals = getframe(depth).f_globals
# original (unwrapped) function
orgname = '_original_' + func.__name__
orgfunc = dc.utils.copy_function(func, orgname)
f_globals[orgname] = orgfunc
... | def chunk(*argnames, concatfunc=None) | Make a function compatible with multicore chunk processing.
This function is intended to be used as a decorator like::
>>> @dc.chunk('array')
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array, timechunk=10)
or you c... | 2.603451 | 2.585086 | 1.007104 |
return {k: v.values for k, v in self.coords.items() if v.dims==()} | def scalarcoords(self) | A dictionary of values that don't label any axes (point-like). | 7.786419 | 5.891339 | 1.321672 |
extensions = []
extension_configs = {}
for item in self.config['markdown_extensions']:
if isinstance(item, str):
extensions.append(item)
else:
k, v = list(item.items())[0]
extensions.append(k)
if v ... | def setup(self) | Setup. | 2.803526 | 2.669777 | 1.050097 |
self.markdown.reset()
return self.markdown.convert(text) | def _filter(self, text) | Filter markdown. | 10.305912 | 5.304746 | 1.942772 |
prefixes = ["", "m", "u", "n"]
unit = 0
while s < 1 and unit + 1 < len(prefixes):
s *= 1000
unit += 1
return "{:.1f} {}s".format(s, prefixes[unit]) | def format_sec(s) | Format seconds in a more human readable way. It supports units down to
nanoseconds.
:param s: Float of seconds to format
:return: String second representation, like 12.4 us | 3.455178 | 2.964277 | 1.165606 |
data = kwargs
headers = kwargs.get('headers', {})
if 'headers' in data:
del data['headers']
return self._create("/entities", data=data, coerce=self.get_entity, headers=headers) | def create_entity(self, **kwargs) | kwargs expected:
'who': kwargs.get('who')
'why': kwargs.get('why')
'uri': kwargs.get('uri')
'ip_addresses': kwargs.get('ip_addresses', {})
'label': kwargs.get('label')
'agent_id': kwargs.get('agent_id')
'metadata': kwargs.get('extra', {... | 4.699702 | 4.418325 | 1.063684 |
pfeed = pf.read_protofeed(source_path)
feed = m.build_feed(pfeed, buffer=buffer)
gt.write_gtfs(feed, target_path, ndigits=ndigits) | def make_gtfs(source_path, target_path, buffer, ndigits) | Create a GTFS feed from the files in the directory SOURCE_PATH.
See the project README for a description of the required source
files.
Save the feed to the file or directory TARGET_PATH.
If the target path ends in '.zip', then write the feed as a zip
archive.
Otherwise assume the path is a direc... | 4.86705 | 6.117616 | 0.79558 |
logger = getLogger('decode.utils.ndarray.psd')
if overlap_half:
step = int(len(data) / (ndivide + 1))
size = step * 2
else:
step = int(len(data) / ndivide)
size = step
if bin(len(data)).count('1') != 1:
logger.warning('warning: length of data is not power o... | def psd(data, dt, ndivide=1, window=hanning, overlap_half=False) | Calculate power spectrum density of data.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
ax (matplotlib.axes): Axis you want to plot on.
doplot (bool): Plot ho... | 3.05059 | 3.086169 | 0.988472 |
allanvar = []
nmax = len(data) if len(data) < tmax / dt else int(tmax / dt)
for i in range(1, nmax+1):
databis = data[len(data) % i:]
y = databis.reshape(len(data)//i, i).mean(axis=1)
allanvar.append(((y[1:] - y[:-1])**2).mean() / 2)
return dt * np.arange(1, nmax+1), np.arra... | def allan_variance(data, dt, tmax=10) | Calculate Allan variance.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
tmax (float): Maximum time.
Returns:
vk (np.ndarray): Frequency.
allanvar (np.ndarray): Allan variance. | 3.304106 | 3.547335 | 0.931433 |
# Path should already be sanitized
attributes = _get_attributes_from_path(path)
try:
if len(attributes) == 3:
# If an item, create a collection for the item.
item = attributes.pop()
path = "/".join(attributes)
... | def discover(cls, path, depth="0") | Discover a list of collections under the given ``path``.
If ``depth`` is "0", only the actual object under ``path`` is
returned.
If ``depth`` is anything but "0", it is considered as "1" and direct
children are included in the result.
The ``path`` is relative.
The roo... | 4.820391 | 4.802402 | 1.003746 |
if self.is_fake:
return
entry = None
for entry in self.journal.list():
pass
return entry.uid if entry is not None else hashlib.sha256(b"").hexdigest() | def etag(self) | Encoded as quoted-string (see RFC 2616). | 8.181103 | 7.715904 | 1.060291 |
# Path should already be sanitized
attributes = _get_attributes_from_path(href)
if len(attributes) <= 1:
raise PrincipalNotAllowedError
# Try to infer tag
if not props:
props = {}
if not props.get("tag") and collection:
props[... | def create_collection(cls, href, collection=None, props=None) | Create a collection.
If the collection already exists and neither ``collection`` nor
``props`` are set, this method shouldn't do anything. Otherwise the
existing collection must be replaced.
``collection`` is a list of vobject components.
``props`` are metadata values for the ... | 3.75997 | 3.605114 | 1.042955 |
# FIXME: Actually implement
token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"")
if old_token:
raise ValueError("Sync token are not supported (you can ignore this warning)")
return token, self.list() | def sync(self, old_token=None) | Get the current sync token and changed items for synchronization.
``old_token`` an old sync token which is used as the base of the
delta update. If sync token is missing, all items are returned.
ValueError is raised for invalid or old tokens. | 14.629691 | 15.217252 | 0.961389 |
if self.is_fake:
return
for item in self.collection.list():
yield item.uid + self.content_suffix | def list(self) | List collection items. | 14.817414 | 11.715145 | 1.264808 |
if self.is_fake:
return
uid = _trim_suffix(href, ('.ics', '.ical', '.vcf'))
etesync_item = self.collection.get(uid)
if etesync_item is None:
return None
try:
item = vobject.readOne(etesync_item.content)
except Exception as e:... | def get(self, href) | Fetch a single item. | 4.439227 | 4.373701 | 1.014982 |
if self.is_fake:
return
content = vobject_item.serialize()
try:
item = self.get(href)
etesync_item = item.etesync_item
etesync_item.content = content
except api.exceptions.DoesNotExist:
etesync_item = self.collection.g... | def upload(self, href, vobject_item) | Upload a new or replace an existing item. | 4.282589 | 4.183959 | 1.023573 |
if self.is_fake:
return
if href is None:
self.collection.delete()
return
item = self.get(href)
if item is None:
raise ComponentNotFoundError(href)
item.etesync_item.delete() | def delete(self, href=None) | Delete an item.
When ``href`` is ``None``, delete the collection. | 6.985709 | 6.93222 | 1.007716 |
if self.is_fake:
return {}
if key == "tag":
return self.tag
elif key is None:
ret = {}
for key in self.journal.info.keys():
ret[key] = self.meta_mappings.map_get(self.journal.info, key)[1]
return ret
el... | def get_meta(self, key=None) | Get metadata value for collection. | 4.136535 | 4.020545 | 1.028849 |
if self.is_fake:
return
props = {}
for key, value in _props.items():
key, value = self.meta_mappings.map_set(key, value)
props[key] = value
# Pop out tag which we don't want
props.pop("tag", None)
self.journal.update_info({}... | def set_meta(self, _props) | Set metadata values for collection. | 5.192086 | 5.088137 | 1.02043 |
delta_props = self.get_meta()
for key in delta_props.keys():
if key not in props:
delta_props[key] = None
delta_props.update(props)
self.set_meta(delta_props) | def set_meta_all(self, props) | Set metadata values for collection.
``props`` a dict with values for properties. | 2.652008 | 2.82871 | 0.937532 |
# FIXME: Make this sensible
last_modified = time.strftime(
"%a, %d %b %Y %H:%M:%S GMT",
time.gmtime(time.time()))
return last_modified | def last_modified(self) | Get the HTTP-datetime of when the collection was modified. | 3.876614 | 3.246117 | 1.194231 |
import datetime
items = []
time_begin = datetime.datetime.now()
for href in self.list():
items.append(self.get(href).item)
time_end = datetime.datetime.now()
self.logger.info(
"Collection read %d items in %s sec from %s", len(items),
... | def serialize(self) | Get the unicode string representing the whole collection. | 3.628175 | 3.377568 | 1.074197 |
if not user:
return
with EteSyncCache.lock:
cls.user = user
cls.etesync = cls._get_etesync_for_user(cls.user)
if cls._should_sync():
cls._mark_sync()
cls.etesync.get_or_create_user_info(force_fetch=True)
... | def acquire_lock(cls, mode, user=None) | Set a context manager to lock the whole storage.
``mode`` must either be "r" for shared access or "w" for exclusive
access.
``user`` is the name of the logged in user or empty. | 3.47558 | 3.60165 | 0.964997 |
super().validate_options(k, v)
if k == 'charset_size':
if v not in (1, 2, 4):
raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v))
elif k == 'wide_charset_size':
if v not in (2, 4):
raise ... | def validate_options(self, k, v) | Validate options. | 3.139176 | 3.096381 | 1.013821 |
return not (stype - self.string_types) or bool(stype & self.wild_string_types) | def match_string(self, stype) | Match string type. | 15.470814 | 12.677881 | 1.2203 |
name = codecs.lookup(
filters.PYTHON_ENCODING_NAMES.get(name, name).lower()
).name
if name.startswith(('utf-32', 'utf-16')):
name = name[:6]
if CURRENT_ENDIAN == BIG_ENDIAN:
name += '-be'
else:
name += '-l... | def get_encoding_name(self, name) | Get encoding name. | 4.86518 | 4.703772 | 1.034315 |
self.blocks = self.config['block_comments']
self.lines = self.config['line_comments']
self.group_comments = self.config['group_comments']
self.prefix = self.config['prefix']
self.generic_mode = self.config['generic_mode']
self.strings = self.config['strings']
... | def setup(self) | Setup. | 2.970747 | 2.926607 | 1.015082 |
if self.blocks:
self.block_comments.append([groups['block'][2:-2], self.line_num, self.current_encoding]) | def evaluate_block(self, groups) | Evaluate block comments. | 13.881173 | 8.865573 | 1.565739 |
if self.lines:
self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding]) | def evaluate_inline_tail(self, groups) | Evaluate inline comments at the tail of source code. | 12.581888 | 10.263683 | 1.225865 |
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if (
self.group_comments and
self.line_num == self.prev_line + 1 and
groups['leading_space'] == self.lead... | def evaluate_inline(self, groups) | Evaluate inline comments on their own lines. | 4.421943 | 4.316439 | 1.024442 |
if value.startswith('u8'):
length = 1
value = value[3:-1]
encoding = 'utf-8'
elif value.startswith('u'):
length = 2
value = value[2:-1]
encoding = 'utf-16'
else:
length = 4
value = value[2:-... | def evaluate_unicode(self, value) | Evaluate Unicode. | 3.346416 | 3.292363 | 1.016417 |
if value.startswith('L'):
size = self.wide_charset_size
encoding = self.wide_exec_charset
value = value[2:-1]
pack = BYTE_STORE[size | CURRENT_ENDIAN]
else:
size = self.charset_size
encoding = self.exec_charset
... | def evaluate_normal(self, value) | Evaluate normal string. | 3.240843 | 3.157367 | 1.026438 |
if self.strings:
encoding = self.current_encoding
if self.generic_mode:
# Generic assumes no escapes rules.
self.quoted_strings.append([groups['strings'][1:-1], self.line_num, encoding])
else:
value = groups['strings']... | def evaluate_strings(self, groups) | Evaluate strings. | 5.614809 | 5.529504 | 1.015427 |
g = m.groupdict()
if g["strings"]:
self.evaluate_strings(g)
self.line_num += g['strings'].count('\n')
elif g["code"]:
self.line_num += g["code"].count('\n')
else:
if g['block']:
self.evaluate_block(g)
e... | def evaluate(self, m) | Search for comments. | 3.489096 | 3.32736 | 1.048608 |
prefix = self.prefix + '-' if self.prefix else ''
for comment, line, encoding in text_list:
content.append(
filters.SourceText(
textwrap.dedent(comment),
"%s (%d)" % (context, line),
encoding,
... | def extend_src_text(self, content, context, text_list, category) | Extend the source text list with the gathered text data. | 8.05887 | 7.707623 | 1.045571 |
if self.trigraphs:
text = RE_TRIGRAPHS.sub(self.process_trigraphs, text)
for m in self.pattern.finditer(self.norm_nl(text)):
self.evaluate(m) | def find_content(self, text) | Find content. | 6.887242 | 6.760779 | 1.018705 |
# initialize coords with default values
cube = xr.DataArray(data, dims=('x', 'y', 'ch'), attrs=attrs, name=name)
cube.dcc._initcoords()
# update coords with input values (if any)
if xcoords is not None:
cube.coords.update({key: ('x', xcoords[key]) for key in xcoords})
if ycoords i... | def cube(data, xcoords=None, ycoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None) | Create a cube as an instance of xarray.DataArray with Decode accessor.
Args:
data (numpy.ndarray): 3D (x x y x channel) array.
xcoords (dict, optional): Dictionary of arrays that label x axis.
ycoords (dict, optional): Dictionary of arrays that label y axis.
chcoords (dict, optional... | 2.069294 | 2.114125 | 0.978794 |
array = dc.zeros_like(template)
y, x = array.y.values, array.x.values
gy, gx = cube.y.values, cube.x.values
iy = interp1d(gy, np.arange(len(gy)))(y)
ix = interp1d(gx, np.arange(len(gx)))(x)
for ch in range(len(cube.ch)):
array[:,ch] = map_coordinates(cube.values[:,:,ch], (ix, iy))... | def fromcube(cube, template) | Covert a decode cube to a decode array.
Args:
cube (decode.cube): Decode cube to be cast.
template (decode.array): Decode array whose shape the cube is cast on.
Returns:
decode array (decode.array): Decode array.
Notes:
This functions is under development. | 3.450253 | 4.265552 | 0.808864 |
### pick up kwargs
inchs = kwargs.pop('inchs', None)
exchs = kwargs.pop('exchs', None)
if (inchs is not None) or (exchs is not None):
raise KeyError('Inchs and exchs are no longer supported. Use weight instead.')
# if inchs is not None:
# logger.info('inchs')
# logger.... | def makecontinuum(cube, **kwargs) | Make a continuum array.
Args:
cube (decode.cube): Decode cube which will be averaged over channels.
kwargs (optional): Other arguments.
inchs (list): Included channel kidids.
exchs (list): Excluded channel kidids.
Returns:
decode cube (decode.cube): Decode cube ... | 2.947156 | 2.733909 | 1.078001 |
enc = PYTHON_ENCODING_NAMES.get(enc, enc)
try:
codecs.getencoder(enc)
encoding = enc
except LookupError:
encoding = None
return encoding | def _verify_encoding(self, enc) | Verify encoding is okay. | 4.987614 | 4.404614 | 1.132361 |
content = f.read(4)
encoding = None
m = RE_UTF_BOM.match(content)
if m is not None:
if m.group(1):
encoding = 'utf-8-sig'
elif m.group(2):
encoding = 'utf-32'
elif m.group(3):
encoding = 'utf-32... | def has_bom(self, f) | Check for UTF8, UTF16, and UTF32 BOMs. | 2.216937 | 1.99375 | 1.111944 |
if encoding is None:
pass
elif encoding.lower() == 'utf-8':
encoding = 'utf-8-sig'
elif encoding.lower().startswith('utf-16'):
encoding = 'utf-16'
elif encoding.lower().startswith('utf-32'):
encoding = 'utf-32'
return enco... | def _utf_strip_bom(self, encoding) | Return an encoding that will ignore the BOM. | 2.028862 | 1.779433 | 1.140174 |
encoding = None
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
encoding = self._analyze_file(m)
return encoding | def _detect_buffer_encoding(self, f) | Guess by checking BOM, and checking `_special_encode_check`, and using memory map. | 3.528274 | 3.07063 | 1.149039 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.