text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def enable_virtual_terminal_processing():
"""As of Windows 10, the Windows console supports (some) ANSI escape
sequences, but it needs to be enabled using `SetConsoleMode` first.
More info on the escape sequences supported:
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx... | [
"def",
"enable_virtual_terminal_processing",
"(",
")",
":",
"stdout",
"=",
"GetStdHandle",
"(",
"STD_OUTPUT_HANDLE",
")",
"flags",
"=",
"GetConsoleMode",
"(",
"stdout",
")",
"SetConsoleMode",
"(",
"stdout",
",",
"flags",
"|",
"ENABLE_VIRTUAL_TERMINAL_PROCESSING",
")"
... | 47 | 16.3 |
def setColor(self, poiID, color):
"""setColor(string, (integer, integer, integer, integer)) -> None
Sets the rgba color of the poi.
"""
self._connection._beginMessage(
tc.CMD_SET_POI_VARIABLE, tc.VAR_COLOR, poiID, 1 + 1 + 1 + 1 + 1)
self._connection._string += struct... | [
"def",
"setColor",
"(",
"self",
",",
"poiID",
",",
"color",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_SET_POI_VARIABLE",
",",
"tc",
".",
"VAR_COLOR",
",",
"poiID",
",",
"1",
"+",
"1",
"+",
"1",
"+",
"1",
"+",
... | 45.2 | 15.2 |
def profile_name(org_vm, profile_inst, short=False):
"""
Return Org, Profile, Version as a string from the properties in the
profile instance. The returned form is the form Org:Name:Version or
Org:Name if the optional argument short is TRUE
"""
try:
name_tuple = get_profile_name(org_vm,... | [
"def",
"profile_name",
"(",
"org_vm",
",",
"profile_inst",
",",
"short",
"=",
"False",
")",
":",
"try",
":",
"name_tuple",
"=",
"get_profile_name",
"(",
"org_vm",
",",
"profile_inst",
")",
"except",
"Exception",
"as",
"ex",
":",
"# pylint: disable=broad-except",... | 41.4375 | 19.8125 |
def sec_project_community(self, project=None):
"""
Generate the data for the Communication section in a Project report
:return:
"""
def create_csv(metric1, csv_labels, file_label):
esfilters = None
csv_labels = csv_labels.replace("_", "") # LaTeX not sup... | [
"def",
"sec_project_community",
"(",
"self",
",",
"project",
"=",
"None",
")",
":",
"def",
"create_csv",
"(",
"metric1",
",",
"csv_labels",
",",
"file_label",
")",
":",
"esfilters",
"=",
"None",
"csv_labels",
"=",
"csv_labels",
".",
"replace",
"(",
"\"_\"",
... | 36.754098 | 20.819672 |
def _get_species_taxon_ids(taxdump_file,
select_divisions=None, exclude_divisions=None):
"""Get a list of species taxon IDs (allow filtering by division)."""
if select_divisions and exclude_divisions:
raise ValueError('Cannot specify "select_divisions" and '
... | [
"def",
"_get_species_taxon_ids",
"(",
"taxdump_file",
",",
"select_divisions",
"=",
"None",
",",
"exclude_divisions",
"=",
"None",
")",
":",
"if",
"select_divisions",
"and",
"exclude_divisions",
":",
"raise",
"ValueError",
"(",
"'Cannot specify \"select_divisions\" and '"... | 35.883721 | 21.093023 |
def zip(*args, **kwargs):
""" Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables (or default if too short).
"""
args = [list(iterable) for iterable in args]
n = max(map(len, args))
v = kwargs.get("default", None)
ret... | [
"def",
"zip",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"list",
"(",
"iterable",
")",
"for",
"iterable",
"in",
"args",
"]",
"n",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"args",
")",
")",
"v",
"=",
"kwargs",
".",
... | 45.25 | 12.5 |
def generate_supremacy_circuit_google_v2_bristlecone(n_rows: int,
cz_depth: int, seed: int
) -> circuits.Circuit:
"""
Generates Google Random Circuits v2 in Bristlecone.
See also https://arxiv.org/abs/1... | [
"def",
"generate_supremacy_circuit_google_v2_bristlecone",
"(",
"n_rows",
":",
"int",
",",
"cz_depth",
":",
"int",
",",
"seed",
":",
"int",
")",
"->",
"circuits",
".",
"Circuit",
":",
"def",
"get_qubits",
"(",
"n_rows",
")",
":",
"def",
"count_neighbors",
"(",... | 40.02439 | 18.195122 |
def is_right_model(instance, attribute, value):
"""Must include at least the ``source`` and ``license`` keys, but
not a ``rightsOf`` key (``source`` indicates that the Right is
derived from and allowed by a source Right; it cannot contain the
full rights to a Creation).
"""
for key in ['source'... | [
"def",
"is_right_model",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"for",
"key",
"in",
"[",
"'source'",
",",
"'license'",
"]",
":",
"key_value",
"=",
"value",
".",
"get",
"(",
"key",
")",
"if",
"not",
"isinstance",
"(",
"key_value",
",... | 52.235294 | 19.294118 |
def _gen_uid(self):
'''
Generate the ID for post.
:return: the new ID.
'''
cur_uid = self.kind + tools.get_uu4d()
while MPost.get_by_uid(cur_uid):
cur_uid = self.kind + tools.get_uu4d()
return cur_uid | [
"def",
"_gen_uid",
"(",
"self",
")",
":",
"cur_uid",
"=",
"self",
".",
"kind",
"+",
"tools",
".",
"get_uu4d",
"(",
")",
"while",
"MPost",
".",
"get_by_uid",
"(",
"cur_uid",
")",
":",
"cur_uid",
"=",
"self",
".",
"kind",
"+",
"tools",
".",
"get_uu4d",... | 28.888889 | 14.666667 |
def _find_mocker(symbol: str, context: 'torment.contexts.TestContext') -> Callable[[], bool]:
'''Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowerc... | [
"def",
"_find_mocker",
"(",
"symbol",
":",
"str",
",",
"context",
":",
"'torment.contexts.TestContext'",
")",
"->",
"Callable",
"[",
"[",
"]",
",",
"bool",
"]",
":",
"components",
"=",
"[",
"]",
"method",
"=",
"None",
"for",
"component",
"in",
"symbol",
... | 26.58 | 25.06 |
def set_inherited_traits(self, egg_donor, sperm_donor):
"""Accept either strings or Gods as inputs."""
if type(egg_donor) == str:
self.reproduce_asexually(egg_donor, sperm_donor)
else:
self.reproduce_sexually(egg_donor, sperm_donor) | [
"def",
"set_inherited_traits",
"(",
"self",
",",
"egg_donor",
",",
"sperm_donor",
")",
":",
"if",
"type",
"(",
"egg_donor",
")",
"==",
"str",
":",
"self",
".",
"reproduce_asexually",
"(",
"egg_donor",
",",
"sperm_donor",
")",
"else",
":",
"self",
".",
"rep... | 45.833333 | 14.5 |
def removeTab(self, tab):
"""allows to remove a tab directly -not only by giving its index"""
if not isinstance(tab, int):
tab = self.indexOf(tab)
return super(FwTabWidget, self).removeTab(tab) | [
"def",
"removeTab",
"(",
"self",
",",
"tab",
")",
":",
"if",
"not",
"isinstance",
"(",
"tab",
",",
"int",
")",
":",
"tab",
"=",
"self",
".",
"indexOf",
"(",
"tab",
")",
"return",
"super",
"(",
"FwTabWidget",
",",
"self",
")",
".",
"removeTab",
"(",... | 45 | 7.6 |
def _to_tuple(bbox):
""" Converts the input bbox representation (see the constructor docstring for a list of valid representations)
into a flat tuple
:param bbox: A bbox in one of 7 forms listed in the class description.
:return: A flat tuple of size
:raises: TypeError
"... | [
"def",
"_to_tuple",
"(",
"bbox",
")",
":",
"if",
"isinstance",
"(",
"bbox",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"BBox",
".",
"_tuple_from_list_or_tuple",
"(",
"bbox",
")",
"if",
"isinstance",
"(",
"bbox",
",",
"str",
")",
":",
"r... | 42.052632 | 12.210526 |
def checkValidNodeTypes(provisioner, nodeTypes):
"""
Raises if an invalid nodeType is specified for aws, azure, or gce.
:param str provisioner: 'aws', 'gce', or 'azure' to specify which cloud provisioner used.
:param nodeTypes: A list of node types. Example: ['t2.micro', 't2.medium']
:return: Noth... | [
"def",
"checkValidNodeTypes",
"(",
"provisioner",
",",
"nodeTypes",
")",
":",
"if",
"not",
"nodeTypes",
":",
"return",
"if",
"not",
"isinstance",
"(",
"nodeTypes",
",",
"list",
")",
":",
"nodeTypes",
"=",
"[",
"nodeTypes",
"]",
"if",
"not",
"isinstance",
"... | 45.979167 | 18.979167 |
def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_cod... | [
"def",
"locale",
"(",
"self",
")",
"->",
"babel",
".",
"core",
".",
"Locale",
"or",
"None",
":",
"if",
"not",
"self",
".",
"language_code",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_locale'",
")",
":",
"setattr",
"(",
"self"... | 32.909091 | 12.545455 |
def binary_report(self, sha256sum, apikey):
"""
retrieve report from file scan
"""
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.pos... | [
"def",
"binary_report",
"(",
"self",
",",
"sha256sum",
",",
"apikey",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"file/report\"",
"params",
"=",
"{",
"\"apikey\"",
":",
"apikey",
",",
"\"resource\"",
":",
"sha256sum",
"}",
"rate_limit_clear",
"=",... | 40.105263 | 16.947368 |
def make_access_urls(self, catalog_url, all_services, metadata=None):
"""Make fully qualified urls for the access methods enabled on the dataset.
Parameters
----------
catalog_url : str
The top level server url
all_services : List[SimpleService]
list of :... | [
"def",
"make_access_urls",
"(",
"self",
",",
"catalog_url",
",",
"all_services",
",",
"metadata",
"=",
"None",
")",
":",
"all_service_dict",
"=",
"CaseInsensitiveDict",
"(",
"{",
"}",
")",
"for",
"service",
"in",
"all_services",
":",
"all_service_dict",
"[",
"... | 45.06 | 21.1 |
def sorted_key_list(self):
"""Returns list of keys sorted according to their absolute time."""
if not self.is_baked:
self.bake()
key_value_tuple = sorted(self.dct.items(),
key=lambda x: x[1]['__abs_time__'])
skl = [k[0] for k in key_value_tupl... | [
"def",
"sorted_key_list",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_baked",
":",
"self",
".",
"bake",
"(",
")",
"key_value_tuple",
"=",
"sorted",
"(",
"self",
".",
"dct",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
... | 41.75 | 13.375 |
def tnr(y, z):
"""True negative rate `tn / (tn + fp)`
"""
tp, tn, fp, fn = contingency_table(y, z)
return tn / (tn + fp) | [
"def",
"tnr",
"(",
"y",
",",
"z",
")",
":",
"tp",
",",
"tn",
",",
"fp",
",",
"fn",
"=",
"contingency_table",
"(",
"y",
",",
"z",
")",
"return",
"tn",
"/",
"(",
"tn",
"+",
"fp",
")"
] | 26.4 | 9 |
def search(term, category=Categories.ALL, pages=1, sort=None, order=None):
"""Return a search result for term in category. Can also be
sorted and span multiple pages."""
s = Search()
s.search(term=term, category=category, pages=pages, sort=sort, order=order)
return s | [
"def",
"search",
"(",
"term",
",",
"category",
"=",
"Categories",
".",
"ALL",
",",
"pages",
"=",
"1",
",",
"sort",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"s",
"=",
"Search",
"(",
")",
"s",
".",
"search",
"(",
"term",
"=",
"term",
","... | 44.666667 | 21.333333 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
compare
/katello/api/errata/compare
Otherwise, call ``super``.
"""
if which in ('compare',):
return ... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"in",
"(",
"'compare'",
",",
")",
":",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"super",
"(",
"Errata",
",",
"self",
")",
".",
"path",
"(",
"'base'",
")",
",",
"whi... | 29.357143 | 20.571429 |
def sign(self, data):
"""
Create an URL-safe, signed token from ``data``.
"""
data = signing.b64_encode(data).decode()
return self.signer.sign(data) | [
"def",
"sign",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"signing",
".",
"b64_encode",
"(",
"data",
")",
".",
"decode",
"(",
")",
"return",
"self",
".",
"signer",
".",
"sign",
"(",
"data",
")"
] | 26.142857 | 12.142857 |
def hrlist(self, name_start, name_end, limit=10):
"""
Return a list of the top ``limit`` hash's name between ``name_start`` and
``name_end`` in descending order
.. note:: The range is (``name_start``, ``name_end``]. The ``name_start``
isn't in the range, but ``name_end`` is.
... | [
"def",
"hrlist",
"(",
"self",
",",
"name_start",
",",
"name_end",
",",
"limit",
"=",
"10",
")",
":",
"limit",
"=",
"get_positive_integer",
"(",
"'limit'",
",",
"limit",
")",
"return",
"self",
".",
"execute_command",
"(",
"'hrlist'",
",",
"name_start",
",",... | 42.12 | 18.84 |
def vlan_id(self):
"""
VLAN ID for this interface, if any
:return: VLAN identifier
:rtype: str
"""
nicids = self.nicid.split('-')
if nicids:
u = []
for vlan in nicids:
if vlan.split('.')[-1] not in u:
... | [
"def",
"vlan_id",
"(",
"self",
")",
":",
"nicids",
"=",
"self",
".",
"nicid",
".",
"split",
"(",
"'-'",
")",
"if",
"nicids",
":",
"u",
"=",
"[",
"]",
"for",
"vlan",
"in",
"nicids",
":",
"if",
"vlan",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"... | 26.642857 | 11.928571 |
def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
if path:
return self.get_obj([vim.VirtualMachine], name, path=path)
else:
return self.get_obj([vim.VirtualMachine], name) | [
"def",
"get_vm",
"(",
"self",
",",
"name",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"path",
":",
"return",
"self",
".",
"get_obj",
"(",
"[",
"vim",
".",
"VirtualMachine",
"]",
",",
"name",
",",
"path",
"=",
"path",
")",
"else",
":",
"return",
"s... | 38.5 | 18 |
def _parse_team_data(self, team_data):
"""
Parses a value for every attribute.
This function looks through every attribute and retrieves the value
according to the parsing scheme and index of the attribute from the
passed HTML data. Once the value is retrieved, the attribute's v... | [
"def",
"_parse_team_data",
"(",
"self",
",",
"team_data",
")",
":",
"for",
"field",
"in",
"self",
".",
"__dict__",
":",
"if",
"field",
"==",
"'_year'",
"or",
"field",
"==",
"'_team_conference'",
":",
"continue",
"value",
"=",
"utils",
".",
"_parse_field",
... | 41.142857 | 18 |
def partition(args):
"""
%prog partition happy.txt synteny.graph
Select edges from another graph and merge it with the certain edges built
from the HAPPY mapping data.
"""
allowed_format = ("png", "ps")
p = OptionParser(partition.__doc__)
p.add_option("--prefix", help="Add prefix to the... | [
"def",
"partition",
"(",
"args",
")",
":",
"allowed_format",
"=",
"(",
"\"png\"",
",",
"\"ps\"",
")",
"p",
"=",
"OptionParser",
"(",
"partition",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--prefix\"",
",",
"help",
"=",
"\"Add prefix to the name [d... | 36.862069 | 15.931034 |
def install_json_schema(self):
"""Load install.json schema file."""
if self._install_json_schema is None and self.install_json_schema_file is not None:
# remove old schema file
if os.path.isfile('tcex_json_schema.json'):
# this file is now part of tcex.
... | [
"def",
"install_json_schema",
"(",
"self",
")",
":",
"if",
"self",
".",
"_install_json_schema",
"is",
"None",
"and",
"self",
".",
"install_json_schema_file",
"is",
"not",
"None",
":",
"# remove old schema file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'t... | 48.25 | 16.916667 |
def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if mtimes of files listed in old toc are newer
than ast_build
if pyc=1, check for .py files, too
"""
for (nm, fnm, typ) in old:
if mtime(fnm) > last_build:
logger.info("building because %s ... | [
"def",
"_check_guts_toc_mtime",
"(",
"attr",
",",
"old",
",",
"toc",
",",
"last_build",
",",
"pyc",
"=",
"0",
")",
":",
"for",
"(",
"nm",
",",
"fnm",
",",
"typ",
")",
"in",
"old",
":",
"if",
"mtime",
"(",
"fnm",
")",
">",
"last_build",
":",
"logg... | 33.4 | 16.066667 |
def get_factors_iterative2(n):
"""[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n]
"""
ans, stack, x = [], [], 2
while True:
if x > n // x:
if not stack:
return ans
... | [
"def",
"get_factors_iterative2",
"(",
"n",
")",
":",
"ans",
",",
"stack",
",",
"x",
"=",
"[",
"]",
",",
"[",
"]",
",",
"2",
"while",
"True",
":",
"if",
"x",
">",
"n",
"//",
"x",
":",
"if",
"not",
"stack",
":",
"return",
"ans",
"ans",
".",
"ap... | 19.88 | 18.24 |
def low_connectivity_nodes(self, impedance, count, imp_name=None):
"""
Identify nodes that are connected to fewer than some threshold
of other nodes within a given distance.
Parameters
----------
impedance : float
Distance within which to search for other con... | [
"def",
"low_connectivity_nodes",
"(",
"self",
",",
"impedance",
",",
"count",
",",
"imp_name",
"=",
"None",
")",
":",
"# set a counter variable on all nodes",
"self",
".",
"set",
"(",
"self",
".",
"node_ids",
".",
"to_series",
"(",
")",
",",
"name",
"=",
"'c... | 39.75 | 22.25 |
def get_context_for_image(self, zoom):
"""Creates a temporary cairo context for the image surface
:param zoom: The current scaling factor
:return: Cairo context to draw on
"""
cairo_context = Context(self.__image)
cairo_context.scale(zoom * self.multiplicator, zoom * sel... | [
"def",
"get_context_for_image",
"(",
"self",
",",
"zoom",
")",
":",
"cairo_context",
"=",
"Context",
"(",
"self",
".",
"__image",
")",
"cairo_context",
".",
"scale",
"(",
"zoom",
"*",
"self",
".",
"multiplicator",
",",
"zoom",
"*",
"self",
".",
"multiplica... | 39.666667 | 12 |
def gid(self):
"""Return the group id that the daemon will run with
:rtype: int
"""
if not self._gid:
if self.controller.config.daemon.group:
self._gid = grp.getgrnam(self.config.daemon.group).gr_gid
else:
self._gid = os.getgid()
... | [
"def",
"gid",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_gid",
":",
"if",
"self",
".",
"controller",
".",
"config",
".",
"daemon",
".",
"group",
":",
"self",
".",
"_gid",
"=",
"grp",
".",
"getgrnam",
"(",
"self",
".",
"config",
".",
"daem... | 27.75 | 18.833333 |
def join(self, room):
"""Lets a user join a room on a specific Namespace."""
self.socket.rooms.add(self._get_room_name(room)) | [
"def",
"join",
"(",
"self",
",",
"room",
")",
":",
"self",
".",
"socket",
".",
"rooms",
".",
"add",
"(",
"self",
".",
"_get_room_name",
"(",
"room",
")",
")"
] | 46.333333 | 11.666667 |
def valid_checksum(file, hash_file):
"""
Summary:
Validate file checksum using md5 hash
Args:
file: file object to verify integrity
hash_file: md5 reference checksum file
Returns:
Valid (True) | False, TYPE: bool
"""
bits = 4096
# calc md5 hash
hash_md5 =... | [
"def",
"valid_checksum",
"(",
"file",
",",
"hash_file",
")",
":",
"bits",
"=",
"4096",
"# calc md5 hash",
"hash_md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
... | 30.88 | 11.2 |
def maybe_add_child(self, fcoord):
""" Adds child node for fcoord if it doesn't already exist, and returns it. """
if fcoord not in self.children:
new_position = self.position.play_move(
coords.from_flat(fcoord))
self.children[fcoord] = MCTSNode(
n... | [
"def",
"maybe_add_child",
"(",
"self",
",",
"fcoord",
")",
":",
"if",
"fcoord",
"not",
"in",
"self",
".",
"children",
":",
"new_position",
"=",
"self",
".",
"position",
".",
"play_move",
"(",
"coords",
".",
"from_flat",
"(",
"fcoord",
")",
")",
"self",
... | 48.625 | 5.5 |
def input_to_phase(data, rate, data_type):
""" Take either phase or frequency as input and return phase
"""
if data_type == "phase":
return data
elif data_type == "freq":
return frequency2phase(data, rate)
else:
raise Exception("unknown data_type: " + data_type) | [
"def",
"input_to_phase",
"(",
"data",
",",
"rate",
",",
"data_type",
")",
":",
"if",
"data_type",
"==",
"\"phase\"",
":",
"return",
"data",
"elif",
"data_type",
"==",
"\"freq\"",
":",
"return",
"frequency2phase",
"(",
"data",
",",
"rate",
")",
"else",
":",... | 33.111111 | 10.777778 |
def to_tree(instance, *children):
"""
Generate tree structure of an instance, and its children. This method
yields its results, instead of returning them.
"""
# Yield representation of self
yield unicode(instance)
# Iterate trough each instance child collection
for i, child in enumerat... | [
"def",
"to_tree",
"(",
"instance",
",",
"*",
"children",
")",
":",
"# Yield representation of self",
"yield",
"unicode",
"(",
"instance",
")",
"# Iterate trough each instance child collection",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"children",
")",
":",
... | 26.348837 | 19 |
def t_escaped_LINE_FEED_CHAR(self, t):
r'\x6E' # 'n'
t.lexer.pop_state()
t.value = unichr(0x000a)
return t | [
"def",
"t_escaped_LINE_FEED_CHAR",
"(",
"self",
",",
"t",
")",
":",
"# 'n'",
"t",
".",
"lexer",
".",
"pop_state",
"(",
")",
"t",
".",
"value",
"=",
"unichr",
"(",
"0x000a",
")",
"return",
"t"
] | 27 | 13 |
def is_on(self, channel):
"""
Check if a switch is turned on
:return: bool
"""
if channel in self._is_on:
return self._is_on[channel]
return False | [
"def",
"is_on",
"(",
"self",
",",
"channel",
")",
":",
"if",
"channel",
"in",
"self",
".",
"_is_on",
":",
"return",
"self",
".",
"_is_on",
"[",
"channel",
"]",
"return",
"False"
] | 22.111111 | 11.444444 |
def set_parallel_multiple(self, value):
"""
Setter for 'parallel_multiple' field.
:param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("Paralle... | [
"def",
"set_parallel_multiple",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"ParallelMultiple must be set to a bool\"",
")",
"else",
":",
"self",... | 44.888889 | 17.555556 |
def precheck(context):
"""
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_'
(e.g. "precheck_ami_id")
Checking function should return True if OK, or raise RuntimeError w/ message if not
Args:
context: a populated EFVersionContext object
Returns:
True if the p... | [
"def",
"precheck",
"(",
"context",
")",
":",
"if",
"context",
".",
"noprecheck",
":",
"return",
"True",
"func_name",
"=",
"\"precheck_\"",
"+",
"context",
".",
"key",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"if",
"func_name",
"in",
"globals",
"(... | 35.684211 | 23.052632 |
def _m2crypto_sign(message, ssldir=None, certname=None, **config):
""" Insert two new fields into the message dict and return it.
Those fields are:
- 'signature' - the computed RSA message digest of the JSON repr.
- 'certificate' - the base64 X509 certificate of the sending host.
"""
i... | [
"def",
"_m2crypto_sign",
"(",
"message",
",",
"ssldir",
"=",
"None",
",",
"certname",
"=",
"None",
",",
"*",
"*",
"config",
")",
":",
"if",
"ssldir",
"is",
"None",
"or",
"certname",
"is",
"None",
":",
"error",
"=",
"\"You must set the ssldir and certname key... | 37.064516 | 20.967742 |
def factorization_machine_model(factor_size, num_features,
lr_mult_config, wd_mult_config, init_config):
""" builds factorization machine network with proper formulation:
y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2)
"""
x = mx.symbol.Variable("... | [
"def",
"factorization_machine_model",
"(",
"factor_size",
",",
"num_features",
",",
"lr_mult_config",
",",
"wd_mult_config",
",",
"init_config",
")",
":",
"x",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"\"data\"",
",",
"stype",
"=",
"'csr'",
")",
"# fact... | 44.771429 | 21.457143 |
def create_publication_assistant(self, **args):
'''
Create an assistant for a dataset that allows to make PID
requests for the dataset and all of its files.
:param drs_id: Mandatory. The dataset id of the dataset
to be published.
:param version_number: Mandatory. Th... | [
"def",
"create_publication_assistant",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"# Check args",
"logdebug",
"(",
"LOGGER",
",",
"'Creating publication assistant..'",
")",
"mandatory_args",
"=",
"[",
"'drs_id'",
",",
"'version_number'",
",",
"'is_replica'",
"]",... | 42.054545 | 20.927273 |
def write_shortstr(self, s):
"""Write a string up to 255 bytes long (after any encoding).
If passed a unicode string, encode with UTF-8.
"""
self._flushbits()
if isinstance(s, string):
s = s.encode('utf-8')
if len(s) > 255:
raise FrameSyntaxError... | [
"def",
"write_shortstr",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"_flushbits",
"(",
")",
"if",
"isinstance",
"(",
"s",
",",
"string",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"len",
"(",
"s",
")",
">",
"255",
":"... | 31 | 14.642857 |
def feed_parser(self, data):
"""Parse received message."""
assert isinstance(data, bytes)
self.controller.feed_parser(data) | [
"def",
"feed_parser",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"controller",
".",
"feed_parser",
"(",
"data",
")"
] | 36 | 3.75 |
def no_exception(on_exception, logger=None):
"""
处理函数抛出异常的装饰器, ATT: on_exception必填
:param on_exception: 遇到异常时函数返回什么内容
"""
def decorator(function):
def wrapper(*args, **kwargs):
try:
result = function(*args, **kwargs)
except Exception, e:
... | [
"def",
"no_exception",
"(",
"on_exception",
",",
"logger",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"function",
"(",
"*",
... | 26.47619 | 13.238095 |
def _forgiving_issubclass(derived_class, base_class):
"""Forgiving version of ``issubclass``
Does not throw any exception when arguments are not of class type
"""
return (type(derived_class) is ClassType and \
type(base_class) is ClassType and \
issubclass(derived_class, base_cl... | [
"def",
"_forgiving_issubclass",
"(",
"derived_class",
",",
"base_class",
")",
":",
"return",
"(",
"type",
"(",
"derived_class",
")",
"is",
"ClassType",
"and",
"type",
"(",
"base_class",
")",
"is",
"ClassType",
"and",
"issubclass",
"(",
"derived_class",
",",
"b... | 39.75 | 13.625 |
def write_context_error_report(self,file,context_type):
"""Write a context error report relative to the target or query into the specified filename
:param file: The name of a file to write the report to
:param context_type: They type of profile, target or query based
:type file: string
:type contex... | [
"def",
"write_context_error_report",
"(",
"self",
",",
"file",
",",
"context_type",
")",
":",
"if",
"context_type",
"==",
"'target'",
":",
"r",
"=",
"self",
".",
"get_target_context_error_report",
"(",
")",
"elif",
"context_type",
"==",
"'query'",
":",
"r",
"=... | 35.333333 | 17.142857 |
def load_dict(self, dct):
"""Load a dictionary of configuration values."""
for k, v in dct.items():
setattr(self, k, v) | [
"def",
"load_dict",
"(",
"self",
",",
"dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"dct",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] | 36 | 8 |
def get_sample(self, md5):
"""Get the sample from the data store.
This method first fetches the data from datastore, then cleans it for serialization
and then updates it with 'raw_bytes' item.
Args:
md5: The md5 digest of the sample to be fetched from datastore.
... | [
"def",
"get_sample",
"(",
"self",
",",
"md5",
")",
":",
"# Support 'short' md5s but don't waste performance if the full md5 is provided",
"if",
"len",
"(",
"md5",
")",
"<",
"32",
":",
"md5",
"=",
"self",
".",
"get_full_md5",
"(",
"md5",
",",
"self",
".",
"sample... | 39 | 25.46875 |
def inject_metadata_descriptions(self, term_dict):
'''
Inserts a set of descriptions of meta data terms. These will be displayed
below the scatter plot when a meta data term is clicked. All keys in the term dict
must occur as meta data.
Parameters
----------
ter... | [
"def",
"inject_metadata_descriptions",
"(",
"self",
",",
"term_dict",
")",
":",
"assert",
"type",
"(",
"term_dict",
")",
"==",
"dict",
"if",
"not",
"self",
".",
"term_doc_matrix",
".",
"metadata_in_use",
"(",
")",
":",
"raise",
"TermDocMatrixHasNoMetadataException... | 45.034483 | 31.793103 |
def get_null_or_blank_query(field=None):
"""
Query for null or blank field.
"""
if not field:
return field
null_q = get_null_query(field)
blank_q = get_blank_query(field)
return (null_q | blank_q) | [
"def",
"get_null_or_blank_query",
"(",
"field",
"=",
"None",
")",
":",
"if",
"not",
"field",
":",
"return",
"field",
"null_q",
"=",
"get_null_query",
"(",
"field",
")",
"blank_q",
"=",
"get_blank_query",
"(",
"field",
")",
"return",
"(",
"null_q",
"|",
"bl... | 24.888889 | 7.777778 |
def updateUser(self, username, password, fullname, description, email):
""" Updates a user account in the user store
Input:
username - the name of the user. The name must be unique in
the user store.
password - the password for this user.
... | [
"def",
"updateUser",
"(",
"self",
",",
"username",
",",
"password",
",",
"fullname",
",",
"description",
",",
"email",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"username\"",
":",
"username",
"}",
"if",
"password",
"is",
"not",
"None... | 43.357143 | 13.607143 |
def wer(self, s1, s2):
"""
Computes the Word Error Rate, defined as the edit distance between the
two provided sentences after tokenizing to words.
Arguments:
s1 (string): space-separated sentence
s2 (string): space-separated sentence
"""
# build ... | [
"def",
"wer",
"(",
"self",
",",
"s1",
",",
"s2",
")",
":",
"# build mapping of words to integers",
"b",
"=",
"set",
"(",
"s1",
".",
"split",
"(",
")",
"+",
"s2",
".",
"split",
"(",
")",
")",
"word2char",
"=",
"dict",
"(",
"zip",
"(",
"b",
",",
"r... | 35.526316 | 17.736842 |
def plot_fit(self,intervals=True,**kwargs):
""" Plots the fit of the model
Parameters
----------
intervals : Boolean
Whether to plot 95% confidence interval of states
Returns
----------
None (plots data and the fit)
"""
import matplot... | [
"def",
"plot_fit",
"(",
"self",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
... | 39.178082 | 25.739726 |
def render_edge_with_node_label(self, name, edge, edge_settings):
"""
Render edge with label as separate node
"""
props_to_display = self.extract_props(edge.settings)
label = '<'
label += "|".join(self.get_label(prop, value) for prop, value in props_to_display.items())
... | [
"def",
"render_edge_with_node_label",
"(",
"self",
",",
"name",
",",
"edge",
",",
"edge_settings",
")",
":",
"props_to_display",
"=",
"self",
".",
"extract_props",
"(",
"edge",
".",
"settings",
")",
"label",
"=",
"'<'",
"label",
"+=",
"\"|\"",
".",
"join",
... | 41.125 | 29.875 |
def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not nam... | [
"def",
"find_handfile",
"(",
"names",
"=",
"None",
")",
":",
"# 如果没有明确指定,则包含 env 中的值",
"names",
"=",
"names",
"or",
"[",
"env",
".",
"handfile",
"]",
"# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾",
"if",
"not",
"names",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.py'",
... | 30 | 15.243243 |
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False):
""" Retrieve a text node from the API
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage CtsReference
:type subreference: str
:param pre... | [
"def",
"getTextualNode",
"(",
"self",
",",
"textId",
",",
"subreference",
"=",
"None",
",",
"prevnext",
"=",
"False",
",",
"metadata",
"=",
"False",
")",
":",
"text",
",",
"text_metadata",
"=",
"self",
".",
"__getText__",
"(",
"textId",
")",
"if",
"subre... | 44.571429 | 18 |
def __execute_stm(self, instr):
"""Execute STM instruction.
"""
assert instr.operands[0].size in [8, 16, 32, 64, 128, 256]
assert instr.operands[2].size == self.__mem.address_size
op0_val = self.read_operand(instr.operands[0]) # Data.
op2_val = self.read_operand(instr.o... | [
"def",
"__execute_stm",
"(",
"self",
",",
"instr",
")",
":",
"assert",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"in",
"[",
"8",
",",
"16",
",",
"32",
",",
"64",
",",
"128",
",",
"256",
"]",
"assert",
"instr",
".",
"operands",
"[",
... | 32.928571 | 22.5 |
def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | [
"def",
"autosave_all",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"get_stack_count",
"(",
")",
")",
":",
"self",
".",
"autosave",
"(",
"index",
")"
] | 38 | 10.5 |
def address(self, street, city=None, state=None, zipcode=None, **kwargs):
'''Geocode an address.'''
fields = {
'street': street,
'city': city,
'state': state,
'zip': zipcode,
}
return self._fetch('address', fields, **kwargs) | [
"def",
"address",
"(",
"self",
",",
"street",
",",
"city",
"=",
"None",
",",
"state",
"=",
"None",
",",
"zipcode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"fields",
"=",
"{",
"'street'",
":",
"street",
",",
"'city'",
":",
"city",
",",
"'s... | 29.6 | 20 |
def compile_dictionary(self, lang, wordlists, encoding, output):
"""Compile user dictionary."""
cmd = [
self.binary,
'--lang', lang,
'--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name,
'create',
'ma... | [
"def",
"compile_dictionary",
"(",
"self",
",",
"lang",
",",
"wordlists",
",",
"encoding",
",",
"output",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"binary",
",",
"'--lang'",
",",
"lang",
",",
"'--encoding'",
",",
"codecs",
".",
"lookup",
"(",
"filters",
... | 33.954545 | 19.363636 |
def log_player_plays_monopoly(self, player, resource):
"""
:param player: catan.game.Player
:param resource: catan.board.Terrain
"""
self._logln('{0} plays monopoly on {1}'.format(
player.color,
resource.value
)) | [
"def",
"log_player_plays_monopoly",
"(",
"self",
",",
"player",
",",
"resource",
")",
":",
"self",
".",
"_logln",
"(",
"'{0} plays monopoly on {1}'",
".",
"format",
"(",
"player",
".",
"color",
",",
"resource",
".",
"value",
")",
")"
] | 30.666667 | 10.222222 |
def _get_index(self,index):
"""Get the current block index, validating and checking status.
Returns None if the demo is finished"""
if index is None:
if self.finished:
print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
... | [
"def",
"_get_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"is",
"None",
":",
"if",
"self",
".",
"finished",
":",
"print",
">>",
"io",
".",
"stdout",
",",
"'Demo finished. Use <demo_name>.reset() if you want to rerun it.'",
"return",
"None",
"inde... | 33.461538 | 18.846154 |
def perform_matched_selection(self, event):
"""
Performs matched selection.
:param event: QMouseEvent
"""
selected = TextHelper(self.editor).match_select()
if selected and event:
event.accept() | [
"def",
"perform_matched_selection",
"(",
"self",
",",
"event",
")",
":",
"selected",
"=",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"match_select",
"(",
")",
"if",
"selected",
"and",
"event",
":",
"event",
".",
"accept",
"(",
")"
] | 30.75 | 7 |
def hstrlen(self, name, key):
"""
Return the number of bytes stored in the value of ``key``
within hash ``name``
"""
with self.pipe as pipe:
return pipe.hstrlen(self.redis_key(name), key) | [
"def",
"hstrlen",
"(",
"self",
",",
"name",
",",
"key",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hstrlen",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"key",
")"
] | 33.285714 | 10.714286 |
def is_de_listed(self):
"""
判断合约是否过期
"""
instrument = Environment.get_instance().get_instrument(self._order_book_id)
current_date = Environment.get_instance().trading_dt
if instrument.de_listed_date is not None and current_date >= instrument.de_listed_date:
re... | [
"def",
"is_de_listed",
"(",
"self",
")",
":",
"instrument",
"=",
"Environment",
".",
"get_instance",
"(",
")",
".",
"get_instrument",
"(",
"self",
".",
"_order_book_id",
")",
"current_date",
"=",
"Environment",
".",
"get_instance",
"(",
")",
".",
"trading_dt",... | 38 | 21.777778 |
def get_type_hierarchy(s):
"""Get the sequence of parents from `s` to Statement.
Parameters
----------
s : a class or instance of a child of Statement
For example the statement `Phosphorylation(MEK(), ERK())` or just the
class `Phosphorylation`.
Returns
-------
parent_list ... | [
"def",
"get_type_hierarchy",
"(",
"s",
")",
":",
"tp",
"=",
"type",
"(",
"s",
")",
"if",
"not",
"isinstance",
"(",
"s",
",",
"type",
")",
"else",
"s",
"p_list",
"=",
"[",
"tp",
"]",
"for",
"p",
"in",
"tp",
".",
"__bases__",
":",
"if",
"p",
"is"... | 29.2 | 18.8 |
def DeregisterHelper(cls, helper_class):
"""Deregisters a helper class.
The helper classes are identified based on their lower case name.
Args:
helper_class (type): class object of the argument helper.
Raises:
KeyError: if helper class is not set for the corresponding name.
"""
he... | [
"def",
"DeregisterHelper",
"(",
"cls",
",",
"helper_class",
")",
":",
"helper_name",
"=",
"helper_class",
".",
"NAME",
".",
"lower",
"(",
")",
"if",
"helper_name",
"not",
"in",
"cls",
".",
"_helper_classes",
":",
"raise",
"KeyError",
"(",
"'Helper class not se... | 31.117647 | 20.588235 |
def wait_for_subworkflows(self, workflow_results):
'''Wait for results from subworkflows'''
wf_ids = sum([x['pending_workflows'] for x in workflow_results], [])
for wf_id in wf_ids:
# here we did not check if workflow ids match
yield self.socket
res = self.soc... | [
"def",
"wait_for_subworkflows",
"(",
"self",
",",
"workflow_results",
")",
":",
"wf_ids",
"=",
"sum",
"(",
"[",
"x",
"[",
"'pending_workflows'",
"]",
"for",
"x",
"in",
"workflow_results",
"]",
",",
"[",
"]",
")",
"for",
"wf_id",
"in",
"wf_ids",
":",
"# h... | 41.181818 | 12.818182 |
def spectrogram(t_signal, frame_width=FRAME_WIDTH, overlap=FRAME_STRIDE):
"""
Calculate the magnitude spectrogram of a single-channel time-domain signal
from the real frequency components of the STFT with a hanning window
applied to each frame. The frame size and overlap between frames should
be spe... | [
"def",
"spectrogram",
"(",
"t_signal",
",",
"frame_width",
"=",
"FRAME_WIDTH",
",",
"overlap",
"=",
"FRAME_STRIDE",
")",
":",
"frame_width",
"=",
"min",
"(",
"t_signal",
".",
"shape",
"[",
"0",
"]",
",",
"frame_width",
")",
"w",
"=",
"np",
".",
"hanning"... | 46.631579 | 21.052632 |
def switch_toggle(self, device):
"""Toggles the current state of the given device"""
state = self.get_state(device)
if(state == '1'):
return self.switch_off(device)
elif(state == '0'):
return self.switch_on(device)
else:
return state | [
"def",
"switch_toggle",
"(",
"self",
",",
"device",
")",
":",
"state",
"=",
"self",
".",
"get_state",
"(",
"device",
")",
"if",
"(",
"state",
"==",
"'1'",
")",
":",
"return",
"self",
".",
"switch_off",
"(",
"device",
")",
"elif",
"(",
"state",
"==",
... | 30.1 | 12.4 |
def parse_multiple_json(json_file, offset=None):
"""Parse multiple json records from the given file.
Seek to the offset as the start point before parsing
if offset set. return empty list if the json file does
not exists or exception occurs.
Args:
json_file (str): File path to be parsed.
... | [
"def",
"parse_multiple_json",
"(",
"json_file",
",",
"offset",
"=",
"None",
")",
":",
"json_info_list",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"json_file",
")",
":",
"return",
"json_info_list",
"try",
":",
"with",
"open",
"(",... | 27.971429 | 15.971429 |
def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1,
img_id=None, src_vol_id=None, snap_id=None):
"""Create cinder volume, optionally from a glance image, OR
optionally as a clone of an existing volume, OR optionally
from a snapshot. Wait for the ... | [
"def",
"create_cinder_volume",
"(",
"self",
",",
"cinder",
",",
"vol_name",
"=",
"\"demo-vol\"",
",",
"vol_size",
"=",
"1",
",",
"img_id",
"=",
"None",
",",
"src_vol_id",
"=",
"None",
",",
"snap_id",
"=",
"None",
")",
":",
"# Handle parameter input and avoid i... | 49.215909 | 20.056818 |
def is_fringe(self, connections=None):
"""true if this edge has no incoming or no outgoing connections (except turnarounds)
If connections is given, only those connections are considered"""
if connections is None:
return self.is_fringe(self._incoming) or self.is_fringe(self._outgo... | [
"def",
"is_fringe",
"(",
"self",
",",
"connections",
"=",
"None",
")",
":",
"if",
"connections",
"is",
"None",
":",
"return",
"self",
".",
"is_fringe",
"(",
"self",
".",
"_incoming",
")",
"or",
"self",
".",
"is_fringe",
"(",
"self",
".",
"_outgoing",
"... | 60.375 | 18.875 |
def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, f... | [
"def",
"make_send_to_address_tx",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"STANDARD_FEE",
",",
"change_address",
"=",
"None",
")",
":",
"# get out the private key ob... | 40.416667 | 18.25 |
def has_path(self, path, method=None):
"""
Returns True if this Swagger has the given path and optional method
:param string path: Path name
:param string method: HTTP method
:return: True, if this path/method is present in the document
"""
method = self._normali... | [
"def",
"has_path",
"(",
"self",
",",
"path",
",",
"method",
"=",
"None",
")",
":",
"method",
"=",
"self",
".",
"_normalize_method_name",
"(",
"method",
")",
"path_dict",
"=",
"self",
".",
"get_path",
"(",
"path",
")",
"path_dict_exists",
"=",
"path_dict",
... | 35.266667 | 14.733333 |
def version():
"""Wrapper for opj_version library routine."""
OPENJPEG.opj_version.restype = ctypes.c_char_p
library_version = OPENJPEG.opj_version()
if sys.hexversion >= 0x03000000:
return library_version.decode('utf-8')
else:
return library_version | [
"def",
"version",
"(",
")",
":",
"OPENJPEG",
".",
"opj_version",
".",
"restype",
"=",
"ctypes",
".",
"c_char_p",
"library_version",
"=",
"OPENJPEG",
".",
"opj_version",
"(",
")",
"if",
"sys",
".",
"hexversion",
">=",
"0x03000000",
":",
"return",
"library_ver... | 34.875 | 11.375 |
def changeKeybind(self,kbname,combo):
"""
Changes a keybind of a specific keybindname.
:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination
"""
for key,value in self.keybinds.items():
if kbname in value:
... | [
"def",
"changeKeybind",
"(",
"self",
",",
"kbname",
",",
"combo",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"keybinds",
".",
"items",
"(",
")",
":",
"if",
"kbname",
"in",
"value",
":",
"del",
"value",
"[",
"value",
".",
"index",
"(",... | 39.133333 | 12.333333 |
def is_zero(pauli_object):
"""
Tests to see if a PauliTerm or PauliSum is zero.
:param pauli_object: Either a PauliTerm or PauliSum
:returns: True if PauliTerm is zero, False otherwise
:rtype: bool
"""
if isinstance(pauli_object, PauliTerm):
return np.isclose(pauli_object.coefficien... | [
"def",
"is_zero",
"(",
"pauli_object",
")",
":",
"if",
"isinstance",
"(",
"pauli_object",
",",
"PauliTerm",
")",
":",
"return",
"np",
".",
"isclose",
"(",
"pauli_object",
".",
"coefficient",
",",
"0",
")",
"elif",
"isinstance",
"(",
"pauli_object",
",",
"P... | 38.857143 | 19.142857 |
def idle_task(self):
'''called on idle'''
if self.module('console') is not None and not self.menu_added_console:
self.menu_added_console = True
self.module('console').add_menu(self.menu)
if self.module('map') is not None and not self.menu_added_map:
self.menu_... | [
"def",
"idle_task",
"(",
"self",
")",
":",
"if",
"self",
".",
"module",
"(",
"'console'",
")",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"menu_added_console",
":",
"self",
".",
"menu_added_console",
"=",
"True",
"self",
".",
"module",
"(",
"'consol... | 47.5 | 16 |
def save(self, filename, binary=True):
"""
Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
... | 33.883721 | 19.046512 |
def get(self, item, cache=None):
"""Lookup a torrent info property.
If cache is True, check the cache first. If the cache is empty, then
fetch torrent info before returning it.
"""
if item not in self._keys:
raise KeyError(item)
if self._use_cache(cache) and... | [
"def",
"get",
"(",
"self",
",",
"item",
",",
"cache",
"=",
"None",
")",
":",
"if",
"item",
"not",
"in",
"self",
".",
"_keys",
":",
"raise",
"KeyError",
"(",
"item",
")",
"if",
"self",
".",
"_use_cache",
"(",
"cache",
")",
"and",
"(",
"self",
".",... | 33.214286 | 13.142857 |
def add_item(self, item_url, item_metadata):
""" Add the given item to the cache database, updating
the existing metadata if the item is already present
:type item_url: String or Item
:param item_url: the URL of the item, or an Item object
:type item_metadata: String
:pa... | [
"def",
"add_item",
"(",
"self",
",",
"item_url",
",",
"item_metadata",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"DELETE FROM items WHERE url=?\"",
",",
"(",
"str",
"(",
"item_url",
")",
",",
")",
")"... | 37.444444 | 18.722222 |
def sfs_scaled(dac, n=None):
"""Compute the site frequency spectrum scaled such that a constant value is
expected across the spectrum for neutral variation and constant
population size.
Parameters
----------
dac : array_like, int, shape (n_variants,)
Array of derived allele counts.
... | [
"def",
"sfs_scaled",
"(",
"dac",
",",
"n",
"=",
"None",
")",
":",
"# compute site frequency spectrum",
"s",
"=",
"sfs",
"(",
"dac",
",",
"n",
"=",
"n",
")",
"# apply scaling",
"s",
"=",
"scale_sfs",
"(",
"s",
")",
"return",
"s"
] | 25.592593 | 21.888889 |
def simple_interaction_kronecker(snps,phenos,covs=None,Acovs=None,Asnps1=None,Asnps0=None,K1r=None,K1c=None,K2r=None,K2c=None,covar_type='lowrank_diag',rank=1,NumIntervalsDelta0=100,NumIntervalsDeltaAlt=0,searchDelta=False):
"""
I-variate fixed effects interaction test for phenotype specific SNP effects
Ar... | [
"def",
"simple_interaction_kronecker",
"(",
"snps",
",",
"phenos",
",",
"covs",
"=",
"None",
",",
"Acovs",
"=",
"None",
",",
"Asnps1",
"=",
"None",
",",
"Asnps0",
"=",
"None",
",",
"K1r",
"=",
"None",
",",
"K1c",
"=",
"None",
",",
"K2r",
"=",
"None",... | 49.024793 | 29.900826 |
def update_video(video_data):
"""
Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the vi... | [
"def",
"update_video",
"(",
"video_data",
")",
":",
"try",
":",
"video",
"=",
"_get_video",
"(",
"video_data",
".",
"get",
"(",
"\"edx_video_id\"",
")",
")",
"except",
"Video",
".",
"DoesNotExist",
":",
"error_message",
"=",
"u\"Video not found when trying to upda... | 35.564103 | 22.076923 |
def has_errors(self, form):
"""
Find tab fields listed as invalid
"""
return any([fieldname_error for fieldname_error in form.errors.keys()
if fieldname_error in self]) | [
"def",
"has_errors",
"(",
"self",
",",
"form",
")",
":",
"return",
"any",
"(",
"[",
"fieldname_error",
"for",
"fieldname_error",
"in",
"form",
".",
"errors",
".",
"keys",
"(",
")",
"if",
"fieldname_error",
"in",
"self",
"]",
")"
] | 35.833333 | 9.833333 |
def delete(dataset):
"""Use this function to delete dataset by it's id."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | [
"def",
"delete",
"(",
"dataset",
")",
":",
"config",
"=",
"ApiConfig",
"(",
")",
"client",
"=",
"ApiClient",
"(",
"config",
".",
"host",
",",
"config",
".",
"app_id",
",",
"config",
".",
"app_secret",
")",
"client",
".",
"check_correct_host",
"(",
")",
... | 38.625 | 18.875 |
def _init_state(self, initial_state: Union[int, np.ndarray]):
"""Initializes a the shard wavefunction and sets the initial state."""
state = np.reshape(
sim.to_valid_state_vector(initial_state, self._num_qubits),
(self._num_shards, self._shard_size))
state_handle = mem_ma... | [
"def",
"_init_state",
"(",
"self",
",",
"initial_state",
":",
"Union",
"[",
"int",
",",
"np",
".",
"ndarray",
"]",
")",
":",
"state",
"=",
"np",
".",
"reshape",
"(",
"sim",
".",
"to_valid_state_vector",
"(",
"initial_state",
",",
"self",
".",
"_num_qubit... | 56.5 | 15 |
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=... | [
"def",
"fqdns",
"(",
")",
":",
"# Provides:",
"# fqdns",
"grains",
"=",
"{",
"}",
"fqdns",
"=",
"set",
"(",
")",
"addresses",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs",
"(",
"include_loopback",
"=",
"False",
",",
"interface_data",
"=",
... | 40.857143 | 29.285714 |
def newest_file(file_iterable):
"""
Returns the name of the newest file given an iterable of file names.
"""
return max(file_iterable, key=lambda fname: os.path.getmtime(fname)) | [
"def",
"newest_file",
"(",
"file_iterable",
")",
":",
"return",
"max",
"(",
"file_iterable",
",",
"key",
"=",
"lambda",
"fname",
":",
"os",
".",
"path",
".",
"getmtime",
"(",
"fname",
")",
")"
] | 30.166667 | 18.166667 |
def _AsList(arg):
"""Encapsulates an argument in a list, if it's not already iterable."""
if (isinstance(arg, string_types) or
not isinstance(arg, collections.Iterable)):
return [arg]
else:
return list(arg) | [
"def",
"_AsList",
"(",
"arg",
")",
":",
"if",
"(",
"isinstance",
"(",
"arg",
",",
"string_types",
")",
"or",
"not",
"isinstance",
"(",
"arg",
",",
"collections",
".",
"Iterable",
")",
")",
":",
"return",
"[",
"arg",
"]",
"else",
":",
"return",
"list"... | 33.142857 | 15 |
def re_tag(name, remote=False, commit=None):
"""Add a local tag with that name at that commit
If no commit is given, at current commit on cuurent branch
If remote is true, also push the tag to origin
If tag already exists, delete it, then re-make it
"""
if remote:
tags = run('ls-remote... | [
"def",
"re_tag",
"(",
"name",
",",
"remote",
"=",
"False",
",",
"commit",
"=",
"None",
")",
":",
"if",
"remote",
":",
"tags",
"=",
"run",
"(",
"'ls-remote --tags'",
",",
"quiet",
"=",
"True",
")",
".",
"splitlines",
"(",
")",
"if",
"name",
"in",
"t... | 32.266667 | 15.933333 |
def validate_and_get_warnings(self):
"""
Validates/checks a given GTFS feed with respect to a number of different issues.
The set of warnings that are checked for, can be found in the gtfs_validator.ALL_WARNINGS
Returns
-------
warnings: WarningsContainer
"""
... | [
"def",
"validate_and_get_warnings",
"(",
"self",
")",
":",
"self",
".",
"warnings_container",
".",
"clear",
"(",
")",
"self",
".",
"_validate_stops_with_same_stop_time",
"(",
")",
"self",
".",
"_validate_speeds_and_trip_times",
"(",
")",
"self",
".",
"_validate_stop... | 35.117647 | 15.705882 |
def unpatch(obj, name):
"""
Undo the effects of patch(func, obj, name)
"""
setattr(obj, name, getattr(obj, name).original) | [
"def",
"unpatch",
"(",
"obj",
",",
"name",
")",
":",
"setattr",
"(",
"obj",
",",
"name",
",",
"getattr",
"(",
"obj",
",",
"name",
")",
".",
"original",
")"
] | 26.8 | 6.8 |
def capture_snapshots(self, path_globs_and_roots):
"""Synchronously captures Snapshots for each matching PathGlobs rooted at a its root directory.
This is a blocking operation, and should be avoided where possible.
:param path_globs_and_roots tuple<PathGlobsAndRoot>: The PathGlobs to capture, and the root... | [
"def",
"capture_snapshots",
"(",
"self",
",",
"path_globs_and_roots",
")",
":",
"result",
"=",
"self",
".",
"_native",
".",
"lib",
".",
"capture_snapshots",
"(",
"self",
".",
"_scheduler",
",",
"self",
".",
"_to_value",
"(",
"_PathGlobsAndRootCollection",
"(",
... | 43.357143 | 21.214286 |
def update_cname(name, data, **api_opts):
'''
Update CNAME. This is a helper call to update_object.
Find a CNAME ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_cname name=example.example.com data="{
'cano... | [
"def",
"update_cname",
"(",
"name",
",",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"o",
"=",
"get_cname",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"api_opts",
")",
"if",
"not",
"o",
":",
"raise",
"Exception",
"(",
"'CNAME record not found'",
")",
... | 31.1 | 22.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.