text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def purge_bucket(context, provider, **kwargs):
"""Delete objects in bucket."""
session = get_session(provider.region)
if kwargs.get('bucket_name'):
bucket_name = kwargs['bucket_name']
else:
if kwargs.get('bucket_output_lookup'):
value = kwargs['bucket_output_lookup']
... | [
"def",
"purge_bucket",
"(",
"context",
",",
"provider",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"get_session",
"(",
"provider",
".",
"region",
")",
"if",
"kwargs",
".",
"get",
"(",
"'bucket_name'",
")",
":",
"bucket_name",
"=",
"kwargs",
"[",
... | 34.52 | 0.000563 |
def bind_socket(sock, channel='can0'):
"""
Binds the given socket to the given interface.
:param socket.socket sock:
The socket to be bound
:raises OSError:
If the specified interface isn't found.
"""
log.debug('Binding socket to channel=%s', channel)
if HAS_NATIVE_SUPPORT:
... | [
"def",
"bind_socket",
"(",
"sock",
",",
"channel",
"=",
"'can0'",
")",
":",
"log",
".",
"debug",
"(",
"'Binding socket to channel=%s'",
",",
"channel",
")",
"if",
"HAS_NATIVE_SUPPORT",
":",
"sock",
".",
"bind",
"(",
"(",
"channel",
",",
")",
")",
"else",
... | 28.705882 | 0.001984 |
def database_all(self):
"""Return a dictionary mapping engines with databases
"""
all = {}
for engine in self.engines():
all[engine] = self._database_all(engine)
return all | [
"def",
"database_all",
"(",
"self",
")",
":",
"all",
"=",
"{",
"}",
"for",
"engine",
"in",
"self",
".",
"engines",
"(",
")",
":",
"all",
"[",
"engine",
"]",
"=",
"self",
".",
"_database_all",
"(",
"engine",
")",
"return",
"all"
] | 31.142857 | 0.008929 |
def page(title, description, element_list=None, tab_list=None):
"""
Returns a dictionary representing a new page to display elements.
This can be thought of as a simple container for displaying multiple
types of information. The ``section`` method can be used to create
separate tabs.
Args:
... | [
"def",
"page",
"(",
"title",
",",
"description",
",",
"element_list",
"=",
"None",
",",
"tab_list",
"=",
"None",
")",
":",
"_page",
"=",
"{",
"'Type'",
":",
"'Page'",
",",
"'Title'",
":",
"title",
",",
"'Description'",
":",
"description",
",",
"'Data'",
... | 34.555556 | 0.000782 |
def merge(config):
"""Merge the current branch into master."""
repo = config.repo
active_branch = repo.active_branch
if active_branch.name == "master":
error_out("You're already on the master branch.")
if repo.is_dirty():
error_out(
'Repo is "dirty". ({})'.format(
... | [
"def",
"merge",
"(",
"config",
")",
":",
"repo",
"=",
"config",
".",
"repo",
"active_branch",
"=",
"repo",
".",
"active_branch",
"if",
"active_branch",
".",
"name",
"==",
"\"master\"",
":",
"error_out",
"(",
"\"You're already on the master branch.\"",
")",
"if",... | 30.853659 | 0.000766 |
def _encodeTimestamp(timestamp):
""" Encodes a 7-octet timestamp from the specified date
Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases
:param timestamp: The timestamp to encode
:type timestamp: datetime.datetime
... | [
"def",
"_encodeTimestamp",
"(",
"timestamp",
")",
":",
"if",
"timestamp",
".",
"tzinfo",
"==",
"None",
":",
"raise",
"ValueError",
"(",
"'Please specify time zone information for the timestamp (e.g. by using gsmmodem.util.SimpleOffsetTzInfo)'",
")",
"# See if the timezone differe... | 42.62963 | 0.009346 |
def setCurrentLayer(self, layer):
"""
Sets the current layer for this scene to the inputed layer.
:param layer | <XNodeLayer> || None
"""
if self._currentLayer == layer:
return False
old = self._currentLayer
self._currentLayer = ... | [
"def",
"setCurrentLayer",
"(",
"self",
",",
"layer",
")",
":",
"if",
"self",
".",
"_currentLayer",
"==",
"layer",
":",
"return",
"False",
"old",
"=",
"self",
".",
"_currentLayer",
"self",
".",
"_currentLayer",
"=",
"layer",
"if",
"old",
"is",
"not",
"Non... | 24.857143 | 0.012915 |
def pop(self, arg=None):
"""Removes the child at given position or by name (or name iterator).
if no argument is given removes the last."""
self._stable = False
if arg is None:
arg = len(self.childs) - 1
if isinstance(arg, int):
try:
re... | [
"def",
"pop",
"(",
"self",
",",
"arg",
"=",
"None",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"len",
"(",
"self",
".",
"childs",
")",
"-",
"1",
"if",
"isinstance",
"(",
"arg",
",",
"int",
")",
... | 36.533333 | 0.001778 |
def sync(self, vault_client):
"""Synchronizes the local and remote Vault resources. Has the net
effect of adding backend if needed"""
if self.present:
if not self.existing:
LOG.info("Mounting %s backend on %s",
self.backend, self.path)
... | [
"def",
"sync",
"(",
"self",
",",
"vault_client",
")",
":",
"if",
"self",
".",
"present",
":",
"if",
"not",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"Mounting %s backend on %s\"",
",",
"self",
".",
"backend",
",",
"self",
".",
"path",
")... | 40.454545 | 0.002195 |
def detect(self, stream, threshold, threshold_type, trig_int, plotvar,
pre_processed=False, daylong=False, parallel_process=True,
xcorr_func=None, concurrency=None, cores=None,
ignore_length=False, overlap="calculate", debug=0,
full_peaks=False):
"""
... | [
"def",
"detect",
"(",
"self",
",",
"stream",
",",
"threshold",
",",
"threshold_type",
",",
"trig_int",
",",
"plotvar",
",",
"pre_processed",
"=",
"False",
",",
"daylong",
"=",
"False",
",",
"parallel_process",
"=",
"True",
",",
"xcorr_func",
"=",
"None",
"... | 46.356164 | 0.001302 |
def power_up(self):
""" Changes all settings to guarantee the motors will be used at their maximum power. """
for m in self.motors:
m.compliant = False
m.moving_speed = 0
m.torque_limit = 100.0 | [
"def",
"power_up",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"motors",
":",
"m",
".",
"compliant",
"=",
"False",
"m",
".",
"moving_speed",
"=",
"0",
"m",
".",
"torque_limit",
"=",
"100.0"
] | 40 | 0.012245 |
def threads_list(io_handler, max_depth=1):
"""
Lists the active threads and their current code line
"""
# Normalize maximum depth
try:
max_depth = int(max_depth)
if max_depth < 1:
max_depth = None
except (ValueError, TypeError):
... | [
"def",
"threads_list",
"(",
"io_handler",
",",
"max_depth",
"=",
"1",
")",
":",
"# Normalize maximum depth",
"try",
":",
"max_depth",
"=",
"int",
"(",
"max_depth",
")",
"if",
"max_depth",
"<",
"1",
":",
"max_depth",
"=",
"None",
"except",
"(",
"ValueError",
... | 28.640625 | 0.001055 |
def iau2000b(jd_tt):
"""Compute Earth nutation based on the faster IAU 2000B nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each is either a float, or a NumPy array with
... | [
"def",
"iau2000b",
"(",
"jd_tt",
")",
":",
"dpplan",
"=",
"-",
"0.000135",
"*",
"1e7",
"deplan",
"=",
"0.000388",
"*",
"1e7",
"t",
"=",
"(",
"jd_tt",
"-",
"T0",
")",
"/",
"36525.0",
"# TODO: can these be replaced with fa0 and f1?",
"el",
"=",
"fmod",
"(",
... | 28.471698 | 0.014734 |
def get_changed_files(include_staged=False):
"""
Returns a list of the files that changed in the Git repository. This is
used to check if the files that are supposed to be upgraded have changed.
If so, the upgrade will be prevented.
"""
process = subprocess.Popen(['git', 'status', '--porcelain'],
stdou... | [
"def",
"get_changed_files",
"(",
"include_staged",
"=",
"False",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'git'",
",",
"'status'",
",",
"'--porcelain'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subpro... | 35.315789 | 0.015965 |
def AddPerformanceOptions(self, argument_group):
"""Adds the performance options to the argument group.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_group.add_argument(
'--buffer_size', '--buffer-size', '--bs', dest='buffer_size',
action='s... | [
"def",
"AddPerformanceOptions",
"(",
"self",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--buffer_size'",
",",
"'--buffer-size'",
",",
"'--bs'",
",",
"dest",
"=",
"'buffer_size'",
",",
"action",
"=",
"'store'",
",",
"default",
... | 41.4375 | 0.001475 |
def p_create_instance_event_statement_2(self, p):
'''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO self_access'''
p[0] = CreateInstanceEventNode(variable_name=p[4],
event_specification=p[6],
to_vari... | [
"def",
"p_create_instance_event_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"CreateInstanceEventNode",
"(",
"variable_name",
"=",
"p",
"[",
"4",
"]",
",",
"event_specification",
"=",
"p",
"[",
"6",
"]",
",",
"to_variable_access",
... | 66.6 | 0.008902 |
def apply_colormap(image, colormap, contig=True):
"""Return palette-colored image.
The image values are used to index the colormap on axis 1. The returned
image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype.
Parameters
----------
image : numpy.ndarray
Indexes into ... | [
"def",
"apply_colormap",
"(",
"image",
",",
"colormap",
",",
"contig",
"=",
"True",
")",
":",
"image",
"=",
"numpy",
".",
"take",
"(",
"colormap",
",",
"image",
",",
"axis",
"=",
"1",
")",
"image",
"=",
"numpy",
".",
"rollaxis",
"(",
"image",
",",
... | 32.071429 | 0.001081 |
def _validate_user_inputs(self, attributes=None, event_tags=None):
""" Helper method to validate user inputs.
Args:
attributes: Dict representing user attributes.
event_tags: Dict representing metadata associated with an event.
Returns:
Boolean True if inputs are valid. False otherwise.
... | [
"def",
"_validate_user_inputs",
"(",
"self",
",",
"attributes",
"=",
"None",
",",
"event_tags",
"=",
"None",
")",
":",
"if",
"attributes",
"and",
"not",
"validator",
".",
"are_attributes_valid",
"(",
"attributes",
")",
":",
"self",
".",
"logger",
".",
"error... | 38.173913 | 0.01 |
def set_disk0(self, disk0):
"""
Sets the size (MB) for PCMCIA disk0.
:param disk0: disk0 size (integer)
"""
yield from self._hypervisor.send('vm set_disk0 "{name}" {disk0}'.format(name=self._name, disk0=disk0))
log.info('Router "{name}" [{id}]: disk0 updated from {old_... | [
"def",
"set_disk0",
"(",
"self",
",",
"disk0",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_disk0 \"{name}\" {disk0}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"disk0",
"=",
"disk0",
")",
")",
"log... | 52.785714 | 0.009309 |
def _clipboard(self, pri=False):
""" C """
# Copy highlighted url to clipboard
fpo = self.top.body.focus_position
url_idx = len([i for i in self.items[:fpo + 1]
if isinstance(i, urwid.Columns)]) - 1
if self.compact is False and fpo <= 1:
return
... | [
"def",
"_clipboard",
"(",
"self",
",",
"pri",
"=",
"False",
")",
":",
"# Copy highlighted url to clipboard",
"fpo",
"=",
"self",
".",
"top",
".",
"body",
".",
"focus_position",
"url_idx",
"=",
"len",
"(",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"items",... | 39.636364 | 0.00224 |
def page_attr(title=None, **kwargs):
"""
Page Attr allows you to add page meta data in the request `g` context
:params **kwargs:
meta keys we're expecting:
title (str)
description (str)
url (str) (Will pick it up by itself if not set)
image (str)
site_name (str) ... | [
"def",
"page_attr",
"(",
"title",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"dict",
"(",
"title",
"=",
"\"\"",
",",
"description",
"=",
"\"\"",
",",
"url",
"=",
"\"\"",
",",
"image",
"=",
"\"\"",
",",
"site_name",
"=",
"\"\"",... | 24.02439 | 0.000976 |
def list_floating_ip_actions(self, ip_addr):
"""
Retrieve a list of all actions that have been executed on a Floating IP.
"""
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions')
return json['actions']
else:
ra... | [
"def",
"list_floating_ip_actions",
"(",
"self",
",",
"ip_addr",
")",
":",
"if",
"self",
".",
"api_version",
"==",
"2",
":",
"json",
"=",
"self",
".",
"request",
"(",
"'/floating_ips/'",
"+",
"ip_addr",
"+",
"'/actions'",
")",
"return",
"json",
"[",
"'actio... | 38.222222 | 0.008523 |
def _simple_name(distribution):
"""Infer the original name passed into a distribution constructor.
Distributions typically follow the pattern of
with.name_scope(name) as name:
super(name=name)
so we attempt to reverse the name-scope transformation to allow
addressing of RVs by the distribution's original... | [
"def",
"_simple_name",
"(",
"distribution",
")",
":",
"simple_name",
"=",
"distribution",
".",
"name",
"# turn 'scope/x/' into 'x'",
"if",
"simple_name",
".",
"endswith",
"(",
"'/'",
")",
":",
"simple_name",
"=",
"simple_name",
".",
"split",
"(",
"'/'",
")",
"... | 24.540541 | 0.009534 |
def scores(factors):
""" Computes the score of temperaments
and elements.
"""
temperaments = {
const.CHOLERIC: 0,
const.MELANCHOLIC: 0,
const.SANGUINE: 0,
const.PHLEGMATIC: 0
}
qualities = {
const.HOT: 0,
const.COLD: 0,
... | [
"def",
"scores",
"(",
"factors",
")",
":",
"temperaments",
"=",
"{",
"const",
".",
"CHOLERIC",
":",
"0",
",",
"const",
".",
"MELANCHOLIC",
":",
"0",
",",
"const",
".",
"SANGUINE",
":",
"0",
",",
"const",
".",
"PHLEGMATIC",
":",
"0",
"}",
"qualities",... | 23.171429 | 0.009467 |
def import_obj(cls, slc_to_import, slc_to_override, import_time=None):
"""Inserts or overrides slc in the database.
remote_id and import_time fields in params_dict are set to track the
slice origin and ensure correct overrides for multiple imports.
Slice.perm is used to find the datasou... | [
"def",
"import_obj",
"(",
"cls",
",",
"slc_to_import",
",",
"slc_to_override",
",",
"import_time",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"session",
"make_transient",
"(",
"slc_to_import",
")",
"slc_to_import",
".",
"dashboards",
"=",
"[",
"]",
"s... | 43.870968 | 0.001439 |
def minimum_valid_values_in_any_group(df, levels=None, n=1, invalid=np.nan):
"""
Filter ``DataFrame`` by at least n valid values in at least one group.
Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove
rows where there are less than `n` valid values per group. Gro... | [
"def",
"minimum_valid_values_in_any_group",
"(",
"df",
",",
"levels",
"=",
"None",
",",
"n",
"=",
"1",
",",
"invalid",
"=",
"np",
".",
"nan",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"if",
"levels",
"is",
"None",
":",
"if",
"'Group'",
"in"... | 40.783784 | 0.008414 |
def convert_time_units(t):
""" Convert time in seconds into reasonable time units. """
if t == 0:
return '0 s'
order = log10(t)
if -9 < order < -6:
time_units = 'ns'
factor = 1000000000
elif -6 <= order < -3:
time_units = 'us'
factor = 1000000
elif -3 <= o... | [
"def",
"convert_time_units",
"(",
"t",
")",
":",
"if",
"t",
"==",
"0",
":",
"return",
"'0 s'",
"order",
"=",
"log10",
"(",
"t",
")",
"if",
"-",
"9",
"<",
"order",
"<",
"-",
"6",
":",
"time_units",
"=",
"'ns'",
"factor",
"=",
"1000000000",
"elif",
... | 26.777778 | 0.002004 |
def create_hds_stream(self, localStreamNames, targetFolder, **kwargs):
"""
Create an HDS (HTTP Dynamic Streaming) stream out of an existing
H.264/AAC stream. HDS is used to stream standard MP4 media over
regular HTTP connections.
:param localStreamNames: The stream(s) that will ... | [
"def",
"create_hds_stream",
"(",
"self",
",",
"localStreamNames",
",",
"targetFolder",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"protocol",
".",
"execute",
"(",
"'createhdsstream'",
",",
"localStreamNames",
"=",
"localStreamNames",
",",
"targetF... | 41.776316 | 0.000615 |
def info(package, conn=None):
'''
List info for a package
'''
close = False
if conn is None:
close = True
conn = init()
fields = (
'package',
'version',
'release',
'installed',
'os',
'os_family',
'dependencies',
'os... | [
"def",
"info",
"(",
"package",
",",
"conn",
"=",
"None",
")",
":",
"close",
"=",
"False",
"if",
"conn",
"is",
"None",
":",
"close",
"=",
"True",
"conn",
"=",
"init",
"(",
")",
"fields",
"=",
"(",
"'package'",
",",
"'version'",
",",
"'release'",
","... | 20.222222 | 0.001311 |
def __get_files_to_be_added(self, repository):
"""
:return: the files that have been modified and can be added
"""
for root, dirs, files in os.walk(repository.working_dir):
for f in files:
relative_path = os.path.join(root, f)[len(repository.working_dir) + 1:]... | [
"def",
"__get_files_to_be_added",
"(",
"self",
",",
"repository",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"repository",
".",
"working_dir",
")",
":",
"for",
"f",
"in",
"files",
":",
"relative_path",
"=",
"os",
... | 42.416667 | 0.011538 |
def CreatedField(name='created', tz_aware=False, **kwargs):
''' A shortcut field for creation time. It sets the current date and time
when it enters the database and then doesn't update on further saves.
If you've used the Django ORM, this is the equivalent of auto_now_add
:param tz_aware... | [
"def",
"CreatedField",
"(",
"name",
"=",
"'created'",
",",
"tz_aware",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"computed_field",
"(",
"DateTimeField",
"(",
")",
",",
"one_time",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"def",
"created",... | 41.647059 | 0.001381 |
def confirm(text, default=False, abort=False, prompt_suffix=': ',
show_default=True, err=False):
"""Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this
function will catch it and raise a :exc:`Abort` exception.
.. versionadded:: 4.0
... | [
"def",
"confirm",
"(",
"text",
",",
"default",
"=",
"False",
",",
"abort",
"=",
"False",
",",
"prompt_suffix",
"=",
"': '",
",",
"show_default",
"=",
"True",
",",
"err",
"=",
"False",
")",
":",
"prompt",
"=",
"_build_prompt",
"(",
"text",
",",
"prompt_... | 37.071429 | 0.000626 |
def component_suites(request, resource=None, component=None, extra_element="", **kwargs):
'Return part of a client-side component, served locally for some reason'
get_params = request.GET.urlencode()
if get_params and False:
redone_url = "/static/dash/component/%s/%s%s?%s" %(component, extra_elemen... | [
"def",
"component_suites",
"(",
"request",
",",
"resource",
"=",
"None",
",",
"component",
"=",
"None",
",",
"extra_element",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"get_params",
"=",
"request",
".",
"GET",
".",
"urlencode",
"(",
")",
"if",
"g... | 49.4 | 0.011928 |
def emit(self, span_datas):
"""Send SpanData tuples to Zipkin server, default using the v2 API.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
... | [
"def",
"emit",
"(",
"self",
",",
"span_datas",
")",
":",
"try",
":",
"zipkin_spans",
"=",
"self",
".",
"translate_to_zipkin",
"(",
"span_datas",
")",
"result",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"self",
".",
"url",
",",
"data",
"=",
"json",... | 38.181818 | 0.002323 |
def create_data_item_from_data(self, data: numpy.ndarray, title: str=None) -> DataItem:
"""Create a data item in the library from data.
.. versionadded:: 1.0
.. deprecated:: 1.1
Use :py:meth:`~nion.swift.Facade.Library.create_data_item_from_data` instead.
Scriptable: No
... | [
"def",
"create_data_item_from_data",
"(",
"self",
",",
"data",
":",
"numpy",
".",
"ndarray",
",",
"title",
":",
"str",
"=",
"None",
")",
"->",
"DataItem",
":",
"return",
"DataItem",
"(",
"self",
".",
"__document_controller",
".",
"add_data",
"(",
"data",
"... | 39.2 | 0.014963 |
def list_example():
""" Example list pagination.
"""
from uuid import uuid4
from redis import StrictRedis
from zato.redis_paginator import ListPaginator
conn = StrictRedis()
key = 'paginator:{}'.format(uuid4().hex)
for x in range(1, 18):
conn.rpush(key, x)
... | [
"def",
"list_example",
"(",
")",
":",
"from",
"uuid",
"import",
"uuid4",
"from",
"redis",
"import",
"StrictRedis",
"from",
"zato",
".",
"redis_paginator",
"import",
"ListPaginator",
"conn",
"=",
"StrictRedis",
"(",
")",
"key",
"=",
"'paginator:{}'",
".",
"form... | 24.458333 | 0.014754 |
def toggle_wrap_mode(self, checked):
"""Toggle wrap mode"""
self.plain_text.editor.toggle_wrap_mode(checked)
self.set_option('wrap', checked) | [
"def",
"toggle_wrap_mode",
"(",
"self",
",",
"checked",
")",
":",
"self",
".",
"plain_text",
".",
"editor",
".",
"toggle_wrap_mode",
"(",
"checked",
")",
"self",
".",
"set_option",
"(",
"'wrap'",
",",
"checked",
")"
] | 41.25 | 0.011905 |
def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
")",
".",
"get_queryset",
"(",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
"return",
"qs"
] | 33.8 | 0.011561 |
def internal_name(self):
"""
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq | [
"def",
"internal_name",
"(",
"self",
")",
":",
"unq",
"=",
"super",
"(",
")",
".",
"internal_name",
"(",
")",
"if",
"self",
".",
"tret",
"is",
"not",
"None",
":",
"unq",
"+=",
"\"_\"",
"+",
"self",
".",
"tret",
"return",
"unq"
] | 25.875 | 0.009346 |
def classify(self, phrase, cut_to_len=True):
""" Classify a phrase based on the loaded model. If cut_to_len is True, cut to
desired length."""
if (len(phrase) > self.max_phrase_len):
if not cut_to_len:
raise Exception("Phrase too long.")
phrase = phrase[0:self.max... | [
"def",
"classify",
"(",
"self",
",",
"phrase",
",",
"cut_to_len",
"=",
"True",
")",
":",
"if",
"(",
"len",
"(",
"phrase",
")",
">",
"self",
".",
"max_phrase_len",
")",
":",
"if",
"not",
"cut_to_len",
":",
"raise",
"Exception",
"(",
"\"Phrase too long.\""... | 46.2 | 0.023355 |
def get_zmat(self, construction_table=None,
use_lookup=None):
"""Transform to internal coordinates.
Transforming to internal coordinates involves basically three
steps:
1. Define an order of how to build and define for each atom
the used reference atoms.
... | [
"def",
"get_zmat",
"(",
"self",
",",
"construction_table",
"=",
"None",
",",
"use_lookup",
"=",
"None",
")",
":",
"if",
"use_lookup",
"is",
"None",
":",
"use_lookup",
"=",
"settings",
"[",
"'defaults'",
"]",
"[",
"'use_lookup'",
"]",
"self",
".",
"get_bond... | 43.947368 | 0.000878 |
def _create_readme(fmt, reffmt):
'''
Creates the readme file for the bundle
Returns a str representing the readme file
'''
now = datetime.datetime.utcnow()
timestamp = now.strftime('%Y-%m-%d %H:%M:%S UTC')
# yapf: disable
outstr = _readme_str.format(timestamp=timestamp,
... | [
"def",
"_create_readme",
"(",
"fmt",
",",
"reffmt",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"timestamp",
"=",
"now",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S UTC'",
")",
"# yapf: disable",
"outstr",
"=",
"_readme_str",
".... | 25.705882 | 0.002208 |
def search_meta(self, attr, value=None, stronly=False):
""" Get a list of Symbols by searching a specific meta
attribute, and optionally the value.
Parameters
----------
attr : str
The meta attribute to query.
value : None, str or list
... | [
"def",
"search_meta",
"(",
"self",
",",
"attr",
",",
"value",
"=",
"None",
",",
"stronly",
"=",
"False",
")",
":",
"if",
"stronly",
":",
"qry",
"=",
"self",
".",
"ses",
".",
"query",
"(",
"Symbol",
".",
"name",
")",
".",
"join",
"(",
"SymbolMeta",
... | 32.404255 | 0.008286 |
def filter_events(cls, client, event_data):
"""Filter registered events and yield them."""
for event in cls.events:
# try event filters
if event.matches(client, event_data):
yield event | [
"def",
"filter_events",
"(",
"cls",
",",
"client",
",",
"event_data",
")",
":",
"for",
"event",
"in",
"cls",
".",
"events",
":",
"# try event filters",
"if",
"event",
".",
"matches",
"(",
"client",
",",
"event_data",
")",
":",
"yield",
"event"
] | 33.714286 | 0.008264 |
def dumpDictHdf5(RV,o):
""" Dump a dictionary where each page is a list or an array """
for key in list(RV.keys()):
o.create_dataset(name=key,data=SP.array(RV[key]),chunks=True,compression='gzip') | [
"def",
"dumpDictHdf5",
"(",
"RV",
",",
"o",
")",
":",
"for",
"key",
"in",
"list",
"(",
"RV",
".",
"keys",
"(",
")",
")",
":",
"o",
".",
"create_dataset",
"(",
"name",
"=",
"key",
",",
"data",
"=",
"SP",
".",
"array",
"(",
"RV",
"[",
"key",
"]... | 52.25 | 0.028302 |
def backbone(self):
"""Returns a new `Residue` containing only the backbone atoms.
Returns
-------
bb_monomer : Residue
`Residue` containing only the backbone atoms of the original
`Monomer`.
Raises
------
IndexError
Raise if ... | [
"def",
"backbone",
"(",
"self",
")",
":",
"try",
":",
"backbone",
"=",
"OrderedDict",
"(",
"[",
"(",
"'N'",
",",
"self",
".",
"atoms",
"[",
"'N'",
"]",
")",
",",
"(",
"'CA'",
",",
"self",
".",
"atoms",
"[",
"'CA'",
"]",
")",
",",
"(",
"'C'",
... | 43.090909 | 0.001376 |
def nodes(self):
"""
Returns an (n,2) list of nodes, or vertices on the path.
Note that this generic class function assumes that all of the
reference points are on the path which is true for lines and
three point arcs.
If you were to define another class where that wasn'... | [
"def",
"nodes",
"(",
"self",
")",
":",
"return",
"np",
".",
"column_stack",
"(",
"(",
"self",
".",
"points",
",",
"self",
".",
"points",
")",
")",
".",
"reshape",
"(",
"-",
"1",
")",
"[",
"1",
":",
"-",
"1",
"]",
".",
"reshape",
"(",
"(",
"-"... | 40.84 | 0.001914 |
def main():
"""
Testing function for DFA brzozowski algebraic method Operation
"""
argv = sys.argv
if len(argv) < 2:
targetfile = 'target.y'
else:
targetfile = argv[1]
print 'Parsing ruleset: ' + targetfile,
flex_a = Flexparser()
mma = flex_a.yyparse(targetfile)
p... | [
"def",
"main",
"(",
")",
":",
"argv",
"=",
"sys",
".",
"argv",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"targetfile",
"=",
"'target.y'",
"else",
":",
"targetfile",
"=",
"argv",
"[",
"1",
"]",
"print",
"'Parsing ruleset: '",
"+",
"targetfile",
",... | 27.5 | 0.001757 |
def _register_numpy_extensions(self):
"""
Numpy extensions are builtin
"""
# system checks
import numpy as np
numpy_floating_types = (np.float16, np.float32, np.float64)
if hasattr(np, 'float128'): # nocover
numpy_floating_types = numpy_floating_types... | [
"def",
"_register_numpy_extensions",
"(",
"self",
")",
":",
"# system checks",
"import",
"numpy",
"as",
"np",
"numpy_floating_types",
"=",
"(",
"np",
".",
"float16",
",",
"np",
".",
"float32",
",",
"np",
".",
"float64",
")",
"if",
"hasattr",
"(",
"np",
","... | 41.537313 | 0.001053 |
def plot_welch_peaks(f, S, peak_loc=None, title=''):
'''Plot welch PSD with peaks as scatter points
Args
----
f: ndarray
Array of frequencies produced with PSD
S: ndarray
Array of powers produced with PSD
peak_loc: ndarray
Indices of peak locations in signal
title: s... | [
"def",
"plot_welch_peaks",
"(",
"f",
",",
"S",
",",
"peak_loc",
"=",
"None",
",",
"title",
"=",
"''",
")",
":",
"plt",
".",
"plot",
"(",
"f",
",",
"S",
",",
"linewidth",
"=",
"_linewidth",
")",
"plt",
".",
"title",
"(",
"title",
")",
"plt",
".",
... | 24.192308 | 0.001529 |
def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
... | [
"def",
"build",
"(",
"self",
",",
"_name",
",",
"*",
"anons",
",",
"*",
"*",
"query",
")",
":",
"builder",
"=",
"self",
".",
"builder",
".",
"get",
"(",
"_name",
")",
"if",
"not",
"builder",
":",
"raise",
"RouteBuildError",
"(",
"\"No route with that n... | 55 | 0.012522 |
def move(src_parent, src_idx, dest_parent, dest_idx):
"""Move an item."""
copy(src_parent, src_idx, dest_parent, dest_idx)
remove(src_parent, src_idx) | [
"def",
"move",
"(",
"src_parent",
",",
"src_idx",
",",
"dest_parent",
",",
"dest_idx",
")",
":",
"copy",
"(",
"src_parent",
",",
"src_idx",
",",
"dest_parent",
",",
"dest_idx",
")",
"remove",
"(",
"src_parent",
",",
"src_idx",
")"
] | 38.25 | 0.025641 |
def bold(text, close=True):
""" Bolds text for terminal outputs
@text: #str to bold
@close: #bool whether or not to reset the bold flag
-> #str bolded @text
..
from vital.debug import bold
bold("Hello world")
# -> '\x1b[1mHello world\x1b[1;m'
... | [
"def",
"bold",
"(",
"text",
",",
"close",
"=",
"True",
")",
":",
"return",
"getattr",
"(",
"colors",
",",
"\"BOLD\"",
")",
"+",
"str",
"(",
"text",
")",
"+",
"(",
"colors",
".",
"RESET",
"if",
"close",
"else",
"\"\"",
")"
] | 25.947368 | 0.001957 |
def needle_msa(reference, results, gap_open=-15, gap_extend=0,
matrix=submat.DNA_SIMPLE):
'''Create a multiple sequence alignment based on aligning every result
sequence against the reference, then inserting gaps until every aligned
reference is identical
'''
gap = '-'
# Convert ... | [
"def",
"needle_msa",
"(",
"reference",
",",
"results",
",",
"gap_open",
"=",
"-",
"15",
",",
"gap_extend",
"=",
"0",
",",
"matrix",
"=",
"submat",
".",
"DNA_SIMPLE",
")",
":",
"gap",
"=",
"'-'",
"# Convert alignments to list of strings",
"alignments",
"=",
"... | 35.714286 | 0.000487 |
def convert_UCERFSource(self, node):
"""
Converts the Ucerf Source node into an SES Control object
"""
dirname = os.path.dirname(self.fname) # where the source_model_file is
source_file = os.path.join(dirname, node["filename"])
if "startDate" in node.attrib and "investigationTime" in node.attri... | [
"def",
"convert_UCERFSource",
"(",
"self",
",",
"node",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"fname",
")",
"# where the source_model_file is",
"source_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
","... | 45.16129 | 0.000699 |
def graph_format(new_mem, old_mem, is_firstiteration=True):
"""Show changes graphically in memory consumption"""
if is_firstiteration:
output = " n/a "
elif new_mem - old_mem > 50000000:
output = " +++++"
elif new_mem - old_mem > 20000000:
output = " ++++ "
elif new_me... | [
"def",
"graph_format",
"(",
"new_mem",
",",
"old_mem",
",",
"is_firstiteration",
"=",
"True",
")",
":",
"if",
"is_firstiteration",
":",
"output",
"=",
"\" n/a \"",
"elif",
"new_mem",
"-",
"old_mem",
">",
"50000000",
":",
"output",
"=",
"\" +++++\"",
"elif... | 31.826087 | 0.001326 |
def set_quota(self, quota_bytes):
"""
Set a quota (in bytes) on this user library. The quota is 'best effort',
and should be set conservatively.
A quota of 0 is 'unlimited'
"""
self.set_library_metadata(ArcticLibraryBinding.QUOTA, quota_bytes)
self.quota = quota... | [
"def",
"set_quota",
"(",
"self",
",",
"quota_bytes",
")",
":",
"self",
".",
"set_library_metadata",
"(",
"ArcticLibraryBinding",
".",
"QUOTA",
",",
"quota_bytes",
")",
"self",
".",
"quota",
"=",
"quota_bytes",
"self",
".",
"quota_countdown",
"=",
"0"
] | 35 | 0.008357 |
def filter_on_demands(ava, required=None, optional=None):
""" Never return more than is needed. Filters out everything
the server is prepared to return but the receiver doesn't ask for
:param ava: Attribute value assertion as a dictionary
:param required: Required attributes
:param optional: Option... | [
"def",
"filter_on_demands",
"(",
"ava",
",",
"required",
"=",
"None",
",",
"optional",
"=",
"None",
")",
":",
"# Is all what's required there:",
"if",
"required",
"is",
"None",
":",
"required",
"=",
"{",
"}",
"lava",
"=",
"dict",
"(",
"[",
"(",
"k",
".",... | 33.073171 | 0.000716 |
def create_namespaced_config_map(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_config_map # noqa: E501
create a ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | [
"def",
"create_namespaced_config_map",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"retu... | 61.4 | 0.001283 |
def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
R... | [
"def",
"is_storage",
"(",
"url",
",",
"storage",
"=",
"None",
")",
":",
"if",
"storage",
":",
"return",
"True",
"split_url",
"=",
"url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"if",
"len",
"(",
"split_url",
")",
"==",
"2",
"and",
"split_url",
"... | 24.090909 | 0.001815 |
def editColor( self, item, index ):
"""
Prompts the user to pick a new color for the inputed item/column.
:param item | <XColorTreeWidgetItem>
index | <int>
"""
if ( not index ):
return
newcolor = QColorDialog.ge... | [
"def",
"editColor",
"(",
"self",
",",
"item",
",",
"index",
")",
":",
"if",
"(",
"not",
"index",
")",
":",
"return",
"newcolor",
"=",
"QColorDialog",
".",
"getColor",
"(",
"item",
".",
"colorAt",
"(",
"index",
"-",
"1",
")",
",",
"self",
")",
"if",... | 29.380952 | 0.023548 |
def is_admin(self, roles):
"""determine from a list of roles if is ldapcherry administrator"""
for r in roles:
if r in self.admin_roles:
return True
return False | [
"def",
"is_admin",
"(",
"self",
",",
"roles",
")",
":",
"for",
"r",
"in",
"roles",
":",
"if",
"r",
"in",
"self",
".",
"admin_roles",
":",
"return",
"True",
"return",
"False"
] | 34.666667 | 0.00939 |
def reducing(reducer, init=UNSET):
"""Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
... | [
"def",
"reducing",
"(",
"reducer",
",",
"init",
"=",
"UNSET",
")",
":",
"reducer2",
"=",
"reducer",
"def",
"reducing_transducer",
"(",
"reducer",
")",
":",
"return",
"Reducing",
"(",
"reducer",
",",
"reducer2",
",",
"init",
")",
"return",
"reducing_transduce... | 35.714286 | 0.001299 |
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
for name, child in self._children.items():
child.render(**kwargs)
return self._template.render(this=self, kwargs=kwargs) | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"child",
"in",
"self",
".",
"_children",
".",
"items",
"(",
")",
":",
"child",
".",
"render",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_template",
"... | 46.8 | 0.008403 |
def ticket_form_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_forms#create-ticket-forms"
api_path = "/api/v2/ticket_forms.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"ticket_form_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/ticket_forms.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
... | 63 | 0.011765 |
def exportGurobiModel(self, gurobiDriver='gurobi', verbose=False):
"""
Export the model to Gurobi as a gurobipy.Model object.
Args:
gurobiDriver: The name or the path of the Gurobi solver driver.
verbose: Whether should generate verbose output.
Returns:
... | [
"def",
"exportGurobiModel",
"(",
"self",
",",
"gurobiDriver",
"=",
"'gurobi'",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"gurobipy",
"import",
"GRB",
",",
"read",
"from",
"tempfile",
"import",
"mkdtemp",
"from",
"shutil",
"import",
"rmtree",
"from",
"o... | 31.515625 | 0.000962 |
def run_categorical_analysis(table, schema_list, args):
"""Find vocab values for the categorical columns and writes a csv file.
The vocab files are in the from
label1
label2
label3
...
Args:
table: Reference to FederatedTable (if bigquery_table is false) or a
regular Table (otherwise)
sc... | [
"def",
"run_categorical_analysis",
"(",
"table",
",",
"schema_list",
",",
"args",
")",
":",
"import",
"google",
".",
"datalab",
".",
"bigquery",
"as",
"bq",
"# Get list of categorical columns.",
"categorical_columns",
"=",
"[",
"]",
"for",
"col_schema",
"in",
"sch... | 29.409836 | 0.010787 |
def list_all(self, name=None, visibility=None, member_status=None,
owner=None, tag=None, status=None, size_min=None, size_max=None,
sort_key=None, sort_dir=None):
"""
Returns all of the images in one call, rather than in paginated batches.
The same filtering options avail... | [
"def",
"list_all",
"(",
"self",
",",
"name",
"=",
"None",
",",
"visibility",
"=",
"None",
",",
"member_status",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"status",
"=",
"None",
",",
"size_min",
"=",
"None",
",",
"size_max"... | 55.416667 | 0.011834 |
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Mane function
'''
high_out = __salt__['highstate'](data)
return subprocess.check_output(['ponysay', salt.utils.data.decode(high_out)]) | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"high_out",
"=",
"__salt__",
"[",
"'highstate'",
"]",
"(",
"data",
")",
"return",
"subprocess",
".",
"check_output",
"(",
"[",
"'ponysay'",
",",
"salt",
"."... | 36 | 0.00905 |
def from_string(cls, key_pem, is_x509_cert):
"""Construct an RsaVerifier instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
is expected to be an RSA key in PEM forma... | [
"def",
"from_string",
"(",
"cls",
",",
"key_pem",
",",
"is_x509_cert",
")",
":",
"key_pem",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"key_pem",
")",
"if",
"is_x509_cert",
":",
"der",
"=",
"rsa",
".",
"pem",
".",
"load_pem",
"(",
"key_pem",
",",
"'CERTIFIC... | 43.612903 | 0.001447 |
def get_work_items(self, **filters):
'''
Get a work item's information
:param filters: A series of key value pairs to filter on
:return: list of Workitems or None
'''
filter_string = ""
for key, val in filters.iteritems():
filter_string += "%s='%s'" % ... | [
"def",
"get_work_items",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"filter_string",
"=",
"\"\"",
"for",
"key",
",",
"val",
"in",
"filters",
".",
"iteritems",
"(",
")",
":",
"filter_string",
"+=",
"\"%s='%s'\"",
"%",
"(",
"key",
",",
"val",
")",
... | 33.255814 | 0.001359 |
def feature_encoders(self, data_dir):
"""Return a dict for encoding and decoding inference input/output.
Args:
data_dir: data directory
Returns:
A dict of <feature name, TextEncoder>.
"""
encoders = (super(BabiQa, self).feature_encoders(data_dir))
label_encoder = self.get_labels_e... | [
"def",
"feature_encoders",
"(",
"self",
",",
"data_dir",
")",
":",
"encoders",
"=",
"(",
"super",
"(",
"BabiQa",
",",
"self",
")",
".",
"feature_encoders",
"(",
"data_dir",
")",
")",
"label_encoder",
"=",
"self",
".",
"get_labels_encoder",
"(",
"data_dir",
... | 29.714286 | 0.002331 |
def ReadArtifact(self, name):
"""Looks up an artifact with given name from the database."""
try:
artifact = self.artifacts[name]
except KeyError:
raise db.UnknownArtifactError(name)
return artifact.Copy() | [
"def",
"ReadArtifact",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"artifact",
"=",
"self",
".",
"artifacts",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"db",
".",
"UnknownArtifactError",
"(",
"name",
")",
"return",
"artifact",
".",
"Copy"... | 28.25 | 0.012876 |
def __compact_notification_addresses(addresses_):
"""
Input::
{
'default': 'http://domain/notice',
'event1': 'http://domain/notice',
'event2': 'http://domain/notice',
'event3': 'http://domain/notice3',
'event4': 'http://domain/notice3'
... | [
"def",
"__compact_notification_addresses",
"(",
"addresses_",
")",
":",
"result",
"=",
"{",
"}",
"addresses",
"=",
"dict",
"(",
"addresses_",
")",
"default",
"=",
"addresses",
".",
"pop",
"(",
"'default'",
",",
"None",
")",
"for",
"key",
",",
"value",
"in"... | 23.625 | 0.001271 |
def merge_args_and_kwargs(function_abi, args, kwargs):
"""
Takes a list of positional args (``args``) and a dict of keyword args
(``kwargs``) defining values to be passed to a call to the contract function
described by ``function_abi``. Checks to ensure that the correct number of
args were given, n... | [
"def",
"merge_args_and_kwargs",
"(",
"function_abi",
",",
"args",
",",
"kwargs",
")",
":",
"# Ensure the function is being applied to the correct number of args",
"if",
"len",
"(",
"args",
")",
"+",
"len",
"(",
"kwargs",
")",
"!=",
"len",
"(",
"function_abi",
".",
... | 36.318182 | 0.002437 |
def unicode_urlencode(obj, charset='utf-8'):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
... | [
"def",
"unicode_urlencode",
"(",
"obj",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"obj",
"=",
"text_type",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":"... | 39.538462 | 0.001901 |
def scaffold(args):
"""
%prog scaffold scaffold.fasta synteny.blast synteny.sizes synteny.bed
physicalmap.blast physicalmap.sizes physicalmap.bed
As evaluation of scaffolding, visualize external line of evidences:
* Plot synteny to an external genome
* Plot alignments to ph... | [
"def",
"scaffold",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"iter",
"import",
"grouper",
"p",
"=",
"OptionParser",
"(",
"scaffold",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--cutoff\"",
",",
"type",
"=",
"\"int\"",
",",
"de... | 36.571429 | 0.002378 |
def compressBWTPoolProcess(tup):
'''
During compression, each available process will calculate a subportion of the BWT independently using this
function. This process takes the chunk and rewrites it into a given filename using the technique described
in the compressBWT(...) function header
'''
... | [
"def",
"compressBWTPoolProcess",
"(",
"tup",
")",
":",
"#pull the tuple info",
"inputFN",
"=",
"tup",
"[",
"0",
"]",
"startIndex",
"=",
"tup",
"[",
"1",
"]",
"endIndex",
"=",
"tup",
"[",
"2",
"]",
"tempFN",
"=",
"tup",
"[",
"3",
"]",
"#this shouldn't hap... | 31.7 | 0.01049 |
def to_abivars(self):
"""Returns a dictionary with the abinit variables"""
abivars = {
"ecuteps" : self.ecuteps,
"ecutwfn" : self.ecutwfn,
"inclvkb" : self.inclvkb,
"gwpara" : self.gwpara,
"awtr" : self.awtr,
"symchi" ... | [
"def",
"to_abivars",
"(",
"self",
")",
":",
"abivars",
"=",
"{",
"\"ecuteps\"",
":",
"self",
".",
"ecuteps",
",",
"\"ecutwfn\"",
":",
"self",
".",
"ecutwfn",
",",
"\"inclvkb\"",
":",
"self",
".",
"inclvkb",
",",
"\"gwpara\"",
":",
"self",
".",
"gwpara",
... | 32.1 | 0.018154 |
def factorize(self,A):
"""
Factorizes A.
Parameters
----------
A : matrix
For symmetric systems, should contain only lower diagonal part.
"""
A = coo_matrix(A)
self.mumps.set_centralized_assembled_values(A.data)
self.mumps.run(job=2) | [
"def",
"factorize",
"(",
"self",
",",
"A",
")",
":",
"A",
"=",
"coo_matrix",
"(",
"A",
")",
"self",
".",
"mumps",
".",
"set_centralized_assembled_values",
"(",
"A",
".",
"data",
")",
"self",
".",
"mumps",
".",
"run",
"(",
"job",
"=",
"2",
")"
] | 21.857143 | 0.009404 |
def _check_key(key, allow_unicode_keys, key_prefix=b''):
"""Checks key and add key_prefix."""
if allow_unicode_keys:
if isinstance(key, six.text_type):
key = key.encode('utf8')
elif isinstance(key, VALID_STRING_TYPES):
try:
if isinstance(key, bytes):
k... | [
"def",
"_check_key",
"(",
"key",
",",
"allow_unicode_keys",
",",
"key_prefix",
"=",
"b''",
")",
":",
"if",
"allow_unicode_keys",
":",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"text_type",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf8'",... | 37.038462 | 0.001012 |
def next_token(text):
r"""Returns the next possible token, advancing the iterator to the next
position to start processing from.
:param Union[str,iterator,Buffer] text: LaTeX to process
:return str: the token
>>> b = Buffer(r'\textbf{Do play\textit{nice}.} $$\min_w \|w\|_2^2$$')
>>> print(ne... | [
"def",
"next_token",
"(",
"text",
")",
":",
"while",
"text",
".",
"hasNext",
"(",
")",
":",
"for",
"name",
",",
"f",
"in",
"tokenizers",
":",
"current_token",
"=",
"f",
"(",
"text",
")",
"if",
"current_token",
"is",
"not",
"None",
":",
"return",
"cur... | 31.655172 | 0.001057 |
def lib_list():
''' Returns the contents of 'pyglass/lib' as a list of 'lib/*' items for package_data '''
lib_list = []
for (root, dirs, files) in os.walk(Dir.LIB):
for filename in files:
root = root.replace('pyglass/', '')
lib_list.append(join(root, filename))
return lib_list | [
"def",
"lib_list",
"(",
")",
":",
"lib_list",
"=",
"[",
"]",
"for",
"(",
"root",
",",
"dirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"Dir",
".",
"LIB",
")",
":",
"for",
"filename",
"in",
"files",
":",
"root",
"=",
"root",
".",
"replac... | 36.75 | 0.026578 |
def build_object(self, obj):
"""Override django-bakery to skip pages marked exclude_from_static"""
if not obj.exclude_from_static:
super(ShowPage, self).build_object(obj) | [
"def",
"build_object",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"obj",
".",
"exclude_from_static",
":",
"super",
"(",
"ShowPage",
",",
"self",
")",
".",
"build_object",
"(",
"obj",
")"
] | 48.75 | 0.010101 |
def union(union_a, union_b):
"""Union of two vector layers.
Issue https://github.com/inasafe/inasafe/issues/3186
:param union_a: The vector layer for the union.
:type union_a: QgsVectorLayer
:param union_b: The vector layer for the union.
:type union_b: QgsVectorLayer
:return: The clip v... | [
"def",
"union",
"(",
"union_a",
",",
"union_b",
")",
":",
"output_layer_name",
"=",
"union_steps",
"[",
"'output_layer_name'",
"]",
"output_layer_name",
"=",
"output_layer_name",
"%",
"(",
"union_a",
".",
"keywords",
"[",
"'layer_purpose'",
"]",
",",
"union_b",
... | 32.293103 | 0.000518 |
def _is_kvm_hyper():
'''
Returns a bool whether or not this node is a KVM hypervisor
'''
try:
with salt.utils.files.fopen('/proc/modules') as fp_:
if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()):
return False
except IOError:
# No /proc/modul... | [
"def",
"_is_kvm_hyper",
"(",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/modules'",
")",
"as",
"fp_",
":",
"if",
"'kvm_'",
"not",
"in",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
... | 35.583333 | 0.002283 |
def _load_cached_grains(opts, cfn):
'''
Returns the grains cached in cfn, or None if the cache is too old or is
corrupted.
'''
if not os.path.isfile(cfn):
log.debug('Grains cache file does not exist.')
return None
grains_cache_age = int(time.time() - os.path.getmtime(cfn))
i... | [
"def",
"_load_cached_grains",
"(",
"opts",
",",
"cfn",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"cfn",
")",
":",
"log",
".",
"debug",
"(",
"'Grains cache file does not exist.'",
")",
"return",
"None",
"grains_cache_age",
"=",
"int",
"(... | 35.028571 | 0.002381 |
def main():
"""Run the core."""
parser = ArgumentParser()
subs = parser.add_subparsers(dest='cmd')
setup_parser = subs.add_parser('add-user')
setup_parser.add_argument('--user-email', required=True,
help='Email address of the new user')
setup_parser.add_argument('-... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"subs",
"=",
"parser",
".",
"add_subparsers",
"(",
"dest",
"=",
"'cmd'",
")",
"setup_parser",
"=",
"subs",
".",
"add_parser",
"(",
"'add-user'",
")",
"setup_parser",
".",
"add_argumen... | 49.09434 | 0.001507 |
def is_compatible(self, model, version):
""" Check if this flag is compatible with a YubiKey of version 'ver'. """
if not model in self.models:
return False
if self.max_ykver:
return (version >= self.min_ykver and
version <= self.max_ykver)
els... | [
"def",
"is_compatible",
"(",
"self",
",",
"model",
",",
"version",
")",
":",
"if",
"not",
"model",
"in",
"self",
".",
"models",
":",
"return",
"False",
"if",
"self",
".",
"max_ykver",
":",
"return",
"(",
"version",
">=",
"self",
".",
"min_ykver",
"and"... | 39.888889 | 0.010899 |
def regex(pattern, prompt=None, empty=False, flags=0):
"""Prompt a string that matches a regular expression.
Parameters
----------
pattern : str
A regular expression that must be matched.
prompt : str, optional
Use an alternative prompt.
empty : bool, optional
Allow an e... | [
"def",
"regex",
"(",
"pattern",
",",
"prompt",
"=",
"None",
",",
"empty",
"=",
"False",
",",
"flags",
"=",
"0",
")",
":",
"s",
"=",
"_prompt_input",
"(",
"prompt",
")",
"if",
"empty",
"and",
"not",
"s",
":",
"return",
"None",
"else",
":",
"m",
"=... | 25.117647 | 0.001127 |
def open_preview(self):
'''
Try to open a preview of the generated document.
Currently only supported on Windows.
'''
self.log.info('Opening preview...')
if self.opt.pdf:
ext = 'pdf'
else:
ext = 'dvi'
filename = '%s.%s' % (self.proj... | [
"def",
"open_preview",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Opening preview...'",
")",
"if",
"self",
".",
"opt",
".",
"pdf",
":",
"ext",
"=",
"'pdf'",
"else",
":",
"ext",
"=",
"'dvi'",
"filename",
"=",
"'%s.%s'",
"%",
"(",
... | 32.230769 | 0.002317 |
def compute_temperature_features(
meter_data_index,
temperature_data,
heating_balance_points=None,
cooling_balance_points=None,
data_quality=False,
temperature_mean=True,
degree_day_method="daily",
percent_hourly_coverage_per_day=0.5,
percent_hourly_coverage_per_billing_period=0.9,
... | [
"def",
"compute_temperature_features",
"(",
"meter_data_index",
",",
"temperature_data",
",",
"heating_balance_points",
"=",
"None",
",",
"cooling_balance_points",
"=",
"None",
",",
"data_quality",
"=",
"False",
",",
"temperature_mean",
"=",
"True",
",",
"degree_day_met... | 37.724696 | 0.001987 |
def get_host(self, hostname):
""" Returns a Host dict with config options, or None if none exists"""
if hostname in self.get_hosts():
return self.load_ssh_conf().lookup(hostname)
logger.warn('Tried to find host with name {0}, but host not found'.format(hostname))
return None | [
"def",
"get_host",
"(",
"self",
",",
"hostname",
")",
":",
"if",
"hostname",
"in",
"self",
".",
"get_hosts",
"(",
")",
":",
"return",
"self",
".",
"load_ssh_conf",
"(",
")",
".",
"lookup",
"(",
"hostname",
")",
"logger",
".",
"warn",
"(",
"'Tried to fi... | 52.333333 | 0.009404 |
def make_property(prop_defs, prop_name, cls_names=[], hierarchy=[]):
""" Generates a property class from the defintion dictionary
args:
prop_defs: the dictionary defining the property
prop_name: the base name of the property
cls_name: the name of the rdf_class with which the property is... | [
"def",
"make_property",
"(",
"prop_defs",
",",
"prop_name",
",",
"cls_names",
"=",
"[",
"]",
",",
"hierarchy",
"=",
"[",
"]",
")",
":",
"register",
"=",
"False",
"try",
":",
"cls_names",
".",
"remove",
"(",
"'RdfClassBase'",
")",
"except",
"ValueError",
... | 35.804348 | 0.000591 |
def set_weather_from_metar(
metar: typing.Union[Metar.Metar, str],
in_file: typing.Union[str, Path],
out_file: typing.Union[str, Path] = None
) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]:
"""
Applies the weather from a METAR object to a MIZ file
Args:
... | [
"def",
"set_weather_from_metar",
"(",
"metar",
":",
"typing",
".",
"Union",
"[",
"Metar",
".",
"Metar",
",",
"str",
"]",
",",
"in_file",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"out_file",
":",
"typing",
".",
"Union",
"[",
"st... | 30.913043 | 0.001363 |
def get_locals(f):
''' returns a formatted view of the local variables in a frame '''
return pformat({i:f.f_locals[i] for i in f.f_locals if not i.startswith('__')}) | [
"def",
"get_locals",
"(",
"f",
")",
":",
"return",
"pformat",
"(",
"{",
"i",
":",
"f",
".",
"f_locals",
"[",
"i",
"]",
"for",
"i",
"in",
"f",
".",
"f_locals",
"if",
"not",
"i",
".",
"startswith",
"(",
"'__'",
")",
"}",
")"
] | 57 | 0.017341 |
def moment(expr, order, central=False):
"""
Calculate the n-th order moment of the sequence
:param expr:
:param order: moment order, must be an integer
:param central: if central moments are to be computed.
:return:
"""
if not isinstance(order, six.integer_types):
raise ValueErr... | [
"def",
"moment",
"(",
"expr",
",",
"order",
",",
"central",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"order",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"ValueError",
"(",
"'Only integer-ordered moments are supported.'",
")",
"if",
"... | 37.133333 | 0.001751 |
def bytes(num, check_result=False):
"""
Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough
"""
if num <= 0:
raise ValueError("'num' should be > 0")
buf = create_string_buffer(num)
result = libcry... | [
"def",
"bytes",
"(",
"num",
",",
"check_result",
"=",
"False",
")",
":",
"if",
"num",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"'num' should be > 0\"",
")",
"buf",
"=",
"create_string_buffer",
"(",
"num",
")",
"result",
"=",
"libcrypto",
".",
"RAND_by... | 33.428571 | 0.002079 |
def data_discovery(self, region, keywords=None, regex=None, time=None,
boundaries=None, include_quantiles=False):
"""Discover Data Observatory measures. This method returns the full
Data Observatory metadata model for each measure or measures that
match the conditions from... | [
"def",
"data_discovery",
"(",
"self",
",",
"region",
",",
"keywords",
"=",
"None",
",",
"regex",
"=",
"None",
",",
"time",
"=",
"None",
",",
"boundaries",
"=",
"None",
",",
"include_quantiles",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"region",
... | 47.305344 | 0.000237 |
def _parse_directive(self, directive):
"""
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
"""
words = directive.split()
if len(words) == 1 and words[0] not in ('include', 'exclude',
... | [
"def",
"_parse_directive",
"(",
"self",
",",
"directive",
")",
":",
"words",
"=",
"directive",
".",
"split",
"(",
")",
"if",
"len",
"(",
"words",
")",
"==",
"1",
"and",
"words",
"[",
"0",
"]",
"not",
"in",
"(",
"'include'",
",",
"'exclude'",
",",
"... | 38.826087 | 0.001092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.