text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def apply_config(self, config):
"""
Applies config
"""
self.hash_name = config['hash_name']
self.dim = config['dim']
self.bin_width = config['bin_width']
self.projection_count = config['projection_count']
self.components = config['components'] | [
"def",
"apply_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"hash_name",
"=",
"config",
"[",
"'hash_name'",
"]",
"self",
".",
"dim",
"=",
"config",
"[",
"'dim'",
"]",
"self",
".",
"bin_width",
"=",
"config",
"[",
"'bin_width'",
"]",
"self... | 33.222222 | 7.444444 |
def get_remote_mgmt_addr(self, tlv_data):
"""Returns Remote Mgmt Addr from the TLV. """
ret, parsed_val = self._check_common_tlv_format(
tlv_data, "IPv4:", "Management Address TLV")
if not ret:
return None
addr_fam = 'IPv4:'
addr = parsed_val[1].split('\n'... | [
"def",
"get_remote_mgmt_addr",
"(",
"self",
",",
"tlv_data",
")",
":",
"ret",
",",
"parsed_val",
"=",
"self",
".",
"_check_common_tlv_format",
"(",
"tlv_data",
",",
"\"IPv4:\"",
",",
"\"Management Address TLV\"",
")",
"if",
"not",
"ret",
":",
"return",
"None",
... | 39.444444 | 11.777778 |
def remove_group_roles(request, group, domain=None, project=None):
"""Removes all roles from a group on a domain or project."""
client = keystoneclient(request, admin=True)
roles = client.roles.list(group=group, domain=domain, project=project)
for role in roles:
remove_group_role(request, role=r... | [
"def",
"remove_group_roles",
"(",
"request",
",",
"group",
",",
"domain",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"client",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
"roles",
"=",
"client",
".",
"roles",
".",
"l... | 56 | 17.714286 |
def parse_package_for_version(name):
"""
Searches for a variable named __version__ in name's __init__.py file and
returns the value. This function parses the source text. It does not load
the module.
"""
from utool import util_regex
init_fpath = join(name, '__init__.py')
version_errmsg ... | [
"def",
"parse_package_for_version",
"(",
"name",
")",
":",
"from",
"utool",
"import",
"util_regex",
"init_fpath",
"=",
"join",
"(",
"name",
",",
"'__init__.py'",
")",
"version_errmsg",
"=",
"textwrap",
".",
"dedent",
"(",
"'''\n You must include a __version__ v... | 38.848485 | 10.363636 |
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6,
units="ad-hoc"):
"""Return the amplitude of the electric field for a Gaussian beam.
This the amplitude at the center of a laser beam of power P (in Watts) and\
a Gaussian intensity distributio... | [
"def",
"electric_field_amplitude_gaussian",
"(",
"P",
",",
"sigmax",
",",
"sigmay",
"=",
"None",
",",
"Omega",
"=",
"1.0e6",
",",
"units",
"=",
"\"ad-hoc\"",
")",
":",
"e0",
"=",
"hbar",
"*",
"Omega",
"/",
"(",
"e",
"*",
"a0",
")",
"# This is the electri... | 40.047619 | 23.428571 |
def diff(file_, imports):
"""Display the difference between modules in a file and imported modules."""
modules_not_imported = compare_modules(file_, imports)
logging.info("The following modules are in {} but do not seem to be imported: "
"{}".format(file_, ", ".join(x for x in modules_not_... | [
"def",
"diff",
"(",
"file_",
",",
"imports",
")",
":",
"modules_not_imported",
"=",
"compare_modules",
"(",
"file_",
",",
"imports",
")",
"logging",
".",
"info",
"(",
"\"The following modules are in {} but do not seem to be imported: \"",
"\"{}\"",
".",
"format",
"(",... | 54.333333 | 26 |
def parse(file_path):
"""Return a decoded API to the data from a file path.
:param file_path: the input file path. Data is not entropy compressed (e.g. gzip)
:return an API to decoded data """
newDecoder = MMTFDecoder()
with open(file_path, "rb") as fh:
newDecoder.decode_data(_unpack(fh))
... | [
"def",
"parse",
"(",
"file_path",
")",
":",
"newDecoder",
"=",
"MMTFDecoder",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"\"rb\"",
")",
"as",
"fh",
":",
"newDecoder",
".",
"decode_data",
"(",
"_unpack",
"(",
"fh",
")",
")",
"return",
"newDecoder"
] | 36.888889 | 15.444444 |
def get_scan_parameters_table_from_meta_data(meta_data_array, scan_parameters=None):
'''Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data .
Parameters
----------
meta_data_array : numpy.ndarray
The array with the scan pa... | [
"def",
"get_scan_parameters_table_from_meta_data",
"(",
"meta_data_array",
",",
"scan_parameters",
"=",
"None",
")",
":",
"if",
"scan_parameters",
"is",
"None",
":",
"try",
":",
"last_not_parameter_column",
"=",
"meta_data_array",
".",
"dtype",
".",
"names",
".",
"i... | 45.931034 | 35.034483 |
def render_region(widget=None, request=None, view=None,
page=None, region=None):
"""returns rendered content
this is not too clear and little tricky,
because external apps needs calling process method
"""
# change the request
if not isinstance(request, dict):
request.q... | [
"def",
"render_region",
"(",
"widget",
"=",
"None",
",",
"request",
"=",
"None",
",",
"view",
"=",
"None",
",",
"page",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"# change the request",
"if",
"not",
"isinstance",
"(",
"request",
",",
"dict",
"... | 31.92 | 21.56 |
def interleave_keys(a, b):
"""Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined by this function. Useful for tasks with two
text fields like machine translation or natural language inference.
... | [
"def",
"interleave_keys",
"(",
"a",
",",
"b",
")",
":",
"def",
"interleave",
"(",
"args",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"x",
"for",
"t",
"in",
"zip",
"(",
"*",
"args",
")",
"for",
"x",
"in",
"t",
"]",
")",
"return",
"int",
... | 48.2 | 22.6 |
def get_token_accuracy(targets, outputs, ignore_index=None):
""" Get the accuracy token accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
... | [
"def",
"get_token_accuracy",
"(",
"targets",
",",
"outputs",
",",
"ignore_index",
"=",
"None",
")",
":",
"n_correct",
"=",
"0.0",
"n_total",
"=",
"0.0",
"for",
"target",
",",
"output",
"in",
"zip",
"(",
"targets",
",",
"outputs",
")",
":",
"if",
"not",
... | 34.9 | 23.98 |
def _wait_new_conf(self):
"""Ask the daemon to drop its configuration and wait for a new one
:return: None
"""
with self.app.conf_lock:
logger.debug("My Arbiter wants me to wait for a new configuration.")
# Clear can occur while setting up a new conf and lead to ... | [
"def",
"_wait_new_conf",
"(",
"self",
")",
":",
"with",
"self",
".",
"app",
".",
"conf_lock",
":",
"logger",
".",
"debug",
"(",
"\"My Arbiter wants me to wait for a new configuration.\"",
")",
"# Clear can occur while setting up a new conf and lead to error.",
"self",
".",
... | 39.2 | 16.5 |
def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) | [
"def",
"prettyprint",
"(",
"d",
")",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\": \"",
")",
")",
")"
] | 39.2 | 9 |
def SetServerInformation(self, server, port):
"""Set the server information.
Args:
server (str): IP address or hostname of the server.
port (int): Port number of the server.
"""
self._host = server
self._port = port
logger.debug('Elasticsearch server: {0!s} port: {1:d}'.format(
... | [
"def",
"SetServerInformation",
"(",
"self",
",",
"server",
",",
"port",
")",
":",
"self",
".",
"_host",
"=",
"server",
"self",
".",
"_port",
"=",
"port",
"logger",
".",
"debug",
"(",
"'Elasticsearch server: {0!s} port: {1:d}'",
".",
"format",
"(",
"server",
... | 29.818182 | 16.090909 |
def separable_approx(h, N=1):
"""
finds the k-th rank approximation to h, where k = 1..N
similar to separable_series
Parameters
----------
h: ndarray
input array (2 or 2 dimensional)
N: int
order of approximation
Returns
-------
all N apprxoimations res[i],... | [
"def",
"separable_approx",
"(",
"h",
",",
"N",
"=",
"1",
")",
":",
"if",
"h",
".",
"ndim",
"==",
"2",
":",
"return",
"_separable_approx2",
"(",
"h",
",",
"N",
")",
"elif",
"h",
".",
"ndim",
"==",
"3",
":",
"return",
"_separable_approx3",
"(",
"h",
... | 22.791667 | 21.291667 |
def unfreeze_extensions(self):
"""Remove a previously frozen list of extensions."""
output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
if not os.path.isfile(output_path):
raise ExternalError("There is no frozen extension list")
os.remove(output_path)
... | [
"def",
"unfreeze_extensions",
"(",
"self",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_registry_folder",
"(",
")",
",",
"'frozen_extensions.json'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"output_path",
")",
":",
... | 40.222222 | 20.222222 |
def _set_interface_fe(self, v, load=False):
"""
Setter method for interface_fe, mapped from YANG variable /rule/command/interface_fe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_fe is considered as a private
method. Backends looking to popula... | [
"def",
"_set_interface_fe",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 74.772727 | 34.5 |
def delete_repository_method(namespace, name, snapshot_id):
"""Redacts a method and all of its associated configurations.
The method should exist in the methods repository.
Args:
namespace (str): Methods namespace
method (str): method name
snapshot_id (int): snapshot_id of the meth... | [
"def",
"delete_repository_method",
"(",
"namespace",
",",
"name",
",",
"snapshot_id",
")",
":",
"uri",
"=",
"\"methods/{0}/{1}/{2}\"",
".",
"format",
"(",
"namespace",
",",
"name",
",",
"snapshot_id",
")",
"return",
"__delete",
"(",
"uri",
")"
] | 34.933333 | 22.4 |
def get_absolute_url(self):
"""
Returns absolute URL for the category.
"""
if not self.tree_parent_id:
url = reverse('root_homepage')
else:
url = reverse('category_detail', kwargs={'category' : self.tree_path})
if self.site_id != settings.SITE_ID:
... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tree_parent_id",
":",
"url",
"=",
"reverse",
"(",
"'root_homepage'",
")",
"else",
":",
"url",
"=",
"reverse",
"(",
"'category_detail'",
",",
"kwargs",
"=",
"{",
"'category'",
":",... | 37.25 | 13.25 |
def get_readable_filesize(size):
"""get_readable_filesize(size) -> filesize -- return human readable
filesize from given size in bytes.
"""
if(size < 1024):
return str(size)+' bytes'
temp = size/1024.0
level = 1
while(temp >= 1024 and level< 3):
temp = temp/1024
level += 1
if(level == 1):
return str(ro... | [
"def",
"get_readable_filesize",
"(",
"size",
")",
":",
"if",
"(",
"size",
"<",
"1024",
")",
":",
"return",
"str",
"(",
"size",
")",
"+",
"' bytes'",
"temp",
"=",
"size",
"/",
"1024.0",
"level",
"=",
"1",
"while",
"(",
"temp",
">=",
"1024",
"and",
"... | 24.470588 | 15.117647 |
def update_filter(self, filter_id,
name=None, description=None,
jql=None, favourite=None):
"""Update a filter and return a filter Resource for it.
:param name: name of the new filter
:type name: Optional[str]
:param description: useful human r... | [
"def",
"update_filter",
"(",
"self",
",",
"filter_id",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"jql",
"=",
"None",
",",
"favourite",
"=",
"None",
")",
":",
"filter",
"=",
"self",
".",
"filter",
"(",
"filter_id",
")",
"data",
"... | 41.75 | 16.75 |
def _get_base(server_certificate, **conn):
"""Fetch the base IAM Server Certificate."""
server_certificate['_version'] = 1
# Get the initial cert details:
cert_details = get_server_certificate_api(server_certificate['ServerCertificateName'], **conn)
if cert_details:
server_certificate.upda... | [
"def",
"_get_base",
"(",
"server_certificate",
",",
"*",
"*",
"conn",
")",
":",
"server_certificate",
"[",
"'_version'",
"]",
"=",
"1",
"# Get the initial cert details:",
"cert_details",
"=",
"get_server_certificate_api",
"(",
"server_certificate",
"[",
"'ServerCertific... | 47.411765 | 30.235294 |
def _parse_01(ofiles, individual=False):
"""
a subfunction for summarizing results
"""
## parse results from outfiles
cols = []
dats = []
for ofile in ofiles:
## parse file
with open(ofile) as infile:
dat = infile.read()
lastbits = dat.split(".mcmc.txt... | [
"def",
"_parse_01",
"(",
"ofiles",
",",
"individual",
"=",
"False",
")",
":",
"## parse results from outfiles",
"cols",
"=",
"[",
"]",
"dats",
"=",
"[",
"]",
"for",
"ofile",
"in",
"ofiles",
":",
"## parse file",
"with",
"open",
"(",
"ofile",
")",
"as",
"... | 30.085106 | 15.893617 |
def get_conversations(self):
"""
Returns list of Conversation objects
"""
cs = self.data["data"]
res = []
for c in cs:
res.append(Conversation(c))
return res | [
"def",
"get_conversations",
"(",
"self",
")",
":",
"cs",
"=",
"self",
".",
"data",
"[",
"\"data\"",
"]",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"res",
".",
"append",
"(",
"Conversation",
"(",
"c",
")",
")",
"return",
"res"
] | 24.222222 | 10.444444 |
def get_artists(self, search, start=0, max_items=100):
"""Search for artists.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('artists', search, start,
max_items) | [
"def",
"get_artists",
"(",
"self",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"return",
"self",
".",
"get_music_service_information",
"(",
"'artists'",
",",
"search",
",",
"start",
",",
"max_items",
")"
] | 42.857143 | 19.857143 |
def slugify(value, separator='-', max_length=0, word_boundary=False,
entities=True, decimal=True, hexadecimal=True):
'''Normalizes string, removes non-alpha characters,
and converts spaces to ``separator`` character
'''
value = normalize('NFKD', to_string(value, 'utf-8', 'ignore'))
if un... | [
"def",
"slugify",
"(",
"value",
",",
"separator",
"=",
"'-'",
",",
"max_length",
"=",
"0",
",",
"word_boundary",
"=",
"False",
",",
"entities",
"=",
"True",
",",
"decimal",
"=",
"True",
",",
"hexadecimal",
"=",
"True",
")",
":",
"value",
"=",
"normaliz... | 28.386364 | 22.25 |
def remove(coll, value):
"""Remove all the occurrences of a given value
:param coll: a collection
:param value: the value to remove
:returns: a list
>>> data = ('NA', 0, 1, 'NA', 1, 2, 3, 'NA', 5)
>>> remove(data, 'NA')
(0, 1, 1, 2, 3, 5)
"""
coll_class = coll.__class__
return... | [
"def",
"remove",
"(",
"coll",
",",
"value",
")",
":",
"coll_class",
"=",
"coll",
".",
"__class__",
"return",
"coll_class",
"(",
"x",
"for",
"x",
"in",
"coll",
"if",
"x",
"!=",
"value",
")"
] | 24.928571 | 16.714286 |
def import_bundles(self, dir, detach=False, force=False):
"""
Import bundles from a directory
:param dir:
:return:
"""
import yaml
fs = fsopendir(dir)
bundles = []
for f in fs.walkfiles(wildcard='bundle.yaml'):
self.logger.info('V... | [
"def",
"import_bundles",
"(",
"self",
",",
"dir",
",",
"detach",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"import",
"yaml",
"fs",
"=",
"fsopendir",
"(",
"dir",
")",
"bundles",
"=",
"[",
"]",
"for",
"f",
"in",
"fs",
".",
"walkfiles",
"(",... | 29.25 | 24.75 |
def from_string(string):
"""
Construct an AdfKey object from the string.
Parameters
----------
string : str
A string.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the string.
Raises
------
... | [
"def",
"from_string",
"(",
"string",
")",
":",
"def",
"is_float",
"(",
"s",
")",
":",
"if",
"'.'",
"in",
"s",
"or",
"'E'",
"in",
"s",
"or",
"'e'",
"in",
"s",
":",
"return",
"True",
"else",
":",
"return",
"False",
"if",
"string",
".",
"find",
"(",... | 29.985294 | 18.279412 |
def _extract_pc(d, root, pc, whichtables):
"""
Extract all data from a PaleoData dictionary.
:param dict d: PaleoData dictionary
:param dict root: Time series root data
:param str pc: paleoData or chronData
:param str whichtables: all, meas, summ, or ens
:return list _ts: Time series
"""... | [
"def",
"_extract_pc",
"(",
"d",
",",
"root",
",",
"pc",
",",
"whichtables",
")",
":",
"logger_ts",
".",
"info",
"(",
"\"enter extract_pc\"",
")",
"_ts",
"=",
"[",
"]",
"try",
":",
"# For each table in pc",
"for",
"k",
",",
"v",
"in",
"d",
"[",
"pc",
... | 53.268293 | 23.512195 |
def setitem(self, indexer, value):
"""Set the value inplace, returning a same-typed block.
This differs from Block.setitem by not allowing setitem to change
the dtype of the Block.
Parameters
----------
indexer : tuple, list-like, array-like, slice
The subse... | [
"def",
"setitem",
"(",
"self",
",",
"indexer",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"indexer",
",",
"tuple",
")",
":",
"# we are always 1-D",
"indexer",
"=",
"indexer",
"[",
"0",
"]",
"check_setitem_lengths",
"(",
"indexer",
",",
"value",
",",
... | 26.862069 | 19.551724 |
def create(
self, request, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Add a permission to a team.'''
team = self.check_team_permissions(
request, parent_lookup_seedteam,
parent_lookup_seedteam__organization)
serial... | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"parent_lookup_seedteam",
"=",
"None",
",",
"parent_lookup_seedteam__organization",
"=",
"None",
")",
":",
"team",
"=",
"self",
".",
"check_team_permissions",
"(",
"request",
",",
"parent_lookup_seedteam",
",",
"p... | 47.076923 | 17.692308 |
def _create_body(self, name, img=None, cont=None, img_format=None,
img_name=None):
"""
Used to create a new task. Since tasks don't have names, the required
'name' parameter is used for the type of task: 'import' or 'export'.
"""
img = utils.get_id(img)
cont =... | [
"def",
"_create_body",
"(",
"self",
",",
"name",
",",
"img",
"=",
"None",
",",
"cont",
"=",
"None",
",",
"img_format",
"=",
"None",
",",
"img_name",
"=",
"None",
")",
":",
"img",
"=",
"utils",
".",
"get_id",
"(",
"img",
")",
"cont",
"=",
"utils",
... | 40.1 | 15.4 |
def setLinkQuality(self, EUIadr, LinkQuality):
"""set custom LinkQualityIn for all receiving messages from the specified EUIadr
Args:
EUIadr: a given extended address
LinkQuality: a given custom link quality
link quality/link margin mapping table
... | [
"def",
"setLinkQuality",
"(",
"self",
",",
"EUIadr",
",",
"LinkQuality",
")",
":",
"print",
"'%s call setLinkQuality'",
"%",
"self",
".",
"port",
"print",
"EUIadr",
"print",
"LinkQuality",
"try",
":",
"# process EUIadr",
"euiHex",
"=",
"hex",
"(",
"EUIadr",
")... | 36.810811 | 14.081081 |
def cache_all(self):
"""Cache all available man pages"""
respond = input(
'By default, cppman fetches pages on-the-fly if corresponding '
'page is not found in the cache. The "cache-all" option is only '
'useful if you want to view man pages offline. '
... | [
"def",
"cache_all",
"(",
"self",
")",
":",
"respond",
"=",
"input",
"(",
"'By default, cppman fetches pages on-the-fly if corresponding '",
"'page is not found in the cache. The \"cache-all\" option is only '",
"'useful if you want to view man pages offline. '",
"'Caching all contents will... | 33.509804 | 19.529412 |
def file_handle(fnh, mode="rU"):
"""
Takes either a file path or an open file handle, checks validity and returns an open
file handle or raises an appropriate Exception.
:type fnh: str
:param fnh: It is the full path to a file, or open file handle
:type mode: str
:param mode: The way in wh... | [
"def",
"file_handle",
"(",
"fnh",
",",
"mode",
"=",
"\"rU\"",
")",
":",
"handle",
"=",
"None",
"if",
"isinstance",
"(",
"fnh",
",",
"file",
")",
":",
"if",
"fnh",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"Input file is closed.\"",
")",
"handle",... | 31.347826 | 22.391304 |
def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False):
"""Compute an array of acoustic frequencies tuned to the mel scale.
The mel scale is a quasi-logarithmic function of acoustic frequency
designed such that perceptually similar pitch intervals (e.g. octaves)
appear equal in width over t... | [
"def",
"mel_frequencies",
"(",
"n_mels",
"=",
"128",
",",
"fmin",
"=",
"0.0",
",",
"fmax",
"=",
"11025.0",
",",
"htk",
"=",
"False",
")",
":",
"# 'Center freqs' of mel bands - uniformly spaced between limits",
"min_mel",
"=",
"hz_to_mel",
"(",
"fmin",
",",
"htk"... | 38.211765 | 26.635294 |
def SLICE(array, n, position=None):
"""
Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an inte... | [
"def",
"SLICE",
"(",
"array",
",",
"n",
",",
"position",
"=",
"None",
")",
":",
"return",
"{",
"'$slice'",
":",
"[",
"array",
",",
"position",
",",
"n",
"]",
"}",
"if",
"position",
"is",
"not",
"None",
"else",
"{",
"'$slice'",
":",
"[",
"array",
... | 49.272727 | 22.363636 |
def nvmlDeviceGetTemperatureThreshold(handle, threshold):
r"""
/**
* Retrieves the temperature threshold for the GPU with the specified threshold type in degrees C.
*
* For Kepler &tm; or newer fully supported devices.
*
* See \ref nvmlTemperatureThresholds_t for details on available te... | [
"def",
"nvmlDeviceGetTemperatureThreshold",
"(",
"handle",
",",
"threshold",
")",
":",
"c_temp",
"=",
"c_uint",
"(",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetTemperatureThreshold\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
"_nvmlTemperature... | 57 | 36.518519 |
def K_lift_check_valve_Crane(D1, D2, fd=None, angled=True):
r'''Returns the loss coefficient for a lift check valve as shown in [1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^2) + (1-\beta^2)... | [
"def",
"K_lift_check_valve_Crane",
"(",
"D1",
",",
"D2",
",",
"fd",
"=",
"None",
",",
"angled",
"=",
"True",
")",
":",
"beta",
"=",
"D1",
"/",
"D2",
"if",
"fd",
"is",
"None",
":",
"fd",
"=",
"ft_Crane",
"(",
"D2",
")",
"if",
"angled",
":",
"K1",
... | 28.184615 | 27.323077 |
def get_vnetwork_dvpgs_output_vnetwork_dvpgs_dvs_nn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = get_vnetwork_dvpgs
output = ET.SubElement(get_vnetwork_dvpgs, "output")
vne... | [
"def",
"get_vnetwork_dvpgs_output_vnetwork_dvpgs_dvs_nn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_dvpgs",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_dvpgs\"",
")",
"config",
... | 42.461538 | 14.230769 |
def run(self, bin, *args, **kwargs):
"""
Run a command inside the Python environment.
"""
bin = self._bin(bin)
cmd = [bin] + list(args)
shell = kwargs.get("shell", False)
call = kwargs.pop("call", False)
input_ = kwargs.pop("input_", None)
if she... | [
"def",
"run",
"(",
"self",
",",
"bin",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bin",
"=",
"self",
".",
"_bin",
"(",
"bin",
")",
"cmd",
"=",
"[",
"bin",
"]",
"+",
"list",
"(",
"args",
")",
"shell",
"=",
"kwargs",
".",
"get",
"(... | 29.72973 | 14.918919 |
def _adaptSynapses(self, inputVector, activeColumns, overlaps):
"""
The primary method in charge of learning. Adapts the permanence values of
the synapses based on the input vector, and the chosen columns after
inhibition round. Permanence values are increased for synapses connected to
input bits th... | [
"def",
"_adaptSynapses",
"(",
"self",
",",
"inputVector",
",",
"activeColumns",
",",
"overlaps",
")",
":",
"inputIndices",
"=",
"np",
".",
"where",
"(",
"inputVector",
">",
"0",
")",
"[",
"0",
"]",
"permChanges",
"=",
"np",
".",
"zeros",
"(",
"self",
"... | 46.535714 | 19.75 |
def mtf_image_transformer_base_single():
"""Small single parameters."""
hparams = mtf_image_transformer_base()
hparams.num_decoder_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams | [
"def",
"mtf_image_transformer_base_single",
"(",
")",
":",
"hparams",
"=",
"mtf_image_transformer_base",
"(",
")",
"hparams",
".",
"num_decoder_layers",
"=",
"6",
"hparams",
".",
"filter_size",
"=",
"256",
"hparams",
".",
"block_length",
"=",
"128",
"hparams",
"."... | 29 | 10.111111 |
def search_all(self, limit=50, format='json'):
''' Returns a single list containing up to 'limit' Result objects'''
desired_limit = limit
results = self._search(limit, format)
limit = limit - len(results)
while len(results) < desired_limit:
more_results = self._search... | [
"def",
"search_all",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"format",
"=",
"'json'",
")",
":",
"desired_limit",
"=",
"limit",
"results",
"=",
"self",
".",
"_search",
"(",
"limit",
",",
"format",
")",
"limit",
"=",
"limit",
"-",
"len",
"(",
"resul... | 39.153846 | 11.461538 |
def update_ff(self, ff, mol2=False, force_ff_assign=False):
"""Manages assigning the force field parameters.
The aim of this method is to avoid unnecessary assignment of the
force field.
Parameters
----------
ff: BuffForceField
The force field to be used for... | [
"def",
"update_ff",
"(",
"self",
",",
"ff",
",",
"mol2",
"=",
"False",
",",
"force_ff_assign",
"=",
"False",
")",
":",
"aff",
"=",
"False",
"if",
"force_ff_assign",
":",
"aff",
"=",
"True",
"elif",
"'assigned_ff'",
"not",
"in",
"self",
".",
"tags",
":"... | 32.384615 | 17.5 |
def enterTuple(self, tuple, path):
"""Called for every tuple.
If this returns False, the elements of the tuple will not be recursed over
and leaveTuple() will not be called.
"""
if skip_name(path):
return False
node = Node(path, tuple)
if self.condition.matches(node):
self.unord... | [
"def",
"enterTuple",
"(",
"self",
",",
"tuple",
",",
"path",
")",
":",
"if",
"skip_name",
"(",
"path",
")",
":",
"return",
"False",
"node",
"=",
"Node",
"(",
"path",
",",
"tuple",
")",
"if",
"self",
".",
"condition",
".",
"matches",
"(",
"node",
")... | 27.692308 | 14.846154 |
def atomic_sa(self, i):
r"""Calculate atomic surface area.
:type i: int
:param i: atom index
:rtype: float
"""
sa = 4.0 * np.pi * self.rads2[i]
neighbors = self.neighbors.get(i)
if neighbors is None:
return sa
XYZi = self.xyzs[i, n... | [
"def",
"atomic_sa",
"(",
"self",
",",
"i",
")",
":",
"sa",
"=",
"4.0",
"*",
"np",
".",
"pi",
"*",
"self",
".",
"rads2",
"[",
"i",
"]",
"neighbors",
"=",
"self",
".",
"neighbors",
".",
"get",
"(",
"i",
")",
"if",
"neighbors",
"is",
"None",
":",
... | 23.464286 | 19.071429 |
def _mount_points(self):
""" Returns map {volume_id: mount_point} """
diskutil_ls = subprocess.Popen(
["diskutil", "list", "-plist"], stdout=subprocess.PIPE
)
disks = _plist_from_popen(diskutil_ls)
return {
disk["DeviceIdentifier"]: disk.get("MountPoint",... | [
"def",
"_mount_points",
"(",
"self",
")",
":",
"diskutil_ls",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"diskutil\"",
",",
"\"list\"",
",",
"\"-plist\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"disks",
"=",
"_plist_from_popen",
"(",
"d... | 34.636364 | 19.545455 |
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set... | [
"def",
"set_parameter",
"(",
"name",
",",
"parameter",
",",
"value",
",",
"path",
"=",
"None",
")",
":",
"if",
"not",
"exists",
"(",
"name",
",",
"path",
"=",
"path",
")",
":",
"return",
"None",
"cmd",
"=",
"'lxc-cgroup'",
"if",
"path",
":",
"cmd",
... | 24.071429 | 22.857143 |
def _build_argspec(self):
"""Builds the ansible argument spec using the fields from the schema
definition. It's the caller's responsibility to add any arguments which
are not defined in the schema (e.g. login parameters)
"""
fields = self.manager._schema.fields
argspec = ... | [
"def",
"_build_argspec",
"(",
"self",
")",
":",
"fields",
"=",
"self",
".",
"manager",
".",
"_schema",
".",
"fields",
"argspec",
"=",
"{",
"}",
"for",
"(",
"field_name",
",",
"field",
")",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
":",
"# Re... | 35.36 | 19.72 |
def log_repo_action(func):
"""
Log all repo actions to .dgit/log.json
"""
def _inner(*args, **kwargs):
result = func(*args, **kwargs)
log_action(func, result, *args, **kwargs)
return result
_inner.__name__ = func.__name__
_inner.__doc__ = fun... | [
"def",
"log_repo_action",
"(",
"func",
")",
":",
"def",
"_inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"log_action",
"(",
"func",
",",
"result",
",",
"*",
"arg... | 25.769231 | 12.076923 |
def get_matching_symbols_pairs(self, cursor, opening_symbol, closing_symbol, backward=False):
"""
Returns the cursor for matching given symbols pairs.
:param cursor: Cursor to match from.
:type cursor: QTextCursor
:param opening_symbol: Opening symbol.
:type opening_symb... | [
"def",
"get_matching_symbols_pairs",
"(",
"self",
",",
"cursor",
",",
"opening_symbol",
",",
"closing_symbol",
",",
"backward",
"=",
"False",
")",
":",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"start_position",
"=",
"cursor",
".",
"selectionEnd",
"(... | 46.297297 | 25.918919 |
def make_wheelfile_inner(base_name, base_dir='.'):
"""Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive."""
zip_filename = base_name + ".whl"
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
# Some applications need reproduc... | [
"def",
"make_wheelfile_inner",
"(",
"base_name",
",",
"base_dir",
"=",
"'.'",
")",
":",
"zip_filename",
"=",
"base_name",
"+",
"\".whl\"",
"log",
".",
"info",
"(",
"\"creating '%s' and adding '%s' to it\"",
",",
"zip_filename",
",",
"base_dir",
")",
"# Some applicat... | 36.056604 | 18.735849 |
def load_checkers():
"""Load the checkers"""
for loader, name, _ in pkgutil.iter_modules([os.path.join(__path__[0], 'checkers')]):
loader.find_module(name).load_module(name) | [
"def",
"load_checkers",
"(",
")",
":",
"for",
"loader",
",",
"name",
",",
"_",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"__path__",
"[",
"0",
"]",
",",
"'checkers'",
")",
"]",
")",
":",
"loader",
".",
"... | 46.5 | 19.75 |
def ifftm(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the magnitude of the inverse Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | [
"def",
"ifftm",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"ifft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] | 33.465116 | 24.372093 |
def AgregarDeduccion(self, codigo_concepto=None, detalle_aclaratorio=None,
dias_almacenaje=None, precio_pkg_diario=None,
comision_gastos_adm=None, base_calculo=None,
alicuota=None, **kwargs):
"Agrega la información refe... | [
"def",
"AgregarDeduccion",
"(",
"self",
",",
"codigo_concepto",
"=",
"None",
",",
"detalle_aclaratorio",
"=",
"None",
",",
"dias_almacenaje",
"=",
"None",
",",
"precio_pkg_diario",
"=",
"None",
",",
"comision_gastos_adm",
"=",
"None",
",",
"base_calculo",
"=",
"... | 56.733333 | 21 |
def shutdown(exiting_interpreter=False):
"""Disconnect the worker, and terminate processes started by ray.init().
This will automatically run at the end when a Python process that uses Ray
exits. It is ok to run this twice in a row. The primary use case for this
function is to cleanup state between tes... | [
"def",
"shutdown",
"(",
"exiting_interpreter",
"=",
"False",
")",
":",
"if",
"exiting_interpreter",
"and",
"global_worker",
".",
"mode",
"==",
"SCRIPT_MODE",
":",
"# This is a duration to sleep before shutting down everything in order",
"# to make sure that log messages finish pr... | 40.542857 | 24.514286 |
def make_executable(script_path):
"""Make `script_path` executable.
:param script_path: The file to change
"""
status = os.stat(script_path)
os.chmod(script_path, status.st_mode | stat.S_IEXEC) | [
"def",
"make_executable",
"(",
"script_path",
")",
":",
"status",
"=",
"os",
".",
"stat",
"(",
"script_path",
")",
"os",
".",
"chmod",
"(",
"script_path",
",",
"status",
".",
"st_mode",
"|",
"stat",
".",
"S_IEXEC",
")"
] | 29.714286 | 10.285714 |
def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Used for hooking up the all endpoints (including custom ones), this
returns a wrapper function that creates a new instance of the resource
class & calls the correct view method for it.
:param view_type: Should be one of... | [
"def",
"as_view",
"(",
"cls",
",",
"view_type",
",",
"*",
"init_args",
",",
"*",
"*",
"init_kwargs",
")",
":",
"@",
"wraps",
"(",
"cls",
")",
"def",
"_wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make a new instan... | 38.384615 | 22 |
def _override_sugar(func):
'''Use this decorator to override an attribute that is specified in
blessings' sugar dict with your own function that adds some additional
functionality.
'''
attr_name = func.__name__
@property
@wraps(func)
def func_that_uses_terminal_sugar(self):
func(... | [
"def",
"_override_sugar",
"(",
"func",
")",
":",
"attr_name",
"=",
"func",
".",
"__name__",
"@",
"property",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_that_uses_terminal_sugar",
"(",
"self",
")",
":",
"func",
"(",
"self",
")",
"return",
"self",
".",
"... | 33.166667 | 18.666667 |
def dataset_status_cli(self, dataset, dataset_opt=None):
""" wrapper for client for dataset_status, with additional
dataset_opt to get the status of a dataset from the API
Parameters
==========
dataset_opt: an alternative to dataset
"""
dataset = ... | [
"def",
"dataset_status_cli",
"(",
"self",
",",
"dataset",
",",
"dataset_opt",
"=",
"None",
")",
":",
"dataset",
"=",
"dataset",
"or",
"dataset_opt",
"return",
"self",
".",
"dataset_status",
"(",
"dataset",
")"
] | 42 | 10.111111 |
def are_genes_in_api(my_clue_api_client, gene_symbols):
"""determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols
"""
if len(gene_symbols) > 0:
query_gene_sym... | [
"def",
"are_genes_in_api",
"(",
"my_clue_api_client",
",",
"gene_symbols",
")",
":",
"if",
"len",
"(",
"gene_symbols",
")",
">",
"0",
":",
"query_gene_symbols",
"=",
"gene_symbols",
"if",
"type",
"(",
"gene_symbols",
")",
"is",
"list",
"else",
"list",
"(",
"... | 35.909091 | 27.045455 |
def base36encode(number):
"""Converts an integer into a base36 string."""
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(ALPHABET):
return sign + ALPHABET[number]
while numbe... | [
"def",
"base36encode",
"(",
"number",
")",
":",
"ALPHABET",
"=",
"\"0123456789abcdefghijklmnopqrstuvwxyz\"",
"base36",
"=",
"''",
"sign",
"=",
"''",
"if",
"number",
"<",
"0",
":",
"sign",
"=",
"'-'",
"number",
"=",
"-",
"number",
"if",
"0",
"<=",
"number",... | 21.1 | 21.65 |
def chk_qualifiers(self):
"""Check format of qualifier"""
if self.name == 'id2gos':
return
for ntd in self.associations:
# print(ntd)
qual = ntd.Qualifier
assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(
... | [
"def",
"chk_qualifiers",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
"==",
"'id2gos'",
":",
"return",
"for",
"ntd",
"in",
"self",
".",
"associations",
":",
"# print(ntd)",
"qual",
"=",
"ntd",
".",
"Qualifier",
"assert",
"isinstance",
"(",
"qual",
"... | 40.833333 | 12.916667 |
def tmdb_movies(api_key, id_tmdb, language="en-US", cache=True):
""" Lookup a movie item using The Movie Database
Online docs: developers.themoviedb.org/3/movies
"""
try:
url = "https://api.themoviedb.org/3/movie/%d" % int(id_tmdb)
except ValueError:
raise MapiProviderException("id_... | [
"def",
"tmdb_movies",
"(",
"api_key",
",",
"id_tmdb",
",",
"language",
"=",
"\"en-US\"",
",",
"cache",
"=",
"True",
")",
":",
"try",
":",
"url",
"=",
"\"https://api.themoviedb.org/3/movie/%d\"",
"%",
"int",
"(",
"id_tmdb",
")",
"except",
"ValueError",
":",
"... | 40.111111 | 18.277778 |
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(zip(*[respo... | [
"def",
"sort_return_tuples",
"(",
"response",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"response",
"or",
"not",
"options",
"[",
"'groups'",
"]",
":",
"return",
"response",
"n",
"=",
"options",
"[",
"'groups'",
"]",
"return",
"list",
"(",
"zip",
... | 38 | 12.444444 |
def exists(name, runas=None):
'''
Query whether a VM exists
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exists macvm runas=macdev
... | [
"def",
"exists",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"vm_info",
"=",
"list_vms",
"(",
"name",
",",
"info",
"=",
"True",
",",
"runas",
"=",
"runas",
")",
".",
"splitlines",
"(",
")",
"for",
"info_line",
"in",
"vm_info",
":",
"if",
"'Na... | 21.304348 | 24 |
def find_urls(self, site, frametype, gpsstart, gpsend,
match=None, on_gaps='warn'):
"""Find all files of the given type in the [start, end) GPS interval.
"""
span = Segment(gpsstart, gpsend)
cache = [e for e in self._read_ffl_cache(site, frametype) if
e... | [
"def",
"find_urls",
"(",
"self",
",",
"site",
",",
"frametype",
",",
"gpsstart",
",",
"gpsend",
",",
"match",
"=",
"None",
",",
"on_gaps",
"=",
"'warn'",
")",
":",
"span",
"=",
"Segment",
"(",
"gpsstart",
",",
"gpsend",
")",
"cache",
"=",
"[",
"e",
... | 38.04 | 15.56 |
def execute_task(self, task, workflow_id, data=None):
""" Celery task that runs a single task on a worker.
Args:
self (Task): Reference to itself, the celery task object.
task (BaseTask): Reference to the task object that performs the work
in its run() method.
w... | [
"def",
"execute_task",
"(",
"self",
",",
"task",
",",
"workflow_id",
",",
"data",
"=",
"None",
")",
":",
"start_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"store_doc",
"=",
"DataStore",
"(",
"*",
"*",
"self",
".",
"app",
".",
"user_options",
"[",... | 43.12766 | 20.5 |
def read_body(response, max_bytes=None):
"""Return a `Deferred` yielding at most *max_bytes* bytes from the
body of a Twisted Web *response*, or the whole body if *max_bytes*
is `None`."""
finished = Deferred()
response.deliverBody(TruncatingReadBodyProtocol(
response.code, response.phrase, ... | [
"def",
"read_body",
"(",
"response",
",",
"max_bytes",
"=",
"None",
")",
":",
"finished",
"=",
"Deferred",
"(",
")",
"response",
".",
"deliverBody",
"(",
"TruncatingReadBodyProtocol",
"(",
"response",
".",
"code",
",",
"response",
".",
"phrase",
",",
"finish... | 44.25 | 12.375 |
def default_marshaller(obj):
"""
Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state
"""
if hasattr(obj, '__gets... | [
"def",
"default_marshaller",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__getstate__'",
")",
":",
"return",
"obj",
".",
"__getstate__",
"(",
")",
"try",
":",
"return",
"obj",
".",
"__dict__",
"except",
"AttributeError",
":",
"raise",
"TypeEr... | 29.578947 | 19.789474 |
def lastElementChild(self) -> Optional[AbstractNode]:
"""Last Element child node.
If this node has no element child, return None.
"""
for child in reversed(self.childNodes): # type: ignore
if child.nodeType == Node.ELEMENT_NODE:
return child
return N... | [
"def",
"lastElementChild",
"(",
"self",
")",
"->",
"Optional",
"[",
"AbstractNode",
"]",
":",
"for",
"child",
"in",
"reversed",
"(",
"self",
".",
"childNodes",
")",
":",
"# type: ignore",
"if",
"child",
".",
"nodeType",
"==",
"Node",
".",
"ELEMENT_NODE",
"... | 35 | 15 |
def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
dmdxs = []
... | [
"def",
"predict_withGradients",
"(",
"self",
",",
"X",
")",
":",
"if",
"X",
".",
"ndim",
"==",
"1",
":",
"X",
"=",
"X",
"[",
"None",
",",
":",
"]",
"ps",
"=",
"self",
".",
"model",
".",
"param_array",
".",
"copy",
"(",
")",
"means",
"=",
"[",
... | 35.785714 | 12.071429 |
def estimate_gas(
self,
block_identifier,
function: str,
*args,
**kwargs,
) -> typing.Optional[int]:
"""Returns a gas estimate for the function with the given arguments or
None if the function call will fail due to Insufficient funds or
... | [
"def",
"estimate_gas",
"(",
"self",
",",
"block_identifier",
",",
"function",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"typing",
".",
"Optional",
"[",
"int",
"]",
":",
"fn",
"=",
"getattr",
"(",
"self",
".",
"contract",
... | 43.775 | 20.925 |
def get_pmids(self):
"""Get list of all PMIDs associated with edges in the network."""
pmids = []
for ea in self._edge_attributes.values():
edge_pmids = ea.get('pmids')
if edge_pmids:
pmids += edge_pmids
return list(set(pmids)) | [
"def",
"get_pmids",
"(",
"self",
")",
":",
"pmids",
"=",
"[",
"]",
"for",
"ea",
"in",
"self",
".",
"_edge_attributes",
".",
"values",
"(",
")",
":",
"edge_pmids",
"=",
"ea",
".",
"get",
"(",
"'pmids'",
")",
"if",
"edge_pmids",
":",
"pmids",
"+=",
"... | 36.5 | 9.875 |
def unpack_rpc_response(status, response=None, rpc_id=0, address=0):
"""Unpack an RPC status back in to payload or exception."""
status_code = status & ((1 << 6) - 1)
if address == 8:
status_code &= ~(1 << 7)
if status == 0:
raise BusyRPCResponse()
elif status == 2:
raise ... | [
"def",
"unpack_rpc_response",
"(",
"status",
",",
"response",
"=",
"None",
",",
"rpc_id",
"=",
"0",
",",
"address",
"=",
"0",
")",
":",
"status_code",
"=",
"status",
"&",
"(",
"(",
"1",
"<<",
"6",
")",
"-",
"1",
")",
"if",
"address",
"==",
"8",
"... | 28.086957 | 20.391304 |
def column_max_width(self, column_number):
"""Return the maximum width of a column based on the current terminal width.
:param int column_number: The column number to query.
:return: The max width of the column.
:rtype: int
"""
inner_widths = max_dimensions(self.table_d... | [
"def",
"column_max_width",
"(",
"self",
",",
"column_number",
")",
":",
"inner_widths",
"=",
"max_dimensions",
"(",
"self",
".",
"table_data",
")",
"[",
"0",
"]",
"outer_border",
"=",
"2",
"if",
"self",
".",
"outer_border",
"else",
"0",
"inner_border",
"=",
... | 44.846154 | 19.230769 |
def load_data(self, sess, inputs, state_inputs):
"""Bulk loads the specified inputs into device memory.
The shape of the inputs must conform to the shapes of the input
placeholders this optimizer was constructed with.
The data is split equally across all the devices. If the data is not... | [
"def",
"load_data",
"(",
"self",
",",
"sess",
",",
"inputs",
",",
"state_inputs",
")",
":",
"if",
"log_once",
"(",
"\"load_data\"",
")",
":",
"logger",
".",
"info",
"(",
"\"Training on concatenated sample batches:\\n\\n{}\\n\"",
".",
"format",
"(",
"summarize",
... | 44.305556 | 21.685185 |
def linear_least_squares(a, b, residuals=False):
"""
Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number... | [
"def",
"linear_least_squares",
"(",
"a",
",",
"b",
",",
"residuals",
"=",
"False",
")",
":",
"# Copyright (c) 2013 Alexandre Drouin. All rights reserved.",
"# From https://gist.github.com/aldro61/5889795",
"from",
"warnings",
"import",
"warn",
"# from scipy.linalg.fblas impo... | 41.547619 | 19.738095 |
def search(self, keyword, p_index=''):
'''
perform searching.
'''
if p_index == '' or p_index == '-1':
current_page_number = 1
else:
current_page_number = int(p_index)
res_all = self.ysearch.get_all_num(keyword)
results = self.ysearch.searc... | [
"def",
"search",
"(",
"self",
",",
"keyword",
",",
"p_index",
"=",
"''",
")",
":",
"if",
"p_index",
"==",
"''",
"or",
"p_index",
"==",
"'-1'",
":",
"current_page_number",
"=",
"1",
"else",
":",
"current_page_number",
"=",
"int",
"(",
"p_index",
")",
"r... | 34.83871 | 11.419355 |
def make_client(ip, port, authkey):
"""Create a manager to connect to our server manager
:param ip: ip address of server
:param port: port over which to server
:param authkey: authorization key
"""
QueueManager.register('get_job_q')
QueueManager.register('get_result_q')
QueueManager.re... | [
"def",
"make_client",
"(",
"ip",
",",
"port",
",",
"authkey",
")",
":",
"QueueManager",
".",
"register",
"(",
"'get_job_q'",
")",
"QueueManager",
".",
"register",
"(",
"'get_result_q'",
")",
"QueueManager",
".",
"register",
"(",
"'get_function'",
")",
"QueueMa... | 29.4375 | 12.875 |
def GetDisplayNameForPathSpec(self, path_spec):
"""Retrieves the display name for a path specification.
Args:
path_spec (dfvfs.PathSpec): path specification.
Returns:
str: human readable version of the path specification.
"""
return path_helper.PathHelper.GetDisplayNameForPathSpec(
... | [
"def",
"GetDisplayNameForPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"return",
"path_helper",
".",
"PathHelper",
".",
"GetDisplayNameForPathSpec",
"(",
"path_spec",
",",
"mount_path",
"=",
"self",
".",
"_mount_path",
",",
"text_prepend",
"=",
"self",
".",
... | 35.181818 | 21.727273 |
def list(self, orgId=None, **request_parameters):
"""List all licenses for a given organization.
If no orgId is specified, the default is the organization of the
authenticated user.
Args:
orgId(basestring): Specify the organization, by ID.
**request_parameters: ... | [
"def",
"list",
"(",
"self",
",",
"orgId",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"orgId",
",",
"basestring",
")",
"params",
"=",
"dict_from_items_with_values",
"(",
"request_parameters",
",",
"orgId",
"=",
"orgId",
","... | 34.212121 | 24.30303 |
def Nor(*xs, simplify=True):
"""Expression NOR (not OR) operator
If *simplify* is ``True``, return a simplified expression.
"""
xs = [Expression.box(x).node for x in xs]
y = exprnode.not_(exprnode.or_(*xs))
if simplify:
y = y.simplify()
return _expr(y) | [
"def",
"Nor",
"(",
"*",
"xs",
",",
"simplify",
"=",
"True",
")",
":",
"xs",
"=",
"[",
"Expression",
".",
"box",
"(",
"x",
")",
".",
"node",
"for",
"x",
"in",
"xs",
"]",
"y",
"=",
"exprnode",
".",
"not_",
"(",
"exprnode",
".",
"or_",
"(",
"*",... | 28 | 14 |
def dotprint(
expr, styles=None, maxdepth=None, repeat=True,
labelfunc=expr_labelfunc(str, str),
idfunc=None, get_children=_op_children, **kwargs):
"""Return the `DOT`_ (graph) description of an Expression tree as a string
Args:
expr (object): The expression to render into a gra... | [
"def",
"dotprint",
"(",
"expr",
",",
"styles",
"=",
"None",
",",
"maxdepth",
"=",
"None",
",",
"repeat",
"=",
"True",
",",
"labelfunc",
"=",
"expr_labelfunc",
"(",
"str",
",",
"str",
")",
",",
"idfunc",
"=",
"None",
",",
"get_children",
"=",
"_op_child... | 46.398148 | 23.166667 |
def from_hash(self, hash):
"""Create a `Multihash` from a hashlib-compatible `hash` object.
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> digest = hash.digest()
>>> mh = Multihash.from_hash(hash)
>>> mh == (Func.sha1, digest)
True... | [
"def",
"from_hash",
"(",
"self",
",",
"hash",
")",
":",
"try",
":",
"func",
"=",
"FuncReg",
".",
"func_from_hash",
"(",
"hash",
")",
"except",
"KeyError",
"as",
"ke",
":",
"raise",
"ValueError",
"(",
"\"no matching multihash function\"",
",",
"hash",
".",
... | 32.166667 | 16.375 |
def error(self, message, code=1):
""" Prints the error, and exits with the given code. """
sys.stderr.write(message)
sys.exit(code) | [
"def",
"error",
"(",
"self",
",",
"message",
",",
"code",
"=",
"1",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
")",
"sys",
".",
"exit",
"(",
"code",
")"
] | 38 | 8 |
def create_engine(url, con=None, header=True, show_progress=5.0, clear_progress=True):
'''Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.com)
HT... | [
"def",
"create_engine",
"(",
"url",
",",
"con",
"=",
"None",
",",
"header",
"=",
"True",
",",
"show_progress",
"=",
"5.0",
",",
"clear_progress",
"=",
"True",
")",
":",
"url",
"=",
"urlparse",
"(",
"url",
")",
"engine_type",
"=",
"url",
".",
"scheme",
... | 37.770833 | 21.3125 |
def _add_interval_elevations(self, gpx, min_interval_length=100):
"""
Adds elevation on points every min_interval_length and add missing
elevation between
"""
for track in gpx.tracks:
for segment in track.segments:
last_interval_changed = 0
... | [
"def",
"_add_interval_elevations",
"(",
"self",
",",
"gpx",
",",
"min_interval_length",
"=",
"100",
")",
":",
"for",
"track",
"in",
"gpx",
".",
"tracks",
":",
"for",
"segment",
"in",
"track",
".",
"segments",
":",
"last_interval_changed",
"=",
"0",
"previous... | 44.571429 | 16.952381 |
def get_table_acl(self, table_name, timeout=None):
'''
Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The se... | [
"def",
"get_table_acl",
"(",
"self",
",",
"table_name",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'table_name'",
",",
"table_name",
")",
"request",
"=",
"HTTPRequest",
"(",
")",
"request",
".",
"method",
"=",
"'GET'",
"request",
".",... | 38.708333 | 18.625 |
def command(self, c):
"""Send command byte to display."""
if self._spi is not None:
# SPI write.
self._gpio.set_low(self._dc)
self._spi.write([c])
else:
# I2C write.
control = 0x00 # Co = 0, DC = 0
self._i2c.write8(control... | [
"def",
"command",
"(",
"self",
",",
"c",
")",
":",
"if",
"self",
".",
"_spi",
"is",
"not",
"None",
":",
"# SPI write.",
"self",
".",
"_gpio",
".",
"set_low",
"(",
"self",
".",
"_dc",
")",
"self",
".",
"_spi",
".",
"write",
"(",
"[",
"c",
"]",
"... | 31.5 | 9.8 |
def patch_instance(self, body, instance, project_id=None):
"""
Updates settings of a Cloud SQL instance.
Caution: This is not a partial update, so you must include values for
all the settings that you want to retain.
:param body: Body required by the Cloud SQL patch API, as des... | [
"def",
"patch_instance",
"(",
"self",
",",
"body",
",",
"instance",
",",
"project_id",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"get_conn",
"(",
")",
".",
"instances",
"(",
")",
".",
"patch",
"(",
"project",
"=",
"project_id",
",",
"instanc... | 46.28 | 22.76 |
def client(self, *args, **kwargs):
"""
Get Client
Get information about a single client.
This method gives output: ``v1/get-client-response.json#``
This method is ``stable``
"""
return self._makeApiCall(self.funcinfo["client"], *args, **kwargs) | [
"def",
"client",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"client\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 24.416667 | 21.75 |
def _void_array_to_nested_list(res, _func, _args):
""" Dereference the FFI result to a list of coordinates """
try:
shape = res.coords.len, 2
ptr = cast(res.coords.data, POINTER(c_double))
array = np.ctypeslib.as_array(ptr, shape)
return array.tolist()
finally:
drop_a... | [
"def",
"_void_array_to_nested_list",
"(",
"res",
",",
"_func",
",",
"_args",
")",
":",
"try",
":",
"shape",
"=",
"res",
".",
"coords",
".",
"len",
",",
"2",
"ptr",
"=",
"cast",
"(",
"res",
".",
"coords",
".",
"data",
",",
"POINTER",
"(",
"c_double",
... | 36.444444 | 13.444444 |
def prepare_static_data(self, data):
"""
If user defined static fields, then process them with visiable value
"""
d = self.obj.to_dict()
d.update(data.copy())
for f in self.get_fields():
if f['static'] and f['name'] in d:
v = make_view_... | [
"def",
"prepare_static_data",
"(",
"self",
",",
"data",
")",
":",
"d",
"=",
"self",
".",
"obj",
".",
"to_dict",
"(",
")",
"d",
".",
"update",
"(",
"data",
".",
"copy",
"(",
")",
")",
"for",
"f",
"in",
"self",
".",
"get_fields",
"(",
")",
":",
"... | 41.272727 | 15.454545 |
def is_valid_aesthetic(value, ae):
"""
Return True if `value` looks valid.
Parameters
----------
value : object
Value to check
ae : str
Aesthetic name
Returns
-------
out : bool
Whether the value is of a valid looking form.
Notes
-----
There are... | [
"def",
"is_valid_aesthetic",
"(",
"value",
",",
"ae",
")",
":",
"if",
"ae",
"==",
"'linetype'",
":",
"named",
"=",
"{",
"'solid'",
",",
"'dashed'",
",",
"'dashdot'",
",",
"'dotted'",
",",
"'_'",
",",
"'--'",
",",
"'-.'",
",",
"':'",
",",
"'None'",
",... | 27.19697 | 18.772727 |
def _polling_iteration(self):
""" :meth:`.WPollingThreadTask._polling_iteration` implementation
"""
if len(self.__task_chain) > 0:
if self.__current_task is None:
self.__current_task = 0
task = self.__task_chain[self.__current_task]
if task.thread() is None:
task.start()
elif task.ready_event... | [
"def",
"_polling_iteration",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__task_chain",
")",
">",
"0",
":",
"if",
"self",
".",
"__current_task",
"is",
"None",
":",
"self",
".",
"__current_task",
"=",
"0",
"task",
"=",
"self",
".",
"__task_ch... | 29.85 | 14.05 |
def find_egg_entry_point(self, object_type, name=None):
"""
Returns the (entry_point, protocol) for the with the given
``name``.
"""
if name is None:
name = 'main'
possible = []
for protocol_options in object_type.egg_protocols:
for protoco... | [
"def",
"find_egg_entry_point",
"(",
"self",
",",
"object_type",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'main'",
"possible",
"=",
"[",
"]",
"for",
"protocol_options",
"in",
"object_type",
".",
"egg_protocols",
":"... | 42.028571 | 16.028571 |
def pypi():
'''Build package and upload to pypi.'''
if not query_yes_no('version updated in '
'`fabsetup/_version.py`?'):
print('abort')
else:
print(cyan('\n## clean-up\n'))
execute(clean)
basedir = dirname(__file__)
# latest_pythons = _deter... | [
"def",
"pypi",
"(",
")",
":",
"if",
"not",
"query_yes_no",
"(",
"'version updated in '",
"'`fabsetup/_version.py`?'",
")",
":",
"print",
"(",
"'abort'",
")",
"else",
":",
"print",
"(",
"cyan",
"(",
"'\\n## clean-up\\n'",
")",
")",
"execute",
"(",
"clean",
")... | 32.5 | 18.045455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.