text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def runScript(self, scriptname, additional_environment=None):
''' Run the specified script from the scripts section of the
module.json file in the directory of this module.
'''
import subprocess
import shlex
command = self.getScript(scriptname)
if command is ... | [
"def",
"runScript",
"(",
"self",
",",
"scriptname",
",",
"additional_environment",
"=",
"None",
")",
":",
"import",
"subprocess",
"import",
"shlex",
"command",
"=",
"self",
".",
"getScript",
"(",
"scriptname",
")",
"if",
"command",
"is",
"None",
":",
"logger... | 32.642857 | 18.5 |
def batch_update(self, values, w=1):
"""
Update the t-digest with an iterable of values. This assumes all points have the
same weight.
"""
for x in values:
self.update(x, w)
self.compress()
return | [
"def",
"batch_update",
"(",
"self",
",",
"values",
",",
"w",
"=",
"1",
")",
":",
"for",
"x",
"in",
"values",
":",
"self",
".",
"update",
"(",
"x",
",",
"w",
")",
"self",
".",
"compress",
"(",
")",
"return"
] | 28.444444 | 15.777778 |
def do_tagg(self, arglist: List[str]):
"""version of creating an html tag using arglist instead of argparser"""
if len(arglist) >= 2:
tag = arglist[0]
content = arglist[1:]
self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content)))
else:
self.pe... | [
"def",
"do_tagg",
"(",
"self",
",",
"arglist",
":",
"List",
"[",
"str",
"]",
")",
":",
"if",
"len",
"(",
"arglist",
")",
">=",
"2",
":",
"tag",
"=",
"arglist",
"[",
"0",
"]",
"content",
"=",
"arglist",
"[",
"1",
":",
"]",
"self",
".",
"poutput"... | 44.375 | 14.125 |
def prepare_new_layer(self, input_layer):
"""Prepare new layer for the output layer.
:param input_layer: Vector layer.
:type input_layer: QgsVectorLayer
:return: New memory layer duplicated from input_layer.
:rtype: QgsVectorLayer
"""
# create memory layer
... | [
"def",
"prepare_new_layer",
"(",
"self",
",",
"input_layer",
")",
":",
"# create memory layer",
"output_layer_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"input_layer",
".",
"name",
"(",
")",
")",
"[",
"0",
"]",
"output_layer_name",
"=",
"unique_filen... | 36.622222 | 14.733333 |
def cylindrical_histogram(data=None, rho_bins="numpy", phi_bins=16, z_bins="numpy", transformed=False, *args, **kwargs):
"""Facade construction function for the CylindricalHistogram.
"""
dropna = kwargs.pop("dropna", True)
data = _prepare_data(data, transformed=transformed, klass=CylindricalHistogram,... | [
"def",
"cylindrical_histogram",
"(",
"data",
"=",
"None",
",",
"rho_bins",
"=",
"\"numpy\"",
",",
"phi_bins",
"=",
"16",
",",
"z_bins",
"=",
"\"numpy\"",
",",
"transformed",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dropna",
"... | 49.6 | 24.8 |
def rapl_read():
""" Read power stats and return dictionary"""
basenames = glob.glob('/sys/class/powercap/intel-rapl:*/')
basenames = sorted(set({x for x in basenames}))
pjoin = os.path.join
ret = list()
for path in basenames:
name = None
try:
name = cat(pjoin(path, ... | [
"def",
"rapl_read",
"(",
")",
":",
"basenames",
"=",
"glob",
".",
"glob",
"(",
"'/sys/class/powercap/intel-rapl:*/'",
")",
"basenames",
"=",
"sorted",
"(",
"set",
"(",
"{",
"x",
"for",
"x",
"in",
"basenames",
"}",
")",
")",
"pjoin",
"=",
"os",
".",
"pa... | 37.958333 | 19.916667 |
def mark_all_read(request):
"""
Mark all messages as read (i.e. delete from inbox) for current logged in user
"""
from .settings import stored_messages_settings
backend = stored_messages_settings.STORAGE_BACKEND()
backend.inbox_purge(request.user)
return Response({"message": "All messages re... | [
"def",
"mark_all_read",
"(",
"request",
")",
":",
"from",
".",
"settings",
"import",
"stored_messages_settings",
"backend",
"=",
"stored_messages_settings",
".",
"STORAGE_BACKEND",
"(",
")",
"backend",
".",
"inbox_purge",
"(",
"request",
".",
"user",
")",
"return"... | 39.75 | 12 |
def get_importable_modules(folder):
"""Find all module files in the given folder that end with '.py' and
don't start with an underscore.
@return module names
@rtype: iterator of string
"""
for fname in os.listdir(folder):
if fname.endswith('.py') and not fname.startswith('_'):
... | [
"def",
"get_importable_modules",
"(",
"folder",
")",
":",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"folder",
")",
":",
"if",
"fname",
".",
"endswith",
"(",
"'.py'",
")",
"and",
"not",
"fname",
".",
"startswith",
"(",
"'_'",
")",
":",
"yield",
... | 36.666667 | 8.333333 |
def publishToRoom(self, roomId, name, data, userList=None):
""" Publish to given room data submitted """
if userList is None:
userList = self.getRoom(roomId)
# Publish data to all room users
logging.debug("%s: broadcasting (name: %s, data: %s, number of users: %s)" % (self._... | [
"def",
"publishToRoom",
"(",
"self",
",",
"roomId",
",",
"name",
",",
"data",
",",
"userList",
"=",
"None",
")",
":",
"if",
"userList",
"is",
"None",
":",
"userList",
"=",
"self",
".",
"getRoom",
"(",
"roomId",
")",
"# Publish data to all room users",
"log... | 43.272727 | 20.909091 |
def ComputeRoot(hashes):
"""
Compute the root hash.
Args:
hashes (list): the list of hashes to build the root from.
Returns:
bytes: the root hash.
"""
if not len(hashes):
raise Exception('Hashes must have length')
if len(hashe... | [
"def",
"ComputeRoot",
"(",
"hashes",
")",
":",
"if",
"not",
"len",
"(",
"hashes",
")",
":",
"raise",
"Exception",
"(",
"'Hashes must have length'",
")",
"if",
"len",
"(",
"hashes",
")",
"==",
"1",
":",
"return",
"hashes",
"[",
"0",
"]",
"tree",
"=",
... | 23.882353 | 17.764706 |
def _get_by(key, val, l):
"""
Out of list *l* return all elements that have *key=val*
This comes in handy when you are working with aggregated/bucketed queries
"""
return [x for x in l if _check_value_recursively(key, val, x)] | [
"def",
"_get_by",
"(",
"key",
",",
"val",
",",
"l",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"l",
"if",
"_check_value_recursively",
"(",
"key",
",",
"val",
",",
"x",
")",
"]"
] | 40.166667 | 16.166667 |
def __request(self, method, url, request_args, headers=None, stream=False):
"""__request.
make the actual request. This method is called by the
request method in case of 'regular' API-calls. Or indirectly by
the__stream_request method if it concerns a 'streaming' call.
"""
... | [
"def",
"__request",
"(",
"self",
",",
"method",
",",
"url",
",",
"request_args",
",",
"headers",
"=",
"None",
",",
"stream",
"=",
"False",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
".",
"client",
",",
"method",
")",
"headers",
"=",
"headers",
"i... | 41 | 16.185185 |
def build_summary_table(summary, idx, is_fragment_root, indent_level, output):
"""Direct translation of Coordinator::PrintExecSummary() to recursively
build a list of rows of summary statistics, one per exec node
summary: the TExecSummary object that contains all the summary data
idx: the index of the... | [
"def",
"build_summary_table",
"(",
"summary",
",",
"idx",
",",
"is_fragment_root",
",",
"indent_level",
",",
"output",
")",
":",
"# pylint: disable=too-many-locals",
"attrs",
"=",
"[",
"\"latency_ns\"",
",",
"\"cpu_time_ns\"",
",",
"\"cardinality\"",
",",
"\"memory_us... | 37.435897 | 20.358974 |
def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
"""Return a tar header as a string of 512 byte blocks.
"""
info = self.get_info()
if format == USTAR_FORMAT:
return self.create_ustar_header(info, encoding, errors)
elif format == GN... | [
"def",
"tobuf",
"(",
"self",
",",
"format",
"=",
"DEFAULT_FORMAT",
",",
"encoding",
"=",
"ENCODING",
",",
"errors",
"=",
"\"surrogateescape\"",
")",
":",
"info",
"=",
"self",
".",
"get_info",
"(",
")",
"if",
"format",
"==",
"USTAR_FORMAT",
":",
"return",
... | 41.307692 | 16.461538 |
def get_contributors(gh, repo_id):
"""Get list of contributors to a repository."""
try:
# FIXME: Use `github3.Repository.contributors` to get this information
contrib_url = gh.repository_with_id(repo_id).contributors_url
r = requests.get(contrib_url)
if r.status_code == 200:
... | [
"def",
"get_contributors",
"(",
"gh",
",",
"repo_id",
")",
":",
"try",
":",
"# FIXME: Use `github3.Repository.contributors` to get this information",
"contrib_url",
"=",
"gh",
".",
"repository_with_id",
"(",
"repo_id",
")",
".",
"contributors_url",
"r",
"=",
"requests",... | 39.206897 | 19.172414 |
def put(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to PUT"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='PUT', **overrides) | [
"def",
"put",
"(",
"self",
",",
"urls",
"=",
"None",
",",
"*",
"*",
"overrides",
")",
":",
"if",
"urls",
"is",
"not",
"None",
":",
"overrides",
"[",
"'urls'",
"]",
"=",
"urls",
"return",
"self",
".",
"where",
"(",
"accept",
"=",
"'PUT'",
",",
"*"... | 41.2 | 6 |
def get_me(self) -> "pyrogram.User":
"""A simple method for testing your authorization. Requires no parameters.
Returns:
Basic information about the user or bot in form of a :obj:`User` object
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error... | [
"def",
"get_me",
"(",
"self",
")",
"->",
"\"pyrogram.User\"",
":",
"return",
"pyrogram",
".",
"User",
".",
"_parse",
"(",
"self",
",",
"self",
".",
"send",
"(",
"functions",
".",
"users",
".",
"GetFullUser",
"(",
"id",
"=",
"types",
".",
"InputPeerSelf",... | 31.294118 | 20.411765 |
def timezone(name, extended=True): # type: (Union[str, int]) -> _Timezone
"""
Return a Timezone instance given its name.
"""
if isinstance(name, int):
return fixed_timezone(name)
if name.lower() == "utc":
return UTC
if name in _tz_cache:
return _tz_cache[name]
tz ... | [
"def",
"timezone",
"(",
"name",
",",
"extended",
"=",
"True",
")",
":",
"# type: (Union[str, int]) -> _Timezone",
"if",
"isinstance",
"(",
"name",
",",
"int",
")",
":",
"return",
"fixed_timezone",
"(",
"name",
")",
"if",
"name",
".",
"lower",
"(",
")",
"==... | 22.352941 | 18.823529 |
def gettrace(self, burn=0, thin=1, chain=-1, slicing=None):
"""Return the trace (last by default).
:Parameters:
burn : integer
The number of transient steps to skip.
thin : integer
Keep one in thin.
chain : integer
The index of the chain to fetch. I... | [
"def",
"gettrace",
"(",
"self",
",",
"burn",
"=",
"0",
",",
"thin",
"=",
"1",
",",
"chain",
"=",
"-",
"1",
",",
"slicing",
"=",
"None",
")",
":",
"# XXX: handle chain == None case properly",
"if",
"chain",
"is",
"None",
":",
"chain",
"=",
"-",
"1",
"... | 31.37931 | 19.275862 |
def create(self):
"""
Creates a new record for a domain.
Args:
type (str): The type of the DNS record (e.g. A, CNAME, TXT).
name (str): The host name, alias, or service being defined by the
record.
data (int): Variable data depending on record... | [
"def",
"create",
"(",
"self",
")",
":",
"input_params",
"=",
"{",
"\"type\"",
":",
"self",
".",
"type",
",",
"\"data\"",
":",
"self",
".",
"data",
",",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"priority\"",
":",
"self",
".",
"priority",
",",
"\"p... | 34.810811 | 18.27027 |
def reset(self, source):
""" Reset scanner's state.
:param source: Source for parsing
"""
self.tokens = []
self.source = source
self.pos = 0 | [
"def",
"reset",
"(",
"self",
",",
"source",
")",
":",
"self",
".",
"tokens",
"=",
"[",
"]",
"self",
".",
"source",
"=",
"source",
"self",
".",
"pos",
"=",
"0"
] | 20.222222 | 16.111111 |
def make(directory):
"""Makes a RAS Machine directory"""
if os.path.exists(directory):
if os.path.isdir(directory):
click.echo('Directory already exists')
else:
click.echo('Path exists and is not a directory')
sys.exit()
os.makedirs(directory)
os.mkdir(o... | [
"def",
"make",
"(",
"directory",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"click",
".",
"echo",
"(",
"'Directory already exists'",
")",
"else",
":... | 31.076923 | 17.923077 |
def maxind_numba(block):
""" filter for indels """
## remove terminal edges
inds = 0
for row in xrange(block.shape[0]):
where = np.where(block[row] != 45)[0]
if len(where) == 0:
obs = 100
else:
left = np.min(where)
right = np.max(where)
... | [
"def",
"maxind_numba",
"(",
"block",
")",
":",
"## remove terminal edges",
"inds",
"=",
"0",
"for",
"row",
"in",
"xrange",
"(",
"block",
".",
"shape",
"[",
"0",
"]",
")",
":",
"where",
"=",
"np",
".",
"where",
"(",
"block",
"[",
"row",
"]",
"!=",
"... | 27.666667 | 14.133333 |
def disable(self, msgid, scope="package", line=None, ignore_unknown=False):
"""don't output message of the given id"""
self._set_msg_status(
msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line) | [
"def",
"disable",
"(",
"self",
",",
"msgid",
",",
"scope",
"=",
"\"package\"",
",",
"line",
"=",
"None",
",",
"ignore_unknown",
"=",
"False",
")",
":",
"self",
".",
"_set_msg_status",
"(",
"msgid",
",",
"enable",
"=",
"False",
",",
"scope",
"=",
"scope... | 50.333333 | 22.666667 |
def get(self, *args, **kwargs):
"""
This renders the form or, if needed, does the http redirects.
"""
step_url = kwargs.get('step', None)
if step_url is None:
if 'reset' in self.request.GET:
self.storage.reset()
self.storage.current_ste... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"step_url",
"=",
"kwargs",
".",
"get",
"(",
"'step'",
",",
"None",
")",
"if",
"step_url",
"is",
"None",
":",
"if",
"'reset'",
"in",
"self",
".",
"request",
".",
"GET"... | 40.76087 | 15.5 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
Implement equation 1, page 20.
"""
# compute median PGA on rock, ... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# compute median PGA on rock, needed to compute non-linear site",
"# amplification",
"C_pga",
"=",
"self",
".",
"COEFFS",
"[",
"PGA",
"(",... | 37.956522 | 21.695652 |
def get_object(self, queryset=None):
""" get privacy settings of current user """
try:
obj = self.get_queryset()
except self.model.DoesNotExist:
raise Http404()
self.check_object_permissions(self.request, obj)
return obj | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"try",
":",
"obj",
"=",
"self",
".",
"get_queryset",
"(",
")",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
")",
"self",
".",
"check_object_... | 34.625 | 10.875 |
def add_to_queue(self, series):
"""Add a series to the queue
@param crunchyroll.models.Series series
@return bool
"""
result = self._android_api.add_to_queue(series_id=series.series_id)
return result | [
"def",
"add_to_queue",
"(",
"self",
",",
"series",
")",
":",
"result",
"=",
"self",
".",
"_android_api",
".",
"add_to_queue",
"(",
"series_id",
"=",
"series",
".",
"series_id",
")",
"return",
"result"
] | 30.125 | 16.25 |
def _warcprox_opts(self, args):
'''
Takes args as produced by the argument parser built by
_build_arg_parser and builds warcprox arguments object suitable to pass
to warcprox.main.init_controller. Copies some arguments, renames some,
populates some with defaults appropriate for b... | [
"def",
"_warcprox_opts",
"(",
"self",
",",
"args",
")",
":",
"warcprox_opts",
"=",
"warcprox",
".",
"Options",
"(",
")",
"warcprox_opts",
".",
"address",
"=",
"'localhost'",
"# let the OS choose an available port; discover it later using",
"# sock.getsockname()[1]",
"warc... | 45.59375 | 12.78125 |
def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | [
"def",
"parse_relation",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCRelation",
":",
"rel",
"=",
"BioCRelation",
"(",
")",
"rel",
".",
"id",
"=",
"obj",
"[",
"'id'",
"]",
"rel",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"for",
"node",
"in",
"ob... | 36 | 13 |
def create_stash(self, payload, path=None):
"""
Create a stash. (JSON document)
"""
if path:
self._request('POST', '/stashes/{}'.format(path),
json=payload)
else:
self._request('POST', '/stashes', json=payload)
return True | [
"def",
"create_stash",
"(",
"self",
",",
"payload",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
":",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/stashes/{}'",
".",
"format",
"(",
"path",
")",
",",
"json",
"=",
"payload",
")",
"else",
":",
... | 31.1 | 11.7 |
def qsnorm(p):
"""
rational approximation for x where q(x)=d, q being the cumulative
normal distribution function. taken from Abramowitz & Stegun p. 933
|error(x)| < 4.5*10**-4
"""
d = p
if d < 0. or d > 1.:
print('d not in (1,1) ')
sys.exit()
x = 0.
if (d - 0.5) > 0:... | [
"def",
"qsnorm",
"(",
"p",
")",
":",
"d",
"=",
"p",
"if",
"d",
"<",
"0.",
"or",
"d",
">",
"1.",
":",
"print",
"(",
"'d not in (1,1) '",
")",
"sys",
".",
"exit",
"(",
")",
"x",
"=",
"0.",
"if",
"(",
"d",
"-",
"0.5",
")",
">",
"0",
":",
"d"... | 28.095238 | 20.380952 |
def list_image(root, recursive, exts):
"""Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path
... | [
"def",
"list_image",
"(",
"root",
",",
"recursive",
",",
"exts",
")",
":",
"i",
"=",
"0",
"if",
"recursive",
":",
"cat",
"=",
"{",
"}",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
",",
"followlinks",
"=",
"True... | 34.638889 | 17.75 |
def set(self, val):
"""Set the value"""
import time
now = time.time()
expected_value = []
new_val = {}
new_val['timestamp'] = now
if self._value != None:
new_val['last_value'] = self._value
expected_value = ['current_value', str(self._value... | [
"def",
"set",
"(",
"self",
",",
"val",
")",
":",
"import",
"time",
"now",
"=",
"time",
".",
"time",
"(",
")",
"expected_value",
"=",
"[",
"]",
"new_val",
"=",
"{",
"}",
"new_val",
"[",
"'timestamp'",
"]",
"=",
"now",
"if",
"self",
".",
"_value",
... | 34.473684 | 15.263158 |
def bootstrap_repl(which_ns: str) -> types.ModuleType:
"""Bootstrap the REPL with a few useful vars and returned the
bootstrapped module so it's functions can be used by the REPL
command."""
repl_ns = runtime.Namespace.get_or_create(sym.symbol("basilisp.repl"))
ns = runtime.Namespace.get_or_create(s... | [
"def",
"bootstrap_repl",
"(",
"which_ns",
":",
"str",
")",
"->",
"types",
".",
"ModuleType",
":",
"repl_ns",
"=",
"runtime",
".",
"Namespace",
".",
"get_or_create",
"(",
"sym",
".",
"symbol",
"(",
"\"basilisp.repl\"",
")",
")",
"ns",
"=",
"runtime",
".",
... | 49.4 | 16 |
def parse_options(self, kwargs):
"""Validate the provided kwargs and return options as json string."""
kwargs = {camelize(key): value for key, value in kwargs.items()}
for key in kwargs.keys():
assert key in self.valid_options, (
'The option {} is not in the available... | [
"def",
"parse_options",
"(",
"self",
",",
"kwargs",
")",
":",
"kwargs",
"=",
"{",
"camelize",
"(",
"key",
")",
":",
"value",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"for",
"key",
"in",
"kwargs",
".",
"keys",
"(",
... | 48.384615 | 19.076923 |
def get_default_jprops_parsers(parser_finder: ParserFinder, conversion_finder: ConversionFinder) -> List[AnyParser]:
"""
Utility method to return the default parsers able to parse a dictionary from a properties file.
:return:
"""
return [SingleFileParserFunction(parser_function=read_dict_from_proper... | [
"def",
"get_default_jprops_parsers",
"(",
"parser_finder",
":",
"ParserFinder",
",",
"conversion_finder",
":",
"ConversionFinder",
")",
"->",
"List",
"[",
"AnyParser",
"]",
":",
"return",
"[",
"SingleFileParserFunction",
"(",
"parser_function",
"=",
"read_dict_from_prop... | 62.466667 | 34.733333 |
def copen(filepath, flag='r', encoding=None):
"""
FIXME: How to test this ?
>>> c = copen(__file__)
>>> c is not None
True
"""
if encoding is None:
encoding = locale.getdefaultlocale()[1]
return codecs.open(filepath, flag, encoding) | [
"def",
"copen",
"(",
"filepath",
",",
"flag",
"=",
"'r'",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"return",
"codecs",
".",
"open",
"(",
... | 20.230769 | 17.769231 |
def venue_stocks(self):
"""List the stocks available for trading on the venue.
https://starfighter.readme.io/docs/list-stocks-on-venue
"""
url = urljoin(self.base_url, 'venues/{0}/stocks'.format(self.venue))
return self.session.get(url).json() | [
"def",
"venue_stocks",
"(",
"self",
")",
":",
"url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"'venues/{0}/stocks'",
".",
"format",
"(",
"self",
".",
"venue",
")",
")",
"return",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
".",
"js... | 39.714286 | 17 |
def p_subidentifiers_defval(self, p):
"""subidentifiers_defval : subidentifiers_defval subidentifier_defval
| subidentifier_defval"""
n = len(p)
if n == 3:
p[0] = ('subidentifiers_defval', p[1][1] + [p[2]])
elif n == 2:
p[0] = ('su... | [
"def",
"p_subidentifiers_defval",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'subidentifiers_defval'",
",",
"p",
"[",
"1",
"]",
"[",
"1",
"]",
"+",
"[",
"p",
"[",... | 42.75 | 12.625 |
def add_update_topology_db(self, **params):
"""Add or update an entry to the topology DB. """
topo_dict = params.get('columns')
session = db.get_session()
host = topo_dict.get('host')
protocol_interface = topo_dict.get('protocol_interface')
with session.begin(subtransacti... | [
"def",
"add_update_topology_db",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"topo_dict",
"=",
"params",
".",
"get",
"(",
"'columns'",
")",
"session",
"=",
"db",
".",
"get_session",
"(",
")",
"host",
"=",
"topo_dict",
".",
"get",
"(",
"'host'",
")"... | 55.95 | 18.025 |
def start(self):
"""
Start the installation wizard
"""
self.log.debug('Starting the installation process')
self.browser.open(self.url)
self.system_check() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Starting the installation process'",
")",
"self",
".",
"browser",
".",
"open",
"(",
"self",
".",
"url",
")",
"self",
".",
"system_check",
"(",
")"
] | 21.777778 | 16 |
def _validate_no_rels(param, rels):
""" Ensure the sortable field is not on a relationship """
if param.field in rels:
raise InvalidQueryParams(**{
'detail': 'The sort query param value of "%s" is not '
'supported. Sorting on relationships is not '
... | [
"def",
"_validate_no_rels",
"(",
"param",
",",
"rels",
")",
":",
"if",
"param",
".",
"field",
"in",
"rels",
":",
"raise",
"InvalidQueryParams",
"(",
"*",
"*",
"{",
"'detail'",
":",
"'The sort query param value of \"%s\" is not '",
"'supported. Sorting on relationships... | 38.363636 | 17.272727 |
def get_filtered_devices(
self, model_name, device_types="upnp:rootdevice", timeout=2
):
"""
returns a dict of devices that contain the given model name
"""
# get list of all UPNP devices in the network
upnp_devices = self.discover_upnp_devices(st=device_types)
... | [
"def",
"get_filtered_devices",
"(",
"self",
",",
"model_name",
",",
"device_types",
"=",
"\"upnp:rootdevice\"",
",",
"timeout",
"=",
"2",
")",
":",
"# get list of all UPNP devices in the network",
"upnp_devices",
"=",
"self",
".",
"discover_upnp_devices",
"(",
"st",
"... | 40.453125 | 19.515625 |
def managed_wrapper_class_factory(zos_obj):
"""Creates and returns a wrapper class of a ZOS object, exposing the ZOS objects
methods and propertis, and patching custom specialized attributes
@param zos_obj: ZOS API Python COM object
"""
cls_name = repr(zos_obj).split()[0].split('.')[-1]
disp... | [
"def",
"managed_wrapper_class_factory",
"(",
"zos_obj",
")",
":",
"cls_name",
"=",
"repr",
"(",
"zos_obj",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"dispatch_attr",
"=",
"'_'",
"+",
"cls_name",
".... | 41.769231 | 24.602564 |
def _max_lengths():
""" The length of the largest magic string + its offset"""
max_header_length = max([len(x.byte_match) + x.offset
for x in magic_header_array])
max_footer_length = max([len(x.byte_match) + abs(x.offset)
for x in magic_footer_array]... | [
"def",
"_max_lengths",
"(",
")",
":",
"max_header_length",
"=",
"max",
"(",
"[",
"len",
"(",
"x",
".",
"byte_match",
")",
"+",
"x",
".",
"offset",
"for",
"x",
"in",
"magic_header_array",
"]",
")",
"max_footer_length",
"=",
"max",
"(",
"[",
"len",
"(",
... | 51.857143 | 14.714286 |
def _serializeParamsUniq_eval(parentUnit, obj, isDeclaration, priv):
"""
Decide to serialize only objs with uniq parameters and class
:param priv: private data for this function
({frozen_params: obj})
:return: tuple (do serialize this object, next priv)
"""
params = paramsToValTuple(p... | [
"def",
"_serializeParamsUniq_eval",
"(",
"parentUnit",
",",
"obj",
",",
"isDeclaration",
",",
"priv",
")",
":",
"params",
"=",
"paramsToValTuple",
"(",
"parentUnit",
")",
"if",
"priv",
"is",
"None",
":",
"priv",
"=",
"{",
"}",
"if",
"isDeclaration",
":",
"... | 24.730769 | 20.269231 |
def on_message(self, message):
"""Message from the backend has been received.
:param message: Message string received.
"""
work_unit = SelenolMessage(message)
request_id = work_unit.request_id
if message['reason'] == ['selenol', 'request']:
try:
... | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"work_unit",
"=",
"SelenolMessage",
"(",
"message",
")",
"request_id",
"=",
"work_unit",
".",
"request_id",
"if",
"message",
"[",
"'reason'",
"]",
"==",
"[",
"'selenol'",
",",
"'request'",
"]",
":... | 34.837838 | 11.945946 |
def __parse(self) -> object:
"""Selects the appropriate method to decode next bencode element and returns the result."""
char = self.data[self.idx: self.idx + 1]
if char in [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0']:
str_len = int(self.__read_to(b':'))
r... | [
"def",
"__parse",
"(",
"self",
")",
"->",
"object",
":",
"char",
"=",
"self",
".",
"data",
"[",
"self",
".",
"idx",
":",
"self",
".",
"idx",
"+",
"1",
"]",
"if",
"char",
"in",
"[",
"b'1'",
",",
"b'2'",
",",
"b'3'",
",",
"b'4'",
",",
"b'5'",
"... | 47.611111 | 17.222222 |
def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_na... | [
"def",
"get_matching_service_template_file",
"(",
"service_name",
",",
"template_files",
")",
":",
"# If this is a subservice, use the parent service's template",
"service_name",
"=",
"service_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"service_name",
"in"... | 44.1 | 16.1 |
def resource_property(klass, name, **kwargs):
"""Builds a resource object property."""
klass.PROPERTIES[name] = kwargs
def getter(self):
return getattr(self, '_%s' % name, kwargs.get('default', None))
if kwargs.get('readonly', False):
setattr(klass, name, property(getter))
else:
... | [
"def",
"resource_property",
"(",
"klass",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"klass",
".",
"PROPERTIES",
"[",
"name",
"]",
"=",
"kwargs",
"def",
"getter",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"'_%s'",
"%",
"name"... | 33.846154 | 16 |
def get_parameter_value(self, parameter, from_cache=True, timeout=10):
"""
Retrieve the current value of the specified parameter.
:param str parameter: Either a fully-qualified XTCE name or an alias in the
format ``NAMESPACE/NAME``.
:param bool from_cache: ... | [
"def",
"get_parameter_value",
"(",
"self",
",",
"parameter",
",",
"from_cache",
"=",
"True",
",",
"timeout",
"=",
"10",
")",
":",
"params",
"=",
"{",
"'fromCache'",
":",
"from_cache",
",",
"'timeout'",
":",
"int",
"(",
"timeout",
"*",
"1000",
")",
",",
... | 47.033333 | 20.1 |
def set_skips(self, skips):
"""Set the line skips."""
skips.sort()
internal_assert(lambda: len(set(skips)) == len(skips), "duplicate line skip(s) in skips", skips)
self.skips = skips | [
"def",
"set_skips",
"(",
"self",
",",
"skips",
")",
":",
"skips",
".",
"sort",
"(",
")",
"internal_assert",
"(",
"lambda",
":",
"len",
"(",
"set",
"(",
"skips",
")",
")",
"==",
"len",
"(",
"skips",
")",
",",
"\"duplicate line skip(s) in skips\"",
",",
... | 42 | 22.2 |
def del_cells(self, name):
"""Implementation of cells deletion
``del space.name`` where name is a cells, or
``del space.cells['name']``
"""
if name in self.cells:
cells = self.cells[name]
self.cells.del_item(name)
self.inherit()
se... | [
"def",
"del_cells",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"cells",
":",
"cells",
"=",
"self",
".",
"cells",
"[",
"name",
"]",
"self",
".",
"cells",
".",
"del_item",
"(",
"name",
")",
"self",
".",
"inherit",
"(",
")"... | 29.2 | 15.9 |
def get_port_profile_for_intf_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
output = ET.SubElement(get_port_profile_for_intf,... | [
"def",
"get_port_profile_for_intf_output_has_more",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_profile_for_intf",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_profile_for_intf\"",
")",
"con... | 42.5 | 14.416667 |
def is_token_expired(self, margin=None):
"""Determine if the token is expired.
:returns:
``True`` if the token is expired, ``False`` if not, and
``None`` if there is no token set.
:param margin:
A security time margin in seconds before real expiration.
... | [
"def",
"is_token_expired",
"(",
"self",
",",
"margin",
"=",
"None",
")",
":",
"if",
"self",
".",
"token",
"is",
"None",
":",
"return",
"None",
"return",
"not",
"utils",
".",
"is_token_valid",
"(",
"self",
".",
"token",
",",
"margin",
")"
] | 34.833333 | 19.944444 |
def get_alpha_or_number(number, template):
"""Returns an Alphanumber that represents the number passed in, expressed
as defined in the template. Otherwise, returns the number
"""
match = re.match(r".*\{alpha:(\d+a\d+d)\}$", template.strip())
if match and match.groups():
format = match.groups... | [
"def",
"get_alpha_or_number",
"(",
"number",
",",
"template",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\".*\\{alpha:(\\d+a\\d+d)\\}$\"",
",",
"template",
".",
"strip",
"(",
")",
")",
"if",
"match",
"and",
"match",
".",
"groups",
"(",
")",
":",
... | 41.666667 | 9.666667 |
def _get_mid_and_update_msg(self, msg, use_mid):
"""Get message ID for current request and assign to msg.mid if needed.
Parameters
----------
msg : katcp.Message ?request message
use_mid : bool or None
If msg.mid is None, a new message ID will be created. msg.mid will b... | [
"def",
"_get_mid_and_update_msg",
"(",
"self",
",",
"msg",
",",
"use_mid",
")",
":",
"if",
"use_mid",
"is",
"None",
":",
"use_mid",
"=",
"self",
".",
"_server_supports_ids",
"if",
"msg",
".",
"mid",
"is",
"None",
":",
"mid",
"=",
"self",
".",
"_next_id",... | 32.7 | 20.733333 |
def get_default_object_parsers(parser_finder: ParserFinder, conversion_finder: ConversionFinder) -> List[AnyParser]:
"""
Utility method to return the default parsers able to parse an object from a file.
Note that MultifileObjectParser is not provided in this list, as it is already added in a hardcoded way i... | [
"def",
"get_default_object_parsers",
"(",
"parser_finder",
":",
"ParserFinder",
",",
"conversion_finder",
":",
"ConversionFinder",
")",
"->",
"List",
"[",
"AnyParser",
"]",
":",
"return",
"[",
"SingleFileParserFunction",
"(",
"parser_function",
"=",
"read_object_from_pi... | 53.307692 | 30.846154 |
def call_script(self, key, tmp_key, key_type, start, end, exclude, *args):
"""Call the lua scripts with given keys and args
Parameters
-----------
key: str
The key of the index sorted-set
tmp_key: str
The final temporary key where to store the filtered pr... | [
"def",
"call_script",
"(",
"self",
",",
"key",
",",
"tmp_key",
",",
"key_type",
",",
"start",
",",
"end",
",",
"exclude",
",",
"*",
"args",
")",
":",
"self",
".",
"model",
".",
"database",
".",
"call_script",
"(",
"# be sure to use the script dict at the cla... | 39.655172 | 22.310345 |
def get_leaf_children(gos_user, go2obj_arg):
"""Find all the GO descendants under all user GO IDs. Return leaf-level GO IDs."""
childgoid2obj = {}
for goid_usr in gos_user:
goobj_usr = go2obj_arg[goid_usr]
fill_childgoid2obj(childgoid2obj, goobj_usr)
return set(go for go, o in childgoid2... | [
"def",
"get_leaf_children",
"(",
"gos_user",
",",
"go2obj_arg",
")",
":",
"childgoid2obj",
"=",
"{",
"}",
"for",
"goid_usr",
"in",
"gos_user",
":",
"goobj_usr",
"=",
"go2obj_arg",
"[",
"goid_usr",
"]",
"fill_childgoid2obj",
"(",
"childgoid2obj",
",",
"goobj_usr"... | 49.142857 | 10.857143 |
def unitary_operator(state_vector):
"""
Uses QR factorization to create a unitary operator
that can encode an arbitrary normalized vector into
the wavefunction of a quantum state.
Assumes that the state of the input qubits is to be expressed as
.. math::
(1, 0, \\ldots, 0)^T
:par... | [
"def",
"unitary_operator",
"(",
"state_vector",
")",
":",
"if",
"not",
"np",
".",
"allclose",
"(",
"[",
"np",
".",
"linalg",
".",
"norm",
"(",
"state_vector",
")",
"]",
",",
"[",
"1",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Vector must be normalize... | 30.891892 | 21.054054 |
def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs):
"""Fetch the target and pass through to pandas.read_csv
Don't provide the first argument of read_csv(); it is supplied internally.
"""
import pandas
t = self.resolved_url.get_resource().get_target()
k... | [
"def",
"read_csv",
"(",
"self",
",",
"dtype",
"=",
"False",
",",
"parse_dates",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
"t",
"=",
"self",
".",
"resolved_url",
".",
"get_resource",
"(",
")",
".",
"get_targ... | 33 | 27.153846 |
def _compute_needed_metrics(self, instance, available_metrics):
""" Compare the available metrics for one MOR we have computed and intersect them
with the set of metrics we want to report
"""
i_key = self._instance_key(instance)
if self.in_compatibility_mode(instance):
... | [
"def",
"_compute_needed_metrics",
"(",
"self",
",",
"instance",
",",
"available_metrics",
")",
":",
"i_key",
"=",
"self",
".",
"_instance_key",
"(",
"instance",
")",
"if",
"self",
".",
"in_compatibility_mode",
"(",
"instance",
")",
":",
"if",
"instance",
".",
... | 48.966667 | 22.033333 |
def rover_lat_accel(VFR_HUD, SERVO_OUTPUT_RAW):
'''return lateral acceleration in m/s/s'''
speed = VFR_HUD.groundspeed
yaw_rate = rover_yaw_rate(VFR_HUD, SERVO_OUTPUT_RAW)
accel = radians(yaw_rate) * speed
return accel | [
"def",
"rover_lat_accel",
"(",
"VFR_HUD",
",",
"SERVO_OUTPUT_RAW",
")",
":",
"speed",
"=",
"VFR_HUD",
".",
"groundspeed",
"yaw_rate",
"=",
"rover_yaw_rate",
"(",
"VFR_HUD",
",",
"SERVO_OUTPUT_RAW",
")",
"accel",
"=",
"radians",
"(",
"yaw_rate",
")",
"*",
"spee... | 38.833333 | 10.833333 |
def setdefault(pb_or_dict, key, value):
"""Set the key on the object to the value if the current value is falsy.
Because protobuf Messages do not distinguish between unset values and
falsy ones particularly well, this method treats any falsy value
(e.g. 0, empty list) as a target to be overwritten, on ... | [
"def",
"setdefault",
"(",
"pb_or_dict",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"get",
"(",
"pb_or_dict",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"set",
"(",
"pb_or_dict",
",",
"key",
",",
"value",
")"
] | 36.947368 | 20.789474 |
def get_version(self, extra=None):
"""
This will return a string that can be used as a prefix
for django's cache key. Something like key.1 or key.1.2
If a version was not found '1' will be stored and returned as
the number for that key.
If extra is given a version will ... | [
"def",
"get_version",
"(",
"self",
",",
"extra",
"=",
"None",
")",
":",
"if",
"extra",
":",
"key",
"=",
"self",
".",
"_get_extra_key",
"(",
"extra",
")",
"else",
":",
"key",
"=",
"self",
".",
"key",
"v",
"=",
"self",
".",
"_get_cache",
"(",
"key",
... | 29.791667 | 20.875 |
def render_to_string(template, extra=None):
"""
Renders the given template to a string.
"""
from jinja2 import Template
extra = extra or {}
final_fqfn = find_template(template)
assert final_fqfn, 'Template not found: %s' % template
template_content = open(final_fqfn, 'r').read()
t = ... | [
"def",
"render_to_string",
"(",
"template",
",",
"extra",
"=",
"None",
")",
":",
"from",
"jinja2",
"import",
"Template",
"extra",
"=",
"extra",
"or",
"{",
"}",
"final_fqfn",
"=",
"find_template",
"(",
"template",
")",
"assert",
"final_fqfn",
",",
"'Template ... | 31.555556 | 11.333333 |
async def lookup_session(self, topic_name):
"""
Attempts to find the session id for a given topic
http://crossbar.io/docs/Subscription-Meta-Events-and-Procedures/
"""
res = await self.call("wamp.subscription.lookup", topic_name)
self.log.info(res) | [
"async",
"def",
"lookup_session",
"(",
"self",
",",
"topic_name",
")",
":",
"res",
"=",
"await",
"self",
".",
"call",
"(",
"\"wamp.subscription.lookup\"",
",",
"topic_name",
")",
"self",
".",
"log",
".",
"info",
"(",
"res",
")"
] | 36.125 | 16.875 |
def decrypt_file(filename, set_env=True, override_env=False):
"""
Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping the key names to
encrypted secrets. This encrypted file can be created using `credkeep.encrypt_file` or the commandline utility.
:param filenam... | [
"def",
"decrypt_file",
"(",
"filename",
",",
"set_env",
"=",
"True",
",",
"override_env",
"=",
"False",
")",
":",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"filename",
")",
")",
"results",
"=",
"{",
"}",
"for",
"key",
",",
"v",
"in",
"dat... | 39.68 | 26.8 |
def _clean_pivot_attributes(self, model):
"""
Get the pivot attributes from a model.
:type model: eloquent.Model
"""
values = {}
delete_keys = []
for key, value in model.get_attributes().items():
if key.find('pivot_') == 0:
values[key... | [
"def",
"_clean_pivot_attributes",
"(",
"self",
",",
"model",
")",
":",
"values",
"=",
"{",
"}",
"delete_keys",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"model",
".",
"get_attributes",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
... | 23.368421 | 16.105263 |
def intermediates(self):
"""
A list of asn1crypto.x509.Certificate objects that were presented as
intermediates by the server
"""
if self._session_context is None:
self._raise_closed()
if self._certificate is None:
self._read_certificates()
... | [
"def",
"intermediates",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session_context",
"is",
"None",
":",
"self",
".",
"_raise_closed",
"(",
")",
"if",
"self",
".",
"_certificate",
"is",
"None",
":",
"self",
".",
"_read_certificates",
"(",
")",
"return",
... | 26 | 15.230769 |
def p_paramlist_single(p):
""" paramlist : ID
"""
p[0] = [ID(p[1], value='', args=None, lineno=p.lineno(1),
fname=CURRENT_FILE[-1])] | [
"def",
"p_paramlist_single",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"ID",
"(",
"p",
"[",
"1",
"]",
",",
"value",
"=",
"''",
",",
"args",
"=",
"None",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"fname",
"=",
"CURR... | 31 | 7.2 |
def convert_disp_formula_elements(self):
"""
<disp-formula> elements must be converted to conforming elements
"""
for disp in self.main.getroot().findall('.//disp-formula'):
#find label element
label_el = disp.find('label')
graphic_el = disp.find('grap... | [
"def",
"convert_disp_formula_elements",
"(",
"self",
")",
":",
"for",
"disp",
"in",
"self",
".",
"main",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'.//disp-formula'",
")",
":",
"#find label element",
"label_el",
"=",
"disp",
".",
"find",
"(",
"'label'"... | 47.152174 | 13.76087 |
def _resource_deletion(resource):
""" Recalculate consumption details and save resource details """
if resource.__class__ not in CostTrackingRegister.registered_resources:
return
new_configuration = {}
price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration)
... | [
"def",
"_resource_deletion",
"(",
"resource",
")",
":",
"if",
"resource",
".",
"__class__",
"not",
"in",
"CostTrackingRegister",
".",
"registered_resources",
":",
"return",
"new_configuration",
"=",
"{",
"}",
"price_estimate",
"=",
"models",
".",
"PriceEstimate",
... | 49.285714 | 20.571429 |
def default_subprocess_runner(cmd, cwd=None, extra_environ=None):
"""The default method of calling the wrapper subprocess."""
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
check_call(cmd, cwd=cwd, env=env) | [
"def",
"default_subprocess_runner",
"(",
"cmd",
",",
"cwd",
"=",
"None",
",",
"extra_environ",
"=",
"None",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"extra_environ",
":",
"env",
".",
"update",
"(",
"extra_environ",
")",
... | 35.142857 | 15.285714 |
def task(self, total: int, name=None, message=None):
"""Wrap code into a begin and end call on this monitor"""
self.begin(total, name, message)
try:
yield self
finally:
self.done() | [
"def",
"task",
"(",
"self",
",",
"total",
":",
"int",
",",
"name",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"begin",
"(",
"total",
",",
"name",
",",
"message",
")",
"try",
":",
"yield",
"self",
"finally",
":",
"self",
".",... | 32.857143 | 14.142857 |
def __is_current(filepath):
'''Checks whether file is current'''
if not __DOWNLOAD_PARAMS['auto_update']:
return True
if not os.path.isfile(filepath):
return False
return datetime.datetime.utcfromtimestamp(os.path.getmtime(filepath)) \
> __get_last_update_time() | [
"def",
"__is_current",
"(",
"filepath",
")",
":",
"if",
"not",
"__DOWNLOAD_PARAMS",
"[",
"'auto_update'",
"]",
":",
"return",
"True",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"return",
"False",
"return",
"datetime",
".",
... | 29.5 | 18.3 |
def experiments_predictions_get(self, resource_url):
"""Get handle for model run resource at given Url.
Parameters
----------
resource_url : string
Url for model run resource at SCO-API
Returns
-------
scoserv.ModelRunHandle
Handle for lo... | [
"def",
"experiments_predictions_get",
"(",
"self",
",",
"resource_url",
")",
":",
"# Get resource directory, Json representation, active flag, and cache id",
"obj_dir",
",",
"obj_json",
",",
"is_active",
",",
"cache_id",
"=",
"self",
".",
"get_object",
"(",
"resource_url",
... | 37.652174 | 17.782609 |
def natural_name(self) -> str:
"""Valid python identifier representation of the expession."""
name = self.expression.strip()
for op in operators:
name = name.replace(op, operator_to_identifier[op])
return wt_kit.string2identifier(name) | [
"def",
"natural_name",
"(",
"self",
")",
"->",
"str",
":",
"name",
"=",
"self",
".",
"expression",
".",
"strip",
"(",
")",
"for",
"op",
"in",
"operators",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"op",
",",
"operator_to_identifier",
"[",
"op",
... | 45.666667 | 8.666667 |
def find_ab_params(spread, min_dist):
"""Fit a, b params for the differentiable curve used in lower
dimensional fuzzy simplicial complex construction. We want the
smooth curve (from a pre-defined family with simple gradient) that
best matches an offset exponential decay.
"""
def curve(x, a, b):... | [
"def",
"find_ab_params",
"(",
"spread",
",",
"min_dist",
")",
":",
"def",
"curve",
"(",
"x",
",",
"a",
",",
"b",
")",
":",
"return",
"1.0",
"/",
"(",
"1.0",
"+",
"a",
"*",
"x",
"**",
"(",
"2",
"*",
"b",
")",
")",
"xv",
"=",
"np",
".",
"lins... | 37.5625 | 14.9375 |
def pdf2png(file_in, file_out):
"""
Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)
Parameters
----------
file_in : str
The path to the pdf file to be converted.
file_out : str
The path to t... | [
"def",
"pdf2png",
"(",
"file_in",
",",
"file_out",
")",
":",
"command",
"=",
"'convert -display 37.5 {} -resize 600 -append {}'",
".",
"format",
"(",
"file_in",
",",
"file_out",
")",
"_subprocess",
".",
"call",
"(",
"_shlex",
".",
"split",
"(",
"command",
")",
... | 33.928571 | 25.214286 |
def create_application(self, team_id, name, url=None):
"""
Creates an application under a given team.
:param team_id: Team identifier.
:param name: The name of the new application being created.
:param url: The url of where the application is located.
"""
params =... | [
"def",
"create_application",
"(",
"self",
",",
"team_id",
",",
"name",
",",
"url",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"url",
":",
"params",
"[",
"'url'",
"]",
"=",
"url",
"return",
"self",
".",
"_request",
... | 42.727273 | 15.818182 |
def delete(self):
"""
Remove the document and all of its bundles from ProvStore.
.. warning::
Cannot be undone.
"""
if self.abstract:
raise AbstractDocumentException()
self._api.delete_document(self.id)
self._id = None
return True | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"abstract",
":",
"raise",
"AbstractDocumentException",
"(",
")",
"self",
".",
"_api",
".",
"delete_document",
"(",
"self",
".",
"id",
")",
"self",
".",
"_id",
"=",
"None",
"return",
"True"
] | 21.928571 | 18.642857 |
def read_atoms(fn, cycfn=None, pos_only=False, conv=1.0):
"""
Read atom information from an atoms.dat file (i.e., tblmd, MDCORE input file)
"""
f = paropen(fn, "r")
l = f.readline().lstrip()
while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ):
l = f.readline().lstrip()
n_atoms = in... | [
"def",
"read_atoms",
"(",
"fn",
",",
"cycfn",
"=",
"None",
",",
"pos_only",
"=",
"False",
",",
"conv",
"=",
"1.0",
")",
":",
"f",
"=",
"paropen",
"(",
"fn",
",",
"\"r\"",
")",
"l",
"=",
"f",
".",
"readline",
"(",
")",
".",
"lstrip",
"(",
")",
... | 28.300813 | 20.593496 |
def fetch_request_ids(item_ids, cls, attr_name, verification_list=None):
"""Return a list of cls instances for all the ids provided in item_ids.
:param item_ids: The list of ids to fetch objects for
:param cls: The class to fetch the ids from
:param attr_name: The name of the attribute for exception pu... | [
"def",
"fetch_request_ids",
"(",
"item_ids",
",",
"cls",
",",
"attr_name",
",",
"verification_list",
"=",
"None",
")",
":",
"if",
"not",
"item_ids",
":",
"return",
"[",
"]",
"items",
"=",
"[",
"]",
"for",
"item_id",
"in",
"item_ids",
":",
"item",
"=",
... | 37.681818 | 19.590909 |
def add_result(self, result):
"""
Adds the result of a completed job to the result list, then decrements
the active job count. If the job set is already complete, the result is
simply discarded instead.
"""
if self._active_jobs == 0:
return
self._res... | [
"def",
"add_result",
"(",
"self",
",",
"result",
")",
":",
"if",
"self",
".",
"_active_jobs",
"==",
"0",
":",
"return",
"self",
".",
"_results",
".",
"add",
"(",
"result",
")",
"self",
".",
"_active_jobs",
"-=",
"1",
"if",
"self",
".",
"_active_jobs",
... | 29.571429 | 17.285714 |
def _parse_chance(self, element):
"""
Parse a chance element
:param element: The XML Element object
:type element: etree._Element
"""
try:
chance = float(element.text)
except (ValueError, TypeError, AttributeError):
self._log.warn('Invalid... | [
"def",
"_parse_chance",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"chance",
"=",
"float",
"(",
"element",
".",
"text",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"AttributeError",
")",
":",
"self",
".",
"_log",
".",
"warn",
"(",
... | 36.842105 | 19.578947 |
def LargestComponent(self):
"""
Returns (i, val) where i is the component index (0 - 2)
which has largest absolute value and val is the value
of the component.
"""
if abs(self.x) > abs(self.y):
if abs(self.x) > abs(self.z):
return (0, self.x)
else:
return (2, self.z)
... | [
"def",
"LargestComponent",
"(",
"self",
")",
":",
"if",
"abs",
"(",
"self",
".",
"x",
")",
">",
"abs",
"(",
"self",
".",
"y",
")",
":",
"if",
"abs",
"(",
"self",
".",
"x",
")",
">",
"abs",
"(",
"self",
".",
"z",
")",
":",
"return",
"(",
"0"... | 26 | 14.375 |
def parse(
source: SourceType, no_location=False, experimental_fragment_variables=False
) -> DocumentNode:
"""Given a GraphQL source, parse it into a Document.
Throws GraphQLError if a syntax error is encountered.
By default, the parser creates AST nodes that know the location in the source that
t... | [
"def",
"parse",
"(",
"source",
":",
"SourceType",
",",
"no_location",
"=",
"False",
",",
"experimental_fragment_variables",
"=",
"False",
")",
"->",
"DocumentNode",
":",
"if",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"source",
"=",
"Source",
"(",
... | 36.060606 | 27.181818 |
def __scanPlugins(self):
"""Scanning local plugin directories and third-party plugin packages.
:returns: No return, but self.__plugins will be updated
:raises: PluginError: raises an exception, maybe CSSLoadError, VersionError, based PluginError
"""
self.logger.info("Initializa... | [
"def",
"__scanPlugins",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Initialization Plugins Start, local plugins path: %s, third party plugins: %s\"",
"%",
"(",
"self",
".",
"plugins_abspath",
",",
"self",
".",
"plugin_packages",
")",
")",
"#: Lo... | 63.482759 | 38.448276 |
def add_global_response_interceptor(self, response_interceptor):
# type: (AbstractResponseInterceptor) -> None
"""Register input to the global response interceptors list.
:param response_interceptor: Response Interceptor instance to
be registered.
:type response_interceptor:... | [
"def",
"add_global_response_interceptor",
"(",
"self",
",",
"response_interceptor",
")",
":",
"# type: (AbstractResponseInterceptor) -> None",
"if",
"response_interceptor",
"is",
"None",
":",
"raise",
"RuntimeConfigException",
"(",
"\"Valid Response Interceptor instance to be provi... | 43.166667 | 20.277778 |
def neighbors(self):
'''
Returns the left and right neighbors as Word instance.
If the word is the first one in the sentence only the right neighbor is returned and vice versa.
'''
if len(self._sentence) == 1:
return {
'left': None,
'ri... | [
"def",
"neighbors",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_sentence",
")",
"==",
"1",
":",
"return",
"{",
"'left'",
":",
"None",
",",
"'right'",
":",
"None",
"}",
"else",
":",
"p",
"=",
"self",
".",
"_position",
"if",
"-",
"1",
... | 34.966667 | 17.366667 |
def fix_module(job):
"""
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
"""
modules = settings.RQ_JOBS_MODULE
if not type(modules) == tuple:
modules = [modules]
for module in modules:
try:
module_match = importlib.import_module(module)
... | [
"def",
"fix_module",
"(",
"job",
")",
":",
"modules",
"=",
"settings",
".",
"RQ_JOBS_MODULE",
"if",
"not",
"type",
"(",
"modules",
")",
"==",
"tuple",
":",
"modules",
"=",
"[",
"modules",
"]",
"for",
"module",
"in",
"modules",
":",
"try",
":",
"module_... | 31.0625 | 15.4375 |
def toggle_codes(self, event):
"""
Show/hide method code explanation widget on button click
"""
btn = event.GetEventObject()
if btn.Label == 'Show method codes':
self.code_msg_boxsizer.ShowItems(True)
btn.SetLabel('Hide method codes')
else:
... | [
"def",
"toggle_codes",
"(",
"self",
",",
"event",
")",
":",
"btn",
"=",
"event",
".",
"GetEventObject",
"(",
")",
"if",
"btn",
".",
"Label",
"==",
"'Show method codes'",
":",
"self",
".",
"code_msg_boxsizer",
".",
"ShowItems",
"(",
"True",
")",
"btn",
".... | 35.416667 | 9.583333 |
async def restart(request: web.Request) -> web.Response:
""" Restart the robot.
Blocks while the restart lock is held.
"""
async with request.app[RESTART_LOCK_NAME]:
asyncio.get_event_loop().call_later(1, _do_restart)
return web.json_response({'message': 'Restarting in 1s'},
... | [
"async",
"def",
"restart",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"async",
"with",
"request",
".",
"app",
"[",
"RESTART_LOCK_NAME",
"]",
":",
"asyncio",
".",
"get_event_loop",
"(",
")",
".",
"call_later",
"(",... | 37.444444 | 11.555556 |
def read_10xgenomics(cls, tarball_fpath: str, prefix: str,
use_ensembl_ids: bool = False):
"""Read a 10X genomics compressed tarball containing expression data.
Note: common prefix patterns:
- "filtered_gene_bc_matrices/[annotations]/"
- "filtered_matric... | [
"def",
"read_10xgenomics",
"(",
"cls",
",",
"tarball_fpath",
":",
"str",
",",
"prefix",
":",
"str",
",",
"use_ensembl_ids",
":",
"bool",
"=",
"False",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Reading file: %s'",
",",
"tarball_fpath",
")",
"with",
"tarfile",
... | 36.878049 | 19.439024 |
def credential_share_simulate(self, cred_id, *user_ids):
"""Shares a given credential to the specified Users.
:param cred_id: Credential ID
:param user_ids: List of User IDs
"""
return self.raw_query("credential", "shareSimulate", data={
'id': cred_id,
'u... | [
"def",
"credential_share_simulate",
"(",
"self",
",",
"cred_id",
",",
"*",
"user_ids",
")",
":",
"return",
"self",
".",
"raw_query",
"(",
"\"credential\"",
",",
"\"shareSimulate\"",
",",
"data",
"=",
"{",
"'id'",
":",
"cred_id",
",",
"'users'",
":",
"[",
"... | 35.9 | 14.2 |
def from_string(cls, token_string):
""" `token_string` should be the string representation from the server. """
# unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface"
if isinstance(token_string, six.text_type):
... | [
"def",
"from_string",
"(",
"cls",
",",
"token_string",
")",
":",
"# unhexlify works fine with unicode input in everythin but pypy3, where it Raises \"TypeError: 'str' does not support the buffer interface\"",
"if",
"isinstance",
"(",
"token_string",
",",
"six",
".",
"text_type",
")... | 64.285714 | 20.428571 |
async def commit(
request: web.Request, session: UpdateSession) -> web.Response:
""" Serves /update/:session/commit """
if session.stage != Stages.DONE:
return web.json_response(
data={'error': 'not-ready',
'message': f'System is not ready to commit the update '
... | [
"async",
"def",
"commit",
"(",
"request",
":",
"web",
".",
"Request",
",",
"session",
":",
"UpdateSession",
")",
"->",
"web",
".",
"Response",
":",
"if",
"session",
".",
"stage",
"!=",
"Stages",
".",
"DONE",
":",
"return",
"web",
".",
"json_response",
... | 37 | 16.473684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.