text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
async def get_cred_def_id(self):
"""
Get the ledger ID of the object
Example:
source_id = 'foobar123'
schema_name = 'Schema Name'
payment_handle = 0
credential_def1 = await CredentialDef.create(source_id, name, schema_id, payment_handle)
assert await cred... | [
"async",
"def",
"get_cred_def_id",
"(",
"self",
")",
":",
"cb",
"=",
"create_cb",
"(",
"CFUNCTYPE",
"(",
"None",
",",
"c_uint32",
",",
"c_uint32",
",",
"c_char_p",
")",
")",
"c_handle",
"=",
"c_uint32",
"(",
"self",
".",
"handle",
")",
"cred_def_id",
"="... | 40.3125 | 18.8125 |
def cgnr_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter,
tol, weighting='local', Cpt_params=None):
"""Use CGNR to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SPD s... | [
"def",
"cgnr_prolongation_smoothing",
"(",
"A",
",",
"T",
",",
"B",
",",
"BtBinv",
",",
"Sparsity_Pattern",
",",
"maxiter",
",",
"tol",
",",
"weighting",
"=",
"'local'",
",",
"Cpt_params",
"=",
"None",
")",
":",
"# For non-SPD system, apply CG on Normal Equations ... | 38.412791 | 22.325581 |
def transport_connected(self):
"""Called when transport has been connected.
Send the stream head if initiator.
"""
with self.lock:
if self.initiator:
if self._output_state is None:
self._initiate() | [
"def",
"transport_connected",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"initiator",
":",
"if",
"self",
".",
"_output_state",
"is",
"None",
":",
"self",
".",
"_initiate",
"(",
")"
] | 30 | 9.888889 |
def usage_palette(parser):
"""Show usage and available palettes."""
parser.print_usage()
print('')
print('available palettes:')
for palette in sorted(PALETTE):
print(' %-12s' % (palette,))
return 0 | [
"def",
"usage_palette",
"(",
"parser",
")",
":",
"parser",
".",
"print_usage",
"(",
")",
"print",
"(",
"''",
")",
"print",
"(",
"'available palettes:'",
")",
"for",
"palette",
"in",
"sorted",
"(",
"PALETTE",
")",
":",
"print",
"(",
"' %-12s'",
"%",
"(... | 25 | 15.444444 |
def _store_documentation(self, path, html, overwrite, quiet):
"""
Stores all documents on the file system.
Target location is **path**. File name is the lowercase name of the document + .rst.
"""
echo("Storing groundwork application documents\n")
echo("Application: %s" ... | [
"def",
"_store_documentation",
"(",
"self",
",",
"path",
",",
"html",
",",
"overwrite",
",",
"quiet",
")",
":",
"echo",
"(",
"\"Storing groundwork application documents\\n\"",
")",
"echo",
"(",
"\"Application: %s\"",
"%",
"self",
".",
"app",
".",
"name",
")",
... | 36.769231 | 21.261538 |
def load_plugins(self, plugin_class_name):
"""
load all available plugins
:param plugin_class_name: str, name of plugin class (e.g. 'PreBuildPlugin')
:return: dict, bindings for plugins of the plugin_class_name class
"""
# imp.findmodule('atomic_reactor') doesn't work
... | [
"def",
"load_plugins",
"(",
"self",
",",
"plugin_class_name",
")",
":",
"# imp.findmodule('atomic_reactor') doesn't work",
"plugins_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'plugins'",
")",
... | 48.347826 | 18.826087 |
def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterati... | [
"def",
"_getSmallestDifference",
"(",
"inputList",
",",
"targetVal",
")",
":",
"targetList",
"=",
"inputList",
"[",
":",
"]",
"retVal",
"=",
"None",
"while",
"True",
":",
"# If we're down to one value, stop iterating",
"if",
"len",
"(",
"targetList",
")",
"==",
... | 30.818182 | 17.787879 |
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns the most played tracks as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)
seq = []
for nod... | [
"def",
"get_top_tracks",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"{",
"}",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"chart.g... | 33.555556 | 19.777778 |
def set_precision(cls, precision):
"""Set the number of decimal places used to report percentages."""
assert 0 <= precision < 10
cls._precision = precision
cls._near0 = 1.0 / 10**precision
cls._near100 = 100.0 - cls._near0 | [
"def",
"set_precision",
"(",
"cls",
",",
"precision",
")",
":",
"assert",
"0",
"<=",
"precision",
"<",
"10",
"cls",
".",
"_precision",
"=",
"precision",
"cls",
".",
"_near0",
"=",
"1.0",
"/",
"10",
"**",
"precision",
"cls",
".",
"_near100",
"=",
"100.0... | 42.833333 | 3.166667 |
def run(self):
"""Compile libfaketime."""
if sys.platform == "linux" or sys.platform == "linux2":
libname = 'libfaketime.so.1'
libnamemt = 'libfaketimeMT.so.1'
elif sys.platform == "darwin":
libname = 'libfaketime.1.dylib'
libnamemt = 'libfaketimeM... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"linux\"",
"or",
"sys",
".",
"platform",
"==",
"\"linux2\"",
":",
"libname",
"=",
"'libfaketime.so.1'",
"libnamemt",
"=",
"'libfaketimeMT.so.1'",
"elif",
"sys",
".",
"platform",
"==",... | 36.591837 | 19.040816 |
def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches an album by given ID.
:param album_id: the album ID.
:type album_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.... | [
"def",
"fetch_album",
"(",
"self",
",",
"album_id",
",",
"terr",
"=",
"KKBOXTerritory",
".",
"TAIWAN",
")",
":",
"url",
"=",
"'https://api.kkbox.com/v1.1/albums/%s'",
"%",
"album_id",
"url",
"+=",
"'?'",
"+",
"url_parse",
".",
"urlencode",
"(",
"{",
"'territor... | 37.333333 | 22.133333 |
def getBucketInfo(self, buckets):
"""See the function description in base.py"""
return [EncoderResult(value=0, scalar=0, encoding=numpy.zeros(self.n))] | [
"def",
"getBucketInfo",
"(",
"self",
",",
"buckets",
")",
":",
"return",
"[",
"EncoderResult",
"(",
"value",
"=",
"0",
",",
"scalar",
"=",
"0",
",",
"encoding",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"n",
")",
")",
"]"
] | 52.333333 | 14 |
def create_instance(self, nova, image_name, instance_name, flavor):
"""Create the specified instance."""
self.log.debug('Creating instance '
'({}|{}|{})'.format(instance_name, image_name, flavor))
image = nova.glance.find_image(image_name)
flavor = nova.flavors.fin... | [
"def",
"create_instance",
"(",
"self",
",",
"nova",
",",
"image_name",
",",
"instance_name",
",",
"flavor",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating instance '",
"'({}|{}|{})'",
".",
"format",
"(",
"instance_name",
",",
"image_name",
",",
... | 38.347826 | 18.347826 |
def sasutil(self) -> 'SASutil':
"""
This methods creates a SASutil object which you can use to run various analytics.
See the sasutil.py module.
:return: sasutil object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
... | [
"def",
"sasutil",
"(",
"self",
")",
"->",
"'SASutil'",
":",
"if",
"not",
"self",
".",
"_loaded_macros",
":",
"self",
".",
"_loadmacros",
"(",
")",
"self",
".",
"_loaded_macros",
"=",
"True",
"return",
"SASutil",
"(",
"self",
")"
] | 28.166667 | 15.166667 |
def verify_signature(self, addr):
"""
Given an address, verify whether or not it was signed by it
"""
return verify(virtualchain.address_reencode(addr), self.get_plaintext_to_sign(), self.sig) | [
"def",
"verify_signature",
"(",
"self",
",",
"addr",
")",
":",
"return",
"verify",
"(",
"virtualchain",
".",
"address_reencode",
"(",
"addr",
")",
",",
"self",
".",
"get_plaintext_to_sign",
"(",
")",
",",
"self",
".",
"sig",
")"
] | 44 | 18.4 |
def _ordered_keys(dict_):
"""
:param dict_: dict of OrderedDict to be processed
:return: list of str of keys in the original order
or in alphabetical order
"""
return isinstance(dict_, OrderedDict) and dict_.keys() or \
dict_ and sorted(dict_.keys()) or... | [
"def",
"_ordered_keys",
"(",
"dict_",
")",
":",
"return",
"isinstance",
"(",
"dict_",
",",
"OrderedDict",
")",
"and",
"dict_",
".",
"keys",
"(",
")",
"or",
"dict_",
"and",
"sorted",
"(",
"dict_",
".",
"keys",
"(",
")",
")",
"or",
"[",
"]"
] | 39.5 | 11.5 |
def closenessScores(self, expValues, actValues, fractional=True):
"""
See the function description in base.py
"""
# Compute the percent error in log space
if expValues[0] > 0:
expValue = math.log10(expValues[0])
else:
expValue = self.minScaledValue
if actValues [0] > 0:
... | [
"def",
"closenessScores",
"(",
"self",
",",
"expValues",
",",
"actValues",
",",
"fractional",
"=",
"True",
")",
":",
"# Compute the percent error in log space",
"if",
"expValues",
"[",
"0",
"]",
">",
"0",
":",
"expValue",
"=",
"math",
".",
"log10",
"(",
"exp... | 27.862069 | 16.275862 |
def connect_mysql(host, port, user, password, database):
"""Connect to MySQL with retries."""
return pymysql.connect(
host=host, port=port,
user=user, passwd=password,
db=database
) | [
"def",
"connect_mysql",
"(",
"host",
",",
"port",
",",
"user",
",",
"password",
",",
"database",
")",
":",
"return",
"pymysql",
".",
"connect",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"user",
"=",
"user",
",",
"passwd",
"=",
"passwor... | 30.142857 | 14.428571 |
def _generatePermEncoderStr(options, encoderDict):
""" Generate the string that defines the permutations to apply for a given
encoder.
Parameters:
-----------------------------------------------------------------------
options: experiment params
encoderDict: the encoder dict, which gets placed into the des... | [
"def",
"_generatePermEncoderStr",
"(",
"options",
",",
"encoderDict",
")",
":",
"permStr",
"=",
"\"\"",
"# If it's the encoder for the classifier input, then it's always present so",
"# put it in as a dict in the permutations.py file instead of a",
"# PermuteEncoder().",
"if",
"encoder... | 32.135338 | 19.165414 |
def animation(self, animation):
"""Setter for animation property.
Parameters
----------
animation: str
Defines the animation of the spinner
"""
self._animation = animation
self._text = self._get_text(self._text['original']) | [
"def",
"animation",
"(",
"self",
",",
"animation",
")",
":",
"self",
".",
"_animation",
"=",
"animation",
"self",
".",
"_text",
"=",
"self",
".",
"_get_text",
"(",
"self",
".",
"_text",
"[",
"'original'",
"]",
")"
] | 31.444444 | 11.444444 |
def load(self, size):
"""open and read the file is existent"""
if self.exists() and self.isfile():
return eval(open(self).read(size)) | [
"def",
"load",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"exists",
"(",
")",
"and",
"self",
".",
"isfile",
"(",
")",
":",
"return",
"eval",
"(",
"open",
"(",
"self",
")",
".",
"read",
"(",
"size",
")",
")"
] | 39.5 | 7 |
def add_field(self, field):
"""
Adds a field to this table
:param field: This can be a string of a field name, a dict of {'alias': field}, or
a ``Field`` instance
:type field: str or dict or Field
"""
field = FieldFactory(
field,
)
... | [
"def",
"add_field",
"(",
"self",
",",
"field",
")",
":",
"field",
"=",
"FieldFactory",
"(",
"field",
",",
")",
"field",
".",
"set_table",
"(",
"self",
")",
"# make sure field is not already added",
"field_name",
"=",
"field",
".",
"get_name",
"(",
")",
"for"... | 26.538462 | 16.923077 |
def _on_process_finished(self):
"""
Write the process finished message and emit the `finished` signal.
"""
exit_code = self._process.exitCode()
if self._process.exitStatus() != self._process.NormalExit:
exit_code = 139
self._formatter.append_message('\x1b[0m\n... | [
"def",
"_on_process_finished",
"(",
"self",
")",
":",
"exit_code",
"=",
"self",
".",
"_process",
".",
"exitCode",
"(",
")",
"if",
"self",
".",
"_process",
".",
"exitStatus",
"(",
")",
"!=",
"self",
".",
"_process",
".",
"NormalExit",
":",
"exit_code",
"=... | 46 | 17.818182 |
def convert_pkt_to_json(pkg):
""" convert_pkt_to_json
Inspired by:
https://gist.githubusercontent.com/cr0hn/1b0c2e672cd0721d3a07/raw/9144676ceb12dbd545e6dce366822bbedde8de2c/pkg_to_json.py
This function convert a Scapy packet to JSON
:param pkg: A kamene package
:type pkg: objects
:return:... | [
"def",
"convert_pkt_to_json",
"(",
"pkg",
")",
":",
"results",
"=",
"defaultdict",
"(",
"dict",
")",
"try",
":",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"pkg",
")",
")",
":",
"layer",
"=",
"pkg",
"[",
"index",
"]",
"# Get layer name... | 41.112903 | 16.185484 |
def async_call(self, fn, *args, **kwargs):
"""Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, ... | [
"def",
"async_call",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"call_point",
"=",
"''",
".",
"join",
"(",
"format_stack",
"(",
"None",
",",
"5",
")",
"[",
":",
"-",
"1",
"]",
")",
"def",
"handler",
"(",
")",
... | 39.681818 | 18.318182 |
def _set_nameserver_fc4s(self, v, load=False):
"""
Setter method for nameserver_fc4s, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_fc4s (nameserver-fc4s-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nam... | [
"def",
"_set_nameserver_fc4s",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 78.44 | 38.96 |
def start(self):
"""
Starts this router.
At least the IOS image must be set before starting it.
"""
# trick: we must send sensors and power supplies info after starting the router
# otherwise they are not taken into account (Dynamips bug?)
yield from Router.start... | [
"def",
"start",
"(",
"self",
")",
":",
"# trick: we must send sensors and power supplies info after starting the router",
"# otherwise they are not taken into account (Dynamips bug?)",
"yield",
"from",
"Router",
".",
"start",
"(",
"self",
")",
"if",
"self",
".",
"_sensors",
"... | 40.538462 | 17.307692 |
def server_by_name(name, profile=None, **kwargs):
'''
Return information about a server
name
Server Name
CLI Example:
.. code-block:: bash
salt '*' nova.server_by_name myserver profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.server_by_name(name) | [
"def",
"server_by_name",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"server_by_name",
"(",
"name",
")"
] | 20.066667 | 24.2 |
def list_dirnames_in_directory(self, dirname):
"""List all names of directories that exist at the root of this
bucket directory.
Note that *directories* don't exist in S3; rather directories are
inferred from path names.
Parameters
----------
dirname : `str`
... | [
"def",
"list_dirnames_in_directory",
"(",
"self",
",",
"dirname",
")",
":",
"prefix",
"=",
"self",
".",
"_create_prefix",
"(",
"dirname",
")",
"dirnames",
"=",
"[",
"]",
"for",
"obj",
"in",
"self",
".",
"_bucket",
".",
"objects",
".",
"filter",
"(",
"Pre... | 38.5 | 20.423077 |
def find_segments(stops, shape):
"""Find corresponding shape points for a list of stops and create shape break points.
Parameters
----------
stops: stop-sequence (list)
List of stop points
shape: list of shape points
shape-sequence of shape points
Returns
-------
break_... | [
"def",
"find_segments",
"(",
"stops",
",",
"shape",
")",
":",
"if",
"not",
"shape",
":",
"return",
"[",
"]",
",",
"0",
"break_points",
"=",
"[",
"]",
"last_i",
"=",
"0",
"cumul_d",
"=",
"0",
"badness",
"=",
"0",
"d_last_stop",
"=",
"float",
"(",
"'... | 36.453333 | 16.826667 |
def _ResolvePath(self, path, expand_variables=True):
"""Resolves a Windows path in file system specific format.
This function will check if the individual path segments exists within
the file system. For this it will prefer the first case sensitive match
above a case insensitive match. If no match was ... | [
"def",
"_ResolvePath",
"(",
"self",
",",
"path",
",",
"expand_variables",
"=",
"True",
")",
":",
"# Allow for paths that start with an environment variable e.g.",
"# %SystemRoot%\\file.txt",
"if",
"path",
".",
"startswith",
"(",
"'%'",
")",
":",
"path_segment",
",",
"... | 37.292683 | 19.914634 |
def _parse_attribute_details_file(self, prop=ATTRIBUTES):
""" Concatenates a list of Attribute Details data structures parsed from a remote file """
# Parse content from remote file URL, which may be stored in one of two places:
# Starting at: contentInfo/MD_FeatureCatalogueDescription/featu... | [
"def",
"_parse_attribute_details_file",
"(",
"self",
",",
"prop",
"=",
"ATTRIBUTES",
")",
":",
"# Parse content from remote file URL, which may be stored in one of two places:",
"# Starting at: contentInfo/MD_FeatureCatalogueDescription/featureCatalogueCitation",
"# ATTRIBUTE: href",
... | 42.083333 | 26.333333 |
def apply_with(self, _, val, ctx):
""" constructor
example val:
{
# header values used in multipart/form-data according to RFC2388
'header': {
'Content-Type': 'text/plain',
# according to RFC2388, available values are '7bi... | [
"def",
"apply_with",
"(",
"self",
",",
"_",
",",
"val",
",",
"ctx",
")",
":",
"self",
".",
"header",
"=",
"val",
".",
"get",
"(",
"'header'",
",",
"{",
"}",
")",
"self",
".",
"data",
"=",
"val",
".",
"get",
"(",
"'data'",
",",
"None",
")",
"s... | 35 | 18.52 |
def _get_tough_method(self, method):
"""Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restart... | [
"def",
"_get_tough_method",
"(",
"self",
",",
"method",
")",
":",
"def",
"tough_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"transaction",
"=",
"self",
".",
"_transaction",
"if",
"not",
"transaction",
":",
"try",
":",
"# check whether con... | 46.393939 | 16.818182 |
def load_classifier():
"""Train the intent classifier."""
path = os.path.join(l.TOPDIR, 'clf.pickle')
obj = pickle.load(open(path, 'r'))
return obj['tfidf_model'], obj['clf'], obj['target_names'] | [
"def",
"load_classifier",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"l",
".",
"TOPDIR",
",",
"'clf.pickle'",
")",
"obj",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"path",
",",
"'r'",
")",
")",
"return",
"obj",
"[",
"'tf... | 34.5 | 14.833333 |
def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... | [
"def",
"is_terminal",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"bool",
":",
"# We special-case 'lambda' here because it behaves weirdly in action sequences.",
"return",
"(",
"symbol",
"in",
"self",
".",
"global_name_mapping",
"or",
"symbol",
"in",
"self",
".... | 53.9 | 20.7 |
def namespaced_function(function, global_dict, defaults=None, preserve_context=False):
'''
Redefine (clone) a function under a different globals() namespace scope
preserve_context:
Allow keeping the context taken from orignal namespace,
and extend it with globals() taken from
... | [
"def",
"namespaced_function",
"(",
"function",
",",
"global_dict",
",",
"defaults",
"=",
"None",
",",
"preserve_context",
"=",
"False",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"function",
".",
"__defaults__",
"if",
"preserve_context",
"... | 34.16 | 18.64 |
def run_vcs_tool(path, action):
"""If path is a valid VCS repository, run the corresponding VCS tool
Supported VCS actions: 'commit', 'browse'
Return False if the VCS tool is not installed"""
info = get_vcs_info(get_vcs_root(path))
tools = info['actions'][action]
for tool, args in tools:
... | [
"def",
"run_vcs_tool",
"(",
"path",
",",
"action",
")",
":",
"info",
"=",
"get_vcs_info",
"(",
"get_vcs_root",
"(",
"path",
")",
")",
"tools",
"=",
"info",
"[",
"'actions'",
"]",
"[",
"action",
"]",
"for",
"tool",
",",
"args",
"in",
"tools",
":",
"if... | 40.25 | 10.875 |
def motif3funct_wei(W):
'''
Functional motifs are subsets of connection patterns embedded within
anatomical motifs. Motif frequency is the frequency of occurrence of
motifs around a node. Motif intensity and coherence are weighted
generalizations of motif frequency.
Parameters
----------
... | [
"def",
"motif3funct_wei",
"(",
"W",
")",
":",
"from",
"scipy",
"import",
"io",
"import",
"os",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"motiflib",
")",
"mot",
"=",
"io",
".",
... | 33.01087 | 18.728261 |
def get_absorbing_atom_symbol_index(absorbing_atom, structure):
"""
Return the absorbing atom symboll and site index in the given structure.
Args:
absorbing_atom (str/int): symbol or site index
structure (Structure)
Returns:
str, int: symbol and site index
"""
if isinst... | [
"def",
"get_absorbing_atom_symbol_index",
"(",
"absorbing_atom",
",",
"structure",
")",
":",
"if",
"isinstance",
"(",
"absorbing_atom",
",",
"str",
")",
":",
"return",
"absorbing_atom",
",",
"structure",
".",
"indices_from_symbol",
"(",
"absorbing_atom",
")",
"[",
... | 36.294118 | 21.705882 |
def _coerceSingleRepetition(self, dataSet):
"""
Make a new liveform with our parameters, and get it to coerce our data
for us.
"""
# make a liveform because there is some logic in _coerced
form = LiveForm(lambda **k: None, self.parameters, self.name)
return form.f... | [
"def",
"_coerceSingleRepetition",
"(",
"self",
",",
"dataSet",
")",
":",
"# make a liveform because there is some logic in _coerced",
"form",
"=",
"LiveForm",
"(",
"lambda",
"*",
"*",
"k",
":",
"None",
",",
"self",
".",
"parameters",
",",
"self",
".",
"name",
")... | 41.375 | 15.125 |
def alias_exists(aliases, indices=None, hosts=None, profile=None):
'''
Return a boolean indicating whether given alias exists
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example:... | [
"def",
"alias_exists",
"(",
"aliases",
",",
"indices",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"return",
"es",
".",
"indices",
".",
"exi... | 38.7 | 31 |
def spkpos(targ, et, ref, abcorr, obs):
"""
Return the position of a target body relative to an observing
body, optionally corrected for light time (planetary aberration)
and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpos_c.html
:param targ: Target body name... | [
"def",
"spkpos",
"(",
"targ",
",",
"et",
",",
"ref",
",",
"abcorr",
",",
"obs",
")",
":",
"targ",
"=",
"stypes",
".",
"stringToCharP",
"(",
"targ",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"abcorr",
"=",
"stypes",
".",
"str... | 34.170732 | 15.97561 |
def get_default_config(self):
""" Returns the default collector settings
"""
config = super(IPCollector, self).get_default_config()
config.update({
'path': 'ip',
'allowed_names': 'InAddrErrors, InDelivers, InDiscards, ' +
'InHdrErrors, InReceives, InUn... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"IPCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'ip'",
",",
"'allowed_names'",
":",
"'InAddrErrors, InDe... | 37.363636 | 16.181818 |
def loadtitlefont(self):
"""Auxiliary method to load font if not yet done."""
if self.titlefont == None:
# print 'the bloody fonts dir is????', fontsdir
# print 'pero esto que hace??', os.path.join(fontsdir, "courR18.pil")
# /home/vital/Workspace/pyResources/Scientifi... | [
"def",
"loadtitlefont",
"(",
"self",
")",
":",
"if",
"self",
".",
"titlefont",
"==",
"None",
":",
"# print 'the bloody fonts dir is????', fontsdir",
"# print 'pero esto que hace??', os.path.join(fontsdir, \"courR18.pil\")",
"# /home/vital/Workspace/p... | 63.25 | 26.25 |
def writeObject(self, obj, output, setReferencePosition=False):
"""Serializes the given object to the output. Returns output.
If setReferencePosition is True, will set the position the
object was written.
"""
def proc_variable_length(format, length):
result = b'... | [
"def",
"writeObject",
"(",
"self",
",",
"obj",
",",
"output",
",",
"setReferencePosition",
"=",
"False",
")",
":",
"def",
"proc_variable_length",
"(",
"format",
",",
"length",
")",
":",
"result",
"=",
"b''",
"if",
"length",
">",
"0b1110",
":",
"result",
... | 45 | 15.391304 |
def display(self, content = None, **settings):
"""
Perform widget rendering and output the result.
"""
lines = self.render(content, **settings)
for l in lines:
print(l) | [
"def",
"display",
"(",
"self",
",",
"content",
"=",
"None",
",",
"*",
"*",
"settings",
")",
":",
"lines",
"=",
"self",
".",
"render",
"(",
"content",
",",
"*",
"*",
"settings",
")",
"for",
"l",
"in",
"lines",
":",
"print",
"(",
"l",
")"
] | 30.571429 | 9.428571 |
def LinearContrast(alpha=1, per_channel=False, name=None, deterministic=False, random_state=None):
"""Adjust contrast by scaling each pixel value to ``127 + alpha*(I_ij-127)``.
dtype support::
See :func:`imgaug.augmenters.contrast.adjust_contrast_linear`.
Parameters
----------
alpha : num... | [
"def",
"LinearContrast",
"(",
"alpha",
"=",
"1",
",",
"per_channel",
"=",
"False",
",",
"name",
"=",
"None",
",",
"deterministic",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
"params1d",
"=",
"[",
"iap",
".",
"handle_continuous_param",
"(",
... | 44.480769 | 30.673077 |
def prepack(self, namedstruct, skip_self=False, skip_sub=False):
'''
Run prepack
'''
if not skip_sub and hasattr(namedstruct, self.name) and hasattr(self.basetypeparser, 'fullprepack'):
self.basetypeparser.fullprepack(getattr(namedstruct, self.name))
Parser.prepack(se... | [
"def",
"prepack",
"(",
"self",
",",
"namedstruct",
",",
"skip_self",
"=",
"False",
",",
"skip_sub",
"=",
"False",
")",
":",
"if",
"not",
"skip_sub",
"and",
"hasattr",
"(",
"namedstruct",
",",
"self",
".",
"name",
")",
"and",
"hasattr",
"(",
"self",
"."... | 50.142857 | 32.714286 |
def config_filename(filename):
"""
Obtains the first filename found that is included in one of the configuration folders.
This function returs the full path for the file.
* It is useful for files that are not config-formatted (e.g. hosts files, json, etc.)
that will be rea... | [
"def",
"config_filename",
"(",
"filename",
")",
":",
"global",
"_ETC_PATHS",
"if",
"filename",
".",
"startswith",
"(",
"'/'",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"using absolute path for filename \\\"%s\\\"\"",
"%",
"filename",
")",
"return",
"filename",
"imp... | 39.565217 | 22.434783 |
def geo_name(self):
"""
Return a name of the state or county, or, for other lowever levels, the
name of the level type in the county.
:return:
"""
if self.level == 'county':
return str(self.county_name)
elif self.level == 'state':
return ... | [
"def",
"geo_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"level",
"==",
"'county'",
":",
"return",
"str",
"(",
"self",
".",
"county_name",
")",
"elif",
"self",
".",
"level",
"==",
"'state'",
":",
"return",
"self",
".",
"state_name",
"else",
":",
... | 28.363636 | 19.454545 |
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
... | [
"def",
"circular",
"(",
"cls",
",",
"shape",
",",
"pixel_scale",
",",
"radius_arcsec",
",",
"centre",
"=",
"(",
"0.",
",",
"0.",
")",
",",
"invert",
"=",
"False",
")",
":",
"mask",
"=",
"mask_util",
".",
"mask_circular_from_shape_pixel_scale_and_radius",
"("... | 50.722222 | 23.5 |
def _jobresult(self, jobid, json=True, headers=None):
"""Poll the async job result.
To be run via in a Thread, the result is put within
the result list which is a hack.
"""
failures = 0
total_time = self.job_timeout or 2**30
remaining = timedelta(seconds=total_t... | [
"def",
"_jobresult",
"(",
"self",
",",
"jobid",
",",
"json",
"=",
"True",
",",
"headers",
"=",
"None",
")",
":",
"failures",
"=",
"0",
"total_time",
"=",
"self",
".",
"job_timeout",
"or",
"2",
"**",
"30",
"remaining",
"=",
"timedelta",
"(",
"seconds",
... | 38.382716 | 19.098765 |
def taskfileinfo_task_data(tfi, role):
"""Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype:... | [
"def",
"taskfileinfo_task_data",
"(",
"tfi",
",",
"role",
")",
":",
"task",
"=",
"tfi",
".",
"task",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"return",
"task",
".",
"n... | 33.142857 | 15.142857 |
def delete_answer(self, answer_id):
"""Deletes the ``Answer`` identified by the given ``Id``.
arg: answer_id (osid.id.Id): the ``Id`` of the ``Answer`` to
delete
raise: NotFound - an ``Answer`` was not found identified by the
given ``Id``
raise: Null... | [
"def",
"delete_answer",
"(",
"self",
",",
"answer_id",
")",
":",
"# Implemented from template for",
"# osid.repository.AssetAdminSession.delete_asset_content_template",
"from",
"dlkit",
".",
"abstract_osid",
".",
"id",
".",
"primitives",
"import",
"Id",
"as",
"ABCId",
"fr... | 42.315789 | 18.526316 |
def yaml_tag_constructor(loader, tag, node):
"""convert shorthand intrinsic function to full name
"""
def _f(loader, tag, node):
if tag == '!GetAtt':
return node.value.split('.')
elif type(node) == yaml.SequenceNode:
return loader.construct_sequence(node)
else... | [
"def",
"yaml_tag_constructor",
"(",
"loader",
",",
"tag",
",",
"node",
")",
":",
"def",
"_f",
"(",
"loader",
",",
"tag",
",",
"node",
")",
":",
"if",
"tag",
"==",
"'!GetAtt'",
":",
"return",
"node",
".",
"value",
".",
"split",
"(",
"'.'",
")",
"eli... | 27.529412 | 13.705882 |
def render_html(self, obj, context=None):
"""
Generate the 'html' attribute of an oembed resource using a template.
Sort of a corollary to the parser's render_oembed method. By default,
the current mapping will be passed in as the context.
OEmbed templates are stored in... | [
"def",
"render_html",
"(",
"self",
",",
"obj",
",",
"context",
"=",
"None",
")",
":",
"provided_context",
"=",
"context",
"or",
"Context",
"(",
")",
"context",
"=",
"RequestContext",
"(",
"mock_request",
"(",
")",
")",
"context",
".",
"update",
"(",
"pro... | 34.347826 | 17.304348 |
def set_string(self, string_options):
"""Set a series of properties using a string.
For example::
'fred=12, tile'
'[fred=12]'
"""
vo = ffi.cast('VipsObject *', self.pointer)
cstr = _to_bytes(string_options)
result = vips_lib.vips_object_set_fro... | [
"def",
"set_string",
"(",
"self",
",",
"string_options",
")",
":",
"vo",
"=",
"ffi",
".",
"cast",
"(",
"'VipsObject *'",
",",
"self",
".",
"pointer",
")",
"cstr",
"=",
"_to_bytes",
"(",
"string_options",
")",
"result",
"=",
"vips_lib",
".",
"vips_object_se... | 23.466667 | 20 |
def unique_(self, col):
"""
Returns unique values in a column
"""
try:
df = self.df.drop_duplicates(subset=[col], inplace=False)
return list(df[col])
except Exception as e:
self.err(e, "Can not select unique data") | [
"def",
"unique_",
"(",
"self",
",",
"col",
")",
":",
"try",
":",
"df",
"=",
"self",
".",
"df",
".",
"drop_duplicates",
"(",
"subset",
"=",
"[",
"col",
"]",
",",
"inplace",
"=",
"False",
")",
"return",
"list",
"(",
"df",
"[",
"col",
"]",
")",
"e... | 31.333333 | 11.777778 |
def parallel_epd_lcdir(
lcdir,
externalparams,
lcfileglob=None,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
epdsmooth_sigclip=3.0,
epdsmooth_windowsize=21,
epdsmooth_func=smooth_magseries_savgol,... | [
"def",
"parallel_epd_lcdir",
"(",
"lcdir",
",",
"externalparams",
",",
"lcfileglob",
"=",
"None",
",",
"timecols",
"=",
"None",
",",
"magcols",
"=",
"None",
",",
"errcols",
"=",
"None",
",",
"lcformat",
"=",
"'hat-sql'",
",",
"lcformatdir",
"=",
"None",
",... | 40.175758 | 27 |
def arraylike_to_numpy(array_like):
"""Convert a 1d array-like (e.g,. list, tensor, etc.) to an np.ndarray"""
orig_type = type(array_like)
# Convert to np.ndarray
if isinstance(array_like, np.ndarray):
pass
elif isinstance(array_like, list):
array_like = np.array(array_like)
el... | [
"def",
"arraylike_to_numpy",
"(",
"array_like",
")",
":",
"orig_type",
"=",
"type",
"(",
"array_like",
")",
"# Convert to np.ndarray",
"if",
"isinstance",
"(",
"array_like",
",",
"np",
".",
"ndarray",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"array_like",
... | 33.75 | 17.15625 |
def has(self, character):
'''
Get if character (or character code point) is contained by any range on
this range group.
:param character: character or unicode code point to look for
:type character: str or int
:returns: True if character is contained by any range, False ... | [
"def",
"has",
"(",
"self",
",",
"character",
")",
":",
"if",
"not",
"self",
":",
"return",
"False",
"character",
"=",
"character",
"if",
"isinstance",
"(",
"character",
",",
"int",
")",
"else",
"ord",
"(",
"character",
")",
"last",
"=",
"self",
"[",
... | 38.5625 | 23.9375 |
def get_text_path(self):
"""
Returns the path of the directory containing text if they exist in this dataset.
"""
for res in self.dsDoc['dataResources']:
resPath = res['resPath']
resType = res['resType']
isCollection = res['isCollection']
i... | [
"def",
"get_text_path",
"(",
"self",
")",
":",
"for",
"res",
"in",
"self",
".",
"dsDoc",
"[",
"'dataResources'",
"]",
":",
"resPath",
"=",
"res",
"[",
"'resPath'",
"]",
"resType",
"=",
"res",
"[",
"'resType'",
"]",
"isCollection",
"=",
"res",
"[",
"'is... | 43.307692 | 17.615385 |
def title(self, title=None):
"""Returns or sets (if a value is provided) the chart's title.
:param str title: If given, the chart's title will be set to this.
:rtype: ``str``"""
if title is None:
return self._title
else:
if not isinstance(title, str):
... | [
"def",
"title",
"(",
"self",
",",
"title",
"=",
"None",
")",
":",
"if",
"title",
"is",
"None",
":",
"return",
"self",
".",
"_title",
"else",
":",
"if",
"not",
"isinstance",
"(",
"title",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"title must ... | 34.5 | 18.666667 |
def tempo_account_update_customer_by_id(self, customer_id=1, data=None):
"""
Updates an Attribute. Caller must have Manage Account Permission. Attribute can be a Category or Customer.
:param customer_id: id of Customer record
:param data: format is
{
... | [
"def",
"tempo_account_update_customer_by_id",
"(",
"self",
",",
"customer_id",
"=",
"1",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"\"\"\"Please, set the data as { isNew:boolean\n name:string\... | 45 | 14.35 |
def parse_phone(phone):
"""Parses the given phone, or returns ``None`` if it's invalid."""
if isinstance(phone, int):
return str(phone)
else:
phone = re.sub(r'[+()\s-]', '', str(phone))
if phone.isdigit():
return phone | [
"def",
"parse_phone",
"(",
"phone",
")",
":",
"if",
"isinstance",
"(",
"phone",
",",
"int",
")",
":",
"return",
"str",
"(",
"phone",
")",
"else",
":",
"phone",
"=",
"re",
".",
"sub",
"(",
"r'[+()\\s-]'",
",",
"''",
",",
"str",
"(",
"phone",
")",
... | 32.375 | 14.125 |
def _asString(self, value):
"""converts the value as a string"""
if sys.version_info[0] == 3:
if isinstance(value, str):
return value
elif isinstance(value, bytes):
return value.decode('utf-8')
elif sys.version_info[0] == 2:
ret... | [
"def",
"_asString",
"(",
"self",
",",
"value",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"bytes",
"... | 37.444444 | 4.333333 |
def extract_variants(pattern):
"""Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz)."""
v1, v2 = pattern.find('{'), pattern.find('}')
if v1 > -1 and v2 > v1:
variations = pattern[v1+1:v2].split(',')
variants = [pattern[:v1] + v + pattern[v2+1:] for v in variations]
else:... | [
"def",
"extract_variants",
"(",
"pattern",
")",
":",
"v1",
",",
"v2",
"=",
"pattern",
".",
"find",
"(",
"'{'",
")",
",",
"pattern",
".",
"find",
"(",
"'}'",
")",
"if",
"v1",
">",
"-",
"1",
"and",
"v2",
">",
"v1",
":",
"variations",
"=",
"pattern"... | 42.333333 | 13.111111 |
def __get_doc_block_lines(self):
"""
Returns the start and end line of the DOcBlock of the stored routine code.
"""
line1 = None
line2 = None
i = 0
for line in self._routine_source_code_lines:
if re.match(r'\s*/\*\*', line):
line1 = i
... | [
"def",
"__get_doc_block_lines",
"(",
"self",
")",
":",
"line1",
"=",
"None",
"line2",
"=",
"None",
"i",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"_routine_source_code_lines",
":",
"if",
"re",
".",
"match",
"(",
"r'\\s*/\\*\\*'",
",",
"line",
")",
":",... | 23.571429 | 20.52381 |
def _from_dict(cls, _dict):
"""Initialize a Tables object from a json dictionary."""
args = {}
if 'location' in _dict:
args['location'] = Location._from_dict(_dict.get('location'))
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'section_title' in ... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'location'",
"in",
"_dict",
":",
"args",
"[",
"'location'",
"]",
"=",
"Location",
".",
"_from_dict",
"(",
"_dict",
".",
"get",
"(",
"'location'",
")",
")",
"if",
... | 39.333333 | 13.757576 |
def export_to_pem(self, private_key=False, password=False):
"""Exports keys to a data buffer suitable to be stored as a PEM file.
Either the public or the private key can be exported to a PEM file.
For private keys the PKCS#8 format is used. If a password is provided
the best encryption ... | [
"def",
"export_to_pem",
"(",
"self",
",",
"private_key",
"=",
"False",
",",
"password",
"=",
"False",
")",
":",
"e",
"=",
"serialization",
".",
"Encoding",
".",
"PEM",
"if",
"private_key",
":",
"if",
"not",
"self",
".",
"has_private",
":",
"raise",
"Inva... | 53.264706 | 20.794118 |
def plot_T_dependent_property(self, Tmin=None, Tmax=None, methods=[],
pts=50, only_valid=True, order=0): # pragma: no cover
r'''Method to create a plot of the property vs temperature according to
either a specified list of methods, or user methods (if set), or all
... | [
"def",
"plot_T_dependent_property",
"(",
"self",
",",
"Tmin",
"=",
"None",
",",
"Tmax",
"=",
"None",
",",
"methods",
"=",
"[",
"]",
",",
"pts",
"=",
"50",
",",
"only_valid",
"=",
"True",
",",
"order",
"=",
"0",
")",
":",
"# pragma: no cover",
"# This f... | 48.269663 | 21.280899 |
def _get_what_to_read_next(fp, previously_read_position, chunk_size):
"""Return information on which file pointer position to read from and how many bytes.
Args:
fp
past_read_positon (int): The file pointer position that has been read previously
chunk_size(int): ideal io chunk_size
... | [
"def",
"_get_what_to_read_next",
"(",
"fp",
",",
"previously_read_position",
",",
"chunk_size",
")",
":",
"seek_position",
"=",
"max",
"(",
"previously_read_position",
"-",
"chunk_size",
",",
"0",
")",
"read_size",
"=",
"chunk_size",
"# examples: say, our new_lines are ... | 43.516129 | 25.580645 |
def get_routing_tuples(cls):
'''A generator of (rule, callback) tuples.'''
for callback in cls.callbacks:
ep_name = '{}.{}'.format(cls.api.__name__, callback.__name__)
yield (Rule(cls.endpoint_path,
endpoint=ep_name,
methods=callbac... | [
"def",
"get_routing_tuples",
"(",
"cls",
")",
":",
"for",
"callback",
"in",
"cls",
".",
"callbacks",
":",
"ep_name",
"=",
"'{}.{}'",
".",
"format",
"(",
"cls",
".",
"api",
".",
"__name__",
",",
"callback",
".",
"__name__",
")",
"yield",
"(",
"Rule",
"(... | 44.625 | 11.125 |
def full_task(self, token_id, presented_pronunciation, pronunciation, pronunciation_probability,
warn=True, default=True):
"""Provide the prediction of the full task.
This function is used to predict the probability of a given pronunciation being reported for a given token.
:... | [
"def",
"full_task",
"(",
"self",
",",
"token_id",
",",
"presented_pronunciation",
",",
"pronunciation",
",",
"pronunciation_probability",
",",
"warn",
"=",
"True",
",",
"default",
"=",
"True",
")",
":",
"if",
"pronunciation_probability",
"is",
"not",
"None",
"an... | 52.244444 | 34.022222 |
def _notifications(self):
"""
Get the number of unread notifications.
"""
if not self.username or not self.auth_token:
if not self.notification_warning:
self.py3.notify_user(
"Github module needs username and "
"auth_tok... | [
"def",
"_notifications",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"auth_token",
":",
"if",
"not",
"self",
".",
"notification_warning",
":",
"self",
".",
"py3",
".",
"notify_user",
"(",
"\"Github module needs user... | 36.795918 | 17 |
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
... | [
"def",
"_filter_data",
"(",
"self",
",",
"pattern",
")",
":",
"removed",
"=",
"[",
"]",
"filtered",
"=",
"[",
"]",
"for",
"param",
"in",
"self",
".",
"data",
":",
"if",
"not",
"param",
"[",
"0",
"]",
".",
"startswith",
"(",
"pattern",
")",
":",
"... | 29.769231 | 16.230769 |
def deprecated(message=None):
"""A decorator for deprecated functions"""
def _decorator(func, message=message):
if message is None:
message = '%s is deprecated' % func.__name__
def newfunc(*args, **kwds):
warnings.warn(message, DeprecationWarning, stacklevel=2)
... | [
"def",
"deprecated",
"(",
"message",
"=",
"None",
")",
":",
"def",
"_decorator",
"(",
"func",
",",
"message",
"=",
"message",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"'%s is deprecated'",
"%",
"func",
".",
"__name__",
"def",
"newfun... | 34.909091 | 14 |
def BitVecSym(
name: str, size: int, annotations: Annotations = None
) -> z3.BitVecRef:
"""Creates a new bit vector with a symbolic value."""
return z3.BitVec(name, size) | [
"def",
"BitVecSym",
"(",
"name",
":",
"str",
",",
"size",
":",
"int",
",",
"annotations",
":",
"Annotations",
"=",
"None",
")",
"->",
"z3",
".",
"BitVecRef",
":",
"return",
"z3",
".",
"BitVec",
"(",
"name",
",",
"size",
")"
] | 38.8 | 13.8 |
def _fit_gpu(self, Ciu_host, Cui_host, show_progress=True):
""" specialized training on the gpu. copies inputs to/from cuda device """
if not implicit.cuda.HAS_CUDA:
raise ValueError("No CUDA extension has been built, can't train on GPU.")
if self.dtype == np.float64:
lo... | [
"def",
"_fit_gpu",
"(",
"self",
",",
"Ciu_host",
",",
"Cui_host",
",",
"show_progress",
"=",
"True",
")",
":",
"if",
"not",
"implicit",
".",
"cuda",
".",
"HAS_CUDA",
":",
"raise",
"ValueError",
"(",
"\"No CUDA extension has been built, can't train on GPU.\"",
")",... | 47.736842 | 23.263158 |
def get_case(flags):
"""Parse flags for case sensitivity settings."""
if not bool(flags & CASE_FLAGS):
case_sensitive = util.is_case_sensitive()
elif flags & FORCECASE:
case_sensitive = True
else:
case_sensitive = False
return case_sensitive | [
"def",
"get_case",
"(",
"flags",
")",
":",
"if",
"not",
"bool",
"(",
"flags",
"&",
"CASE_FLAGS",
")",
":",
"case_sensitive",
"=",
"util",
".",
"is_case_sensitive",
"(",
")",
"elif",
"flags",
"&",
"FORCECASE",
":",
"case_sensitive",
"=",
"True",
"else",
"... | 27.7 | 15.3 |
def decoherence_noise_with_asymmetric_ro(gates: Sequence[Gate], p00=0.975, p11=0.911):
"""Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout.
For simplicity, we use the default values for T1, T2, gate times, et al. and only allow
the specification of readout fidelities.
"""
... | [
"def",
"decoherence_noise_with_asymmetric_ro",
"(",
"gates",
":",
"Sequence",
"[",
"Gate",
"]",
",",
"p00",
"=",
"0.975",
",",
"p11",
"=",
"0.911",
")",
":",
"noise_model",
"=",
"_decoherence_noise_model",
"(",
"gates",
")",
"aprobs",
"=",
"np",
".",
"array"... | 50.363636 | 17.272727 |
def parse_cl_args(in_args):
"""Parse input commandline arguments, handling multiple cases.
Returns the main config file and set of kwargs.
"""
sub_cmds = {"upgrade": install.add_subparser,
"runfn": runfn.add_subparser,
"graph": graph.add_subparser,
"versi... | [
"def",
"parse_cl_args",
"(",
"in_args",
")",
":",
"sub_cmds",
"=",
"{",
"\"upgrade\"",
":",
"install",
".",
"add_subparser",
",",
"\"runfn\"",
":",
"runfn",
".",
"add_subparser",
",",
"\"graph\"",
":",
"graph",
".",
"add_subparser",
",",
"\"version\"",
":",
... | 54.244681 | 19.659574 |
def _compute_ratio(top, bot):
""" Make a map that is the ratio of two maps
"""
data = np.where(bot.data > 0, top.data / bot.data, 0.)
return HpxMap(data, top.hpx) | [
"def",
"_compute_ratio",
"(",
"top",
",",
"bot",
")",
":",
"data",
"=",
"np",
".",
"where",
"(",
"bot",
".",
"data",
">",
"0",
",",
"top",
".",
"data",
"/",
"bot",
".",
"data",
",",
"0.",
")",
"return",
"HpxMap",
"(",
"data",
",",
"top",
".",
... | 38 | 7.4 |
def _rgb_to_hsv(rgbs):
"""Convert Nx3 or Nx4 rgb to hsv"""
rgbs, n_dim = _check_color_dim(rgbs)
hsvs = list()
for rgb in rgbs:
rgb = rgb[:3] # don't use alpha here
idx = np.argmax(rgb)
val = rgb[idx]
c = val - np.min(rgb)
if c == 0:
hue = 0
... | [
"def",
"_rgb_to_hsv",
"(",
"rgbs",
")",
":",
"rgbs",
",",
"n_dim",
"=",
"_check_color_dim",
"(",
"rgbs",
")",
"hsvs",
"=",
"list",
"(",
")",
"for",
"rgb",
"in",
"rgbs",
":",
"rgb",
"=",
"rgb",
"[",
":",
"3",
"]",
"# don't use alpha here",
"idx",
"=",... | 29.962963 | 13.555556 |
def gen_keys(keysize=2048):
'''
Generate Salt minion keys and return them as PEM file strings
'''
# Mandate that keys are at least 2048 in size
if keysize < 2048:
keysize = 2048
tdir = tempfile.mkdtemp()
salt.crypt.gen_keys(tdir, 'minion', keysize)
priv_path = os.path.join(tdir,... | [
"def",
"gen_keys",
"(",
"keysize",
"=",
"2048",
")",
":",
"# Mandate that keys are at least 2048 in size",
"if",
"keysize",
"<",
"2048",
":",
"keysize",
"=",
"2048",
"tdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"salt",
".",
"crypt",
".",
"gen_keys",
"(... | 35.111111 | 17.666667 |
def add_cats(self, axis, cat_data):
'''
Add categories to rows or columns using cat_data array of objects. Each object in cat_data is a dictionary with one key (category title) and value (rows/column names) that have this category. Categories will be added onto the existing categories and will be added in the o... | [
"def",
"add_cats",
"(",
"self",
",",
"axis",
",",
"cat_data",
")",
":",
"for",
"inst_data",
"in",
"cat_data",
":",
"categories",
".",
"add_cats",
"(",
"self",
",",
"axis",
",",
"inst_data",
")"
] | 26.387097 | 31.483871 |
def get_weights(self):
"""
Get weights for this layer
:return: list of numpy arrays which represent weight and bias
"""
tensorWeights = callBigDlFunc(self.bigdl_type,
"getWeights", self.value)
if tensorWeights is not None:
return... | [
"def",
"get_weights",
"(",
"self",
")",
":",
"tensorWeights",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"getWeights\"",
",",
"self",
".",
"value",
")",
"if",
"tensorWeights",
"is",
"not",
"None",
":",
"return",
"[",
"tensor",
".",
"to_nd... | 34.846154 | 16.384615 |
def loadfile(path, mode=None, filetype=None, **kwargs):
"""Loads the given file using the appropriate InferenceFile class.
If ``filetype`` is not provided, this will try to retreive the ``filetype``
from the file's ``attrs``. If the file does not exist yet, an IOError will
be raised if ``filetype`` is ... | [
"def",
"loadfile",
"(",
"path",
",",
"mode",
"=",
"None",
",",
"filetype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"filetype",
"is",
"None",
":",
"# try to read the file to get its filetype",
"try",
":",
"fileclass",
"=",
"get_file_type",
"(",
... | 39.138889 | 21.833333 |
def _yield_leaves(self, url, tree):
'''
Yields a URL corresponding to a leaf dataset for each dataset described by the catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
'''
for leaf in tree.findall('.//{%s}dataset[@urlPat... | [
"def",
"_yield_leaves",
"(",
"self",
",",
"url",
",",
"tree",
")",
":",
"for",
"leaf",
"in",
"tree",
".",
"findall",
"(",
"'.//{%s}dataset[@urlPath]'",
"%",
"INV_NS",
")",
":",
"# Subset by the skips",
"name",
"=",
"leaf",
".",
"get",
"(",
"\"name\"",
")",... | 42.75 | 18.7 |
def siblings_before(self):
"""
:return: a list of this node's siblings that occur *before* this
node in the DOM.
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
before_nodelist = []
for n in impl_nodelist:
if n == self.imp... | [
"def",
"siblings_before",
"(",
"self",
")",
":",
"impl_nodelist",
"=",
"self",
".",
"adapter",
".",
"get_node_children",
"(",
"self",
".",
"parent",
".",
"impl_node",
")",
"before_nodelist",
"=",
"[",
"]",
"for",
"n",
"in",
"impl_nodelist",
":",
"if",
"n",... | 35.916667 | 13.083333 |
def GetPropertyValueEx(self, propertyId: int, ignoreDefaultValue: int) -> Any:
"""
Call IUIAutomationElement::GetCurrentPropertyValueEx.
propertyId: int, a value in class `PropertyId`.
ignoreDefaultValue: int, 0 or 1.
Return Any, corresponding type according to propertyId.
... | [
"def",
"GetPropertyValueEx",
"(",
"self",
",",
"propertyId",
":",
"int",
",",
"ignoreDefaultValue",
":",
"int",
")",
"->",
"Any",
":",
"return",
"self",
".",
"Element",
".",
"GetCurrentPropertyValueEx",
"(",
"propertyId",
",",
"ignoreDefaultValue",
")"
] | 62 | 28.444444 |
def most_recent_common_ancestor(self, *ts):
"""Find the MRCA of some tax_ids.
Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if
no ancestor of the specified tax_ids could be found.
"""
if len(ts) > 200:
res = self._large_mrca(ts)
else:
... | [
"def",
"most_recent_common_ancestor",
"(",
"self",
",",
"*",
"ts",
")",
":",
"if",
"len",
"(",
"ts",
")",
">",
"200",
":",
"res",
"=",
"self",
".",
"_large_mrca",
"(",
"ts",
")",
"else",
":",
"res",
"=",
"self",
".",
"_small_mrca",
"(",
"ts",
")",
... | 28 | 17.875 |
def is_readable(path=None):
"""
Test if the supplied filesystem path can be read
:param path: A filesystem path
:return: True if the path is a file that can be read. Otherwise, False
"""
if os.path.isfile(path) and os.access(path, os.R_OK):
return True
return False | [
"def",
"is_readable",
"(",
"path",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"R_OK",
")",
":",
"return",
"True",
"return",
"False"
] | 32.555556 | 14.111111 |
def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum):
"""Coordinates the computation and update of the availability matrix
for Affinity Propagation clustering.
Parameters
----------
hdf5_file : string or file handle
Specify access to the hierarchical dat... | [
"def",
"compute_availabilities",
"(",
"hdf5_file",
",",
"N_columns",
",",
"damping",
",",
"N_processes",
",",
"rows_sum",
")",
":",
"slice_queue",
"=",
"multiprocessing",
".",
"JoinableQueue",
"(",
")",
"pid_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"... | 35.372093 | 24.372093 |
def itemgetters(*args):
"""
Get a handful of items from an iterable.
This is just map(itemgetter(...), iterable) with a list comprehension.
"""
f = itemgetter(*args)
def inner(l):
return [f(x) for x in l]
return inner | [
"def",
"itemgetters",
"(",
"*",
"args",
")",
":",
"f",
"=",
"itemgetter",
"(",
"*",
"args",
")",
"def",
"inner",
"(",
"l",
")",
":",
"return",
"[",
"f",
"(",
"x",
")",
"for",
"x",
"in",
"l",
"]",
"return",
"inner"
] | 18.846154 | 21.923077 |
def load_user_from_request(req):
"""
Just like the Flask.login load_user_from_request
If you need to customize the user loading from your database,
the FlaskBitjws.get_user_by_key method is the one to modify.
:param req: The flask request to load a user based on.
"""
load_jws_from_request(... | [
"def",
"load_user_from_request",
"(",
"req",
")",
":",
"load_jws_from_request",
"(",
"req",
")",
"if",
"not",
"hasattr",
"(",
"req",
",",
"'jws_header'",
")",
"or",
"req",
".",
"jws_header",
"is",
"None",
"or",
"not",
"'iat'",
"in",
"req",
".",
"jws_payloa... | 37.366667 | 20.766667 |
def get_context_data(self, **kwargs):
"""Includes the Gauge slugs and data in the context."""
data = super(GaugesView, self).get_context_data(**kwargs)
data.update({'gauges': get_r().gauge_slugs()})
return data | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"super",
"(",
"GaugesView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"data",
".",
"update",
"(",
"{",
"'gauges'",
":",
"get_r",
"(... | 47.6 | 12.6 |
def visit_unaryop(self, node):
"""return an astroid.UnaryOp node as string"""
if node.op == "not":
operator = "not "
else:
operator = node.op
return "%s%s" % (operator, self._precedence_parens(node, node.operand)) | [
"def",
"visit_unaryop",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"op",
"==",
"\"not\"",
":",
"operator",
"=",
"\"not \"",
"else",
":",
"operator",
"=",
"node",
".",
"op",
"return",
"\"%s%s\"",
"%",
"(",
"operator",
",",
"self",
".",
"_p... | 37.571429 | 15.571429 |
def handle_pagination(self, page_num=None, page_size=None):
""" Handle retrieving and processing the next page of results. """
self._response_json = self.get_next_page(page_num=page_num, page_size=page_size)
self.update_attrs()
self.position = 0
self.values = self.process_page() | [
"def",
"handle_pagination",
"(",
"self",
",",
"page_num",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"self",
".",
"_response_json",
"=",
"self",
".",
"get_next_page",
"(",
"page_num",
"=",
"page_num",
",",
"page_size",
"=",
"page_size",
")",
"se... | 52.333333 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.