text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def open(self):
# type: () -> None
"""Connect to the TwinCAT message router."""
if self._open:
return
self._port = adsPortOpenEx()
if linux:
adsAddRoute(self._adr.netIdStruct(), self.ip_address)
self._open = True | [
"def",
"open",
"(",
"self",
")",
":",
"# type: () -> None\r",
"if",
"self",
".",
"_open",
":",
"return",
"self",
".",
"_port",
"=",
"adsPortOpenEx",
"(",
")",
"if",
"linux",
":",
"adsAddRoute",
"(",
"self",
".",
"_adr",
".",
"netIdStruct",
"(",
")",
",... | 23.916667 | 21.5 |
def _decrypt(private_key, ciphertext, rsa_oaep_padding=False):
"""
Encrypts a value using an RSA private key
:param private_key:
A PrivateKey instance to decrypt with
:param ciphertext:
A byte string of the data to decrypt
:param rsa_oaep_padding:
If OAEP padding should be... | [
"def",
"_decrypt",
"(",
"private_key",
",",
"ciphertext",
",",
"rsa_oaep_padding",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"private_key",
",",
"PrivateKey",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n private_key m... | 29.591837 | 20.653061 |
def dumps(obj):
"""Outputs json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder) | [
"def",
"dumps",
"(",
"obj",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"cls",
"=",
"CustomEncoder",
")"
] | 49.666667 | 18.666667 |
def find_config_files(
path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False
):
"""Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param f... | [
"def",
"find_config_files",
"(",
"path",
"=",
"[",
"'~/.vcspull'",
"]",
",",
"match",
"=",
"[",
"'*'",
"]",
",",
"filetype",
"=",
"[",
"'json'",
",",
"'yaml'",
"]",
",",
"include_home",
"=",
"False",
")",
":",
"configs",
"=",
"[",
"]",
"if",
"include... | 31.822222 | 19.666667 |
def get_all_resource_attributes(ref_key, network_id, template_id=None, **kwargs):
"""
Get all the resource attributes for a given resource type in the network.
That includes all the resource attributes for a given type within the network.
For example, if the ref_key is 'NODE', then it will r... | [
"def",
"get_all_resource_attributes",
"(",
"ref_key",
",",
"network_id",
",",
"template_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"resource_attr_qry",
"=",
"db",
".",
"DBSession",
".",
... | 44.266667 | 25.777778 |
def get_top_tags(self, limit=None, cacheable=True):
"""
Returns a sequence of the top tags used by this user with their counts
as TopItem objects.
* limit: The limit of how many tags to return.
* cacheable: Whether to cache results.
"""
params = self._get_params(... | [
"def",
"get_top_tags",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
... | 30.086957 | 21.73913 |
def main():
"""
The main loop for the commandline parser.
"""
DATABASE.load_contents()
continue_flag = False
while not continue_flag:
DATABASE.print_contents()
try:
command = raw_input(">>> ")
for stmnt_unformated in sqlparse.parse(command):
... | [
"def",
"main",
"(",
")",
":",
"DATABASE",
".",
"load_contents",
"(",
")",
"continue_flag",
"=",
"False",
"while",
"not",
"continue_flag",
":",
"DATABASE",
".",
"print_contents",
"(",
")",
"try",
":",
"command",
"=",
"raw_input",
"(",
"\">>> \"",
")",
"for"... | 44.239583 | 15.614583 |
def key_to_path(self, key):
"""Return the fullpath to the file with sha1sum key."""
return os.path.join(self.cache_dir, key[:2], key[2:4],
key[4:] + '.pkl') | [
"def",
"key_to_path",
"(",
"self",
",",
"key",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"key",
"[",
":",
"2",
"]",
",",
"key",
"[",
"2",
":",
"4",
"]",
",",
"key",
"[",
"4",
":",
"]",
"+",
"'.p... | 49.25 | 10 |
def reset_network(message):
"""Resets the users network to make changes take effect"""
for command in settings.RESTART_NETWORK:
try:
subprocess.check_call(command)
except:
pass
print(message) | [
"def",
"reset_network",
"(",
"message",
")",
":",
"for",
"command",
"in",
"settings",
".",
"RESTART_NETWORK",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
")",
"except",
":",
"pass",
"print",
"(",
"message",
")"
] | 29.5 | 14.75 |
def loop(bot, config, interval, settings):
"""Schedule a BOT (by label) to run on an interval, e.g. 'MyBot -i 60'"""
print_options(bot, config, settings)
click.echo(f'- Interval: {interval}s')
click.echo()
bot_task = BotTask(bot, config)
bot_task.run_loop(interval) | [
"def",
"loop",
"(",
"bot",
",",
"config",
",",
"interval",
",",
"settings",
")",
":",
"print_options",
"(",
"bot",
",",
"config",
",",
"settings",
")",
"click",
".",
"echo",
"(",
"f'- Interval: {interval}s'",
")",
"click",
".",
"echo",
"(",
")",
"bot_tas... | 40.428571 | 6 |
def repeat(self, time, function, args = []):
"""Repeat `function` every `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, True] | [
"def",
"repeat",
"(",
"self",
",",
"time",
",",
"function",
",",
"args",
"=",
"[",
"]",
")",
":",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
... | 60 | 15.5 |
def _extension(modpath: str) -> setuptools.Extension:
"""Make setuptools.Extension."""
return setuptools.Extension(modpath, [modpath.replace(".", "/") + ".py"]) | [
"def",
"_extension",
"(",
"modpath",
":",
"str",
")",
"->",
"setuptools",
".",
"Extension",
":",
"return",
"setuptools",
".",
"Extension",
"(",
"modpath",
",",
"[",
"modpath",
".",
"replace",
"(",
"\".\"",
",",
"\"/\"",
")",
"+",
"\".py\"",
"]",
")"
] | 55.333333 | 16.666667 |
def load_unicode(self, resource_path):
"""
Gets the content of a resource
"""
resource_content = pkg_resources.resource_string(self.module_name, resource_path)
return resource_content.decode('utf-8') | [
"def",
"load_unicode",
"(",
"self",
",",
"resource_path",
")",
":",
"resource_content",
"=",
"pkg_resources",
".",
"resource_string",
"(",
"self",
".",
"module_name",
",",
"resource_path",
")",
"return",
"resource_content",
".",
"decode",
"(",
"'utf-8'",
")"
] | 39 | 10 |
def _find_monitor(monitors, handle):
"""Find all devices and events with a given monitor installed."""
found_devs = set()
found_events = set()
for conn_string, device in monitors.items():
for event, handles in device.items():
if handle in handles:
found_events.add(e... | [
"def",
"_find_monitor",
"(",
"monitors",
",",
"handle",
")",
":",
"found_devs",
"=",
"set",
"(",
")",
"found_events",
"=",
"set",
"(",
")",
"for",
"conn_string",
",",
"device",
"in",
"monitors",
".",
"items",
"(",
")",
":",
"for",
"event",
",",
"handle... | 30.307692 | 14.384615 |
def gallery_image_versions(self):
"""Instance depends on the API version:
* 2018-06-01: :class:`GalleryImageVersionsOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImageVersionsOperations>`
* 2019-03-01: :class:`GalleryImageVersionsOperations<azure.mgmt.compute.v2019_03_01.ope... | [
"def",
"gallery_image_versions",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'gallery_image_versions'",
")",
"if",
"api_version",
"==",
"'2018-06-01'",
":",
"from",
".",
"v2018_06_01",
".",
"operations",
"import",
"GalleryImageV... | 68.428571 | 40.714286 |
def longest_increasing_subsequence(xs):
'''Return a longest increasing subsequence of xs.
(Note that there may be more than one such subsequence.)
>>> longest_increasing_subsequence(range(3))
[0, 1, 2]
>>> longest_increasing_subsequence([3, 1, 2, 0])
[1, 2]
'''
# Patience sort xs, stack... | [
"def",
"longest_increasing_subsequence",
"(",
"xs",
")",
":",
"# Patience sort xs, stacking (x, prev_ix) pairs on the piles.",
"# Prev_ix indexes the element at the top of the previous pile,",
"# which has a lower x value than the current x value.",
"piles",
"=",
"[",
"[",
"]",
"]",
"#... | 34.814815 | 16.962963 |
def _dump_crawl_stats(self):
'''
Dumps flattened crawling stats so the spiders do not have to
'''
extras = {}
spiders = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys('stats:crawler:*:*:*')
for key in keys:
#... | [
"def",
"_dump_crawl_stats",
"(",
"self",
")",
":",
"extras",
"=",
"{",
"}",
"spiders",
"=",
"{",
"}",
"spider_set",
"=",
"set",
"(",
")",
"total_spider_count",
"=",
"0",
"keys",
"=",
"self",
".",
"redis_conn",
".",
"keys",
"(",
"'stats:crawler:*:*:*'",
"... | 31.037037 | 20.185185 |
def render_children(node: Node, **child_args):
"""Render node children"""
for xml_node in node.xml_node.children:
child = render(xml_node, **child_args)
node.add_child(child) | [
"def",
"render_children",
"(",
"node",
":",
"Node",
",",
"*",
"*",
"child_args",
")",
":",
"for",
"xml_node",
"in",
"node",
".",
"xml_node",
".",
"children",
":",
"child",
"=",
"render",
"(",
"xml_node",
",",
"*",
"*",
"child_args",
")",
"node",
".",
... | 38.8 | 5.2 |
def jd_to_datetime(jd):
"""
Convert a Julian Day to an `jdutil.datetime` object.
Parameters
----------
jd : float
Julian day.
Returns
-------
dt : `jdutil.datetime` object
`jdutil.datetime` equivalent of Julian day.
Examples
--------
>>> jd_to_datetime(2446... | [
"def",
"jd_to_datetime",
"(",
"jd",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"jd_to_date",
"(",
"jd",
")",
"frac_days",
",",
"day",
"=",
"math",
".",
"modf",
"(",
"day",
")",
"day",
"=",
"int",
"(",
"day",
")",
"hour",
",",
"min",
",",
... | 19.285714 | 21.857143 |
def _get_center(self):
'''Returns the center point of the path, disregarding transforms.
'''
x = (self.x + self.width / 2)
y = (self.y + self.height / 2)
return (x, y) | [
"def",
"_get_center",
"(",
"self",
")",
":",
"x",
"=",
"(",
"self",
".",
"x",
"+",
"self",
".",
"width",
"/",
"2",
")",
"y",
"=",
"(",
"self",
".",
"y",
"+",
"self",
".",
"height",
"/",
"2",
")",
"return",
"(",
"x",
",",
"y",
")"
] | 33.666667 | 17.333333 |
def apply(self, *args: Any, **kwargs: Any) -> Any:
"""Called by workers to run the wrapped function.
You may call it yourself if you want to run the task in current process
without sending to the queue.
If task has a `retry` property it will be retried on failure.
If task has a... | [
"def",
"apply",
"(",
"self",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Any",
":",
"def",
"send_signal",
"(",
"sig",
":",
"Signal",
",",
"*",
"*",
"extra",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"... | 37.282051 | 19.487179 |
def fit_sparse(model_matrix,
response,
model,
model_coefficients_start,
tolerance,
l1_regularizer,
l2_regularizer=None,
maximum_iterations=None,
maximum_full_sweeps_per_iteration=1,
lea... | [
"def",
"fit_sparse",
"(",
"model_matrix",
",",
"response",
",",
"model",
",",
"model_coefficients_start",
",",
"tolerance",
",",
"l1_regularizer",
",",
"l2_regularizer",
"=",
"None",
",",
"maximum_iterations",
"=",
"None",
",",
"maximum_full_sweeps_per_iteration",
"="... | 39.173228 | 19.901575 |
def set_deferred_transfer(self, enable):
"""
Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
... | [
"def",
"set_deferred_transfer",
"(",
"self",
",",
"enable",
")",
":",
"if",
"self",
".",
"_deferred_transfer",
"and",
"not",
"enable",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"_deferred_transfer",
"=",
"enable"
] | 50.88 | 24.08 |
def send_email(sender,
subject,
content,
email_recipient_list,
email_address_list,
email_user=None,
email_pass=None,
email_server=None):
'''This sends an email to addresses, informing them about events.
The... | [
"def",
"send_email",
"(",
"sender",
",",
"subject",
",",
"content",
",",
"email_recipient_list",
",",
"email_address_list",
",",
"email_user",
"=",
"None",
",",
"email_pass",
"=",
"None",
",",
"email_server",
"=",
"None",
")",
":",
"if",
"not",
"email_user",
... | 28.324503 | 22.97351 |
def FormatArtifacts(self, artifacts):
"""Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition.
"""
artifact_definitions = [artifact.AsDict() for artifact in artifacts]
jso... | [
"def",
"FormatArtifacts",
"(",
"self",
",",
"artifacts",
")",
":",
"artifact_definitions",
"=",
"[",
"artifact",
".",
"AsDict",
"(",
")",
"for",
"artifact",
"in",
"artifacts",
"]",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"artifact_definitions",
")",
"re... | 30.916667 | 19.833333 |
def fit(self, X, y=None):
'''
Fit the transform. Does nothing, for compatibility with sklearn API.
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
y : None
There is no need of a target ... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"check_ts_data",
"(",
"X",
",",
"y",
")",
"if",
"not",
"X",
"[",
"0",
"]",
".",
"ndim",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"X variable must have more than 1 channel\"",
"... | 28.136364 | 25.227273 |
def embeddedFileGet(self, id):
"""Retrieve embedded file content by name or by number."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document_embeddedFileGet(self, id) | [
"def",
"embeddedFileGet",
"(",
"self",
",",
"id",
")",
":",
"if",
"self",
".",
"isClosed",
"or",
"self",
".",
"isEncrypted",
":",
"raise",
"ValueError",
"(",
"\"operation illegal for closed / encrypted doc\"",
")",
"return",
"_fitz",
".",
"Document_embeddedFileGet",... | 45.333333 | 17.666667 |
def MultipartArchiving(firstPartExtractList, otherPartSkippedList, archiveDir, otherPartFilePath = None):
"""
Archive all parts of multi-part compressed file.
If file has been extracted (via part1) then move all subsequent parts directly to archive directory.
If file has not been extracted then if part >1 add ... | [
"def",
"MultipartArchiving",
"(",
"firstPartExtractList",
",",
"otherPartSkippedList",
",",
"archiveDir",
",",
"otherPartFilePath",
"=",
"None",
")",
":",
"if",
"otherPartFilePath",
"is",
"None",
":",
"for",
"filePath",
"in",
"list",
"(",
"otherPartSkippedList",
")"... | 39.529412 | 24.176471 |
def get_command(self, ctx, name):
"""Get a callable command object."""
if name not in self.daemon_class.list_actions():
return None
# The context object is a Daemon object
daemon = ctx.obj
def subcommand(debug=False):
"""Call a daemonocle action."""
... | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"daemon_class",
".",
"list_actions",
"(",
")",
":",
"return",
"None",
"# The context object is a Daemon object",
"daemon",
"=",
"ctx",
".",
"obj",
... | 31.774194 | 16.580645 |
def safeRmTree(rootPath):
"""
Deletes a tree and returns true if it was correctly deleted
"""
shutil.rmtree(rootPath, True)
return not os.path.exists(rootPath) | [
"def",
"safeRmTree",
"(",
"rootPath",
")",
":",
"shutil",
".",
"rmtree",
"(",
"rootPath",
",",
"True",
")",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rootPath",
")"
] | 27.714286 | 12.571429 |
def get_identities(self, item):
"""Return the identities from an item"""
user = self.get_sh_identity(item, self.get_field_author())
yield user | [
"def",
"get_identities",
"(",
"self",
",",
"item",
")",
":",
"user",
"=",
"self",
".",
"get_sh_identity",
"(",
"item",
",",
"self",
".",
"get_field_author",
"(",
")",
")",
"yield",
"user"
] | 32.6 | 19.4 |
def get_std_icon(name, size=None):
"""Get standard platform icon
Call 'show_std_icons()' for details"""
if not name.startswith('SP_'):
name = 'SP_' + name
icon = QWidget().style().standardIcon(getattr(QStyle, name))
if size is None:
return icon
else:
return QIcon(icon.pix... | [
"def",
"get_std_icon",
"(",
"name",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"'SP_'",
")",
":",
"name",
"=",
"'SP_'",
"+",
"name",
"icon",
"=",
"QWidget",
"(",
")",
".",
"style",
"(",
")",
".",
"standardIcon"... | 32.7 | 12.6 |
def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth,
rrup, mean, idx):
"""
Compute mean for subduction interface events, as explained in table 2,
page 67.
"""
mean[idx] = (A1 + A2 * mag + C['C1'] + C['C2'] * (A3 - mag) ** 3 +
... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"A1",
",",
"A2",
",",
"A3",
",",
"A4",
",",
"A5",
",",
"A6",
",",
"mag",
",",
"hypo_depth",
",",
"rrup",
",",
"mean",
",",
"idx",
")",
":",
"mean",
"[",
"idx",
"]",
"=",
"(",
"A1",
"+",
"A... | 45.222222 | 17.888889 |
def _set_collector_encoding(self, v, load=False):
"""
Setter method for collector_encoding, mapped from YANG variable /telemetry/collector/collector_encoding (collector-encoding-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_collector_encoding is considered as a p... | [
"def",
"_set_collector_encoding",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
","... | 101.727273 | 48.818182 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'batches') and self.batches is not None:
_dict['batches'] = [x._to_dict() for x in self.batches]
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'batches'",
")",
"and",
"self",
".",
"batches",
"is",
"not",
"None",
":",
"_dict",
"[",
"'batches'",
"]",
"=",
"[",
"x",
".",
"_to_dict",
"(",
"... | 42 | 19.166667 |
def write_config_file(config_instance, appdirs=DEFAULT_APPDIRS,
file_name=DEFAULT_CONFIG_FILENAME):
"""
Write a ConfigParser instance to file at the correct location.
Args:
config_instance: Config instance to safe to file.
appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` insta... | [
"def",
"write_config_file",
"(",
"config_instance",
",",
"appdirs",
"=",
"DEFAULT_APPDIRS",
",",
"file_name",
"=",
"DEFAULT_CONFIG_FILENAME",
")",
":",
"path",
"=",
"get_config_path",
"(",
"appdirs",
",",
"file_name",
")",
"with",
"open",
"(",
"path",
",",
"'w'"... | 34.7 | 20 |
def _get_systemd_services(root):
'''
Use os.listdir() to get all the unit files
'''
ret = set()
for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,):
# Make sure user has access to the path, and if the path is a
# link it's likely that another entry in SYSTEM_CONFIG_PATHS
#... | [
"def",
"_get_systemd_services",
"(",
"root",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"SYSTEM_CONFIG_PATHS",
"+",
"(",
"LOCAL_CONFIG_PATH",
",",
")",
":",
"# Make sure user has access to the path, and if the path is a",
"# link it's likely that another ... | 42.052632 | 20.052632 |
def load_pickle(file_path):
"""
Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk.
"""
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data | [
"def",
"load_pickle",
"(",
"file_path",
")",
":",
"pkl_file",
"=",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"data",
"=",
"pickle",
".",
"load",
"(",
"pkl_file",
")",
"pkl_file",
".",
"close",
"(",
")",
"return",
"data"
] | 25.333333 | 15.833333 |
def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
if isinstance(self.amount, Amount):
self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency))
else:
self.amount = Amount("{0:.8f} {1}".format(self... | [
"def",
"load_commodities",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"amount",
",",
"Amount",
")",
":",
"self",
".",
"amount",
"=",
"Amount",
"(",
"\"{0:.8f} {1}\"",
".",
"format",
"(",
"self",
".",
"amount",
".",
"to_double",
"(",
"... | 42.125 | 19.375 |
def run_qpoints(self,
q_points,
with_eigenvectors=False,
with_group_velocities=False,
with_dynamical_matrices=False,
nac_q_direction=None):
"""Phonon calculations on q-points.
Parameters
--------... | [
"def",
"run_qpoints",
"(",
"self",
",",
"q_points",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"with_dynamical_matrices",
"=",
"False",
",",
"nac_q_direction",
"=",
"None",
")",
":",
"if",
"self",
".",
"_dynamical_ma... | 38.369565 | 14.152174 |
def cmd_list(self):
"""List migrations."""
from peewee_migrate.router import Router, LOGGER
LOGGER.setLevel('DEBUG')
LOGGER.propagate = 0
router = Router(self.database,
migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'],
migrate_ta... | [
"def",
"cmd_list",
"(",
"self",
")",
":",
"from",
"peewee_migrate",
".",
"router",
"import",
"Router",
",",
"LOGGER",
"LOGGER",
".",
"setLevel",
"(",
"'DEBUG'",
")",
"LOGGER",
".",
"propagate",
"=",
"0",
"router",
"=",
"Router",
"(",
"self",
".",
"databa... | 34.5 | 17.625 |
def readDataAndReshuffle(args, categoriesInOrderOfInterest=None):
"""
Read data file specified in args, optionally reshuffle categories, print out
some statistics, and return various data structures. This routine is pretty
specific and only used in some simple test scripts.
categoriesInOrderOfInterest (list)... | [
"def",
"readDataAndReshuffle",
"(",
"args",
",",
"categoriesInOrderOfInterest",
"=",
"None",
")",
":",
"# Read data",
"dataDict",
"=",
"readCSV",
"(",
"args",
".",
"dataPath",
",",
"1",
")",
"labelRefs",
",",
"dataDict",
"=",
"mapLabelRefs",
"(",
"dataDict",
"... | 34.413793 | 20.91954 |
def update(self):
"""
Draw the star.
"""
if not self._screen.is_visible(self._x, self._y):
self._respawn()
cur_char, _, _, _ = self._screen.get_from(self._x, self._y)
if cur_char not in (ord(self._old_char), 32):
self._respawn()
self._cyc... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_screen",
".",
"is_visible",
"(",
"self",
".",
"_x",
",",
"self",
".",
"_y",
")",
":",
"self",
".",
"_respawn",
"(",
")",
"cur_char",
",",
"_",
",",
"_",
",",
"_",
"=",
"self",
... | 27.857143 | 17.952381 |
def fast_forward_selection(scenarios, number_of_reduced_scenarios, probability=None):
"""Fast forward selection algorithm
Parameters
----------
scenarios : numpy.array
Contain the input scenarios.
The columns representing the individual scenarios
The rows are the vector of value... | [
"def",
"fast_forward_selection",
"(",
"scenarios",
",",
"number_of_reduced_scenarios",
",",
"probability",
"=",
"None",
")",
":",
"print",
"(",
"\"Running fast forward selection algorithm\"",
")",
"number_of_scenarios",
"=",
"scenarios",
".",
"shape",
"[",
"1",
"]",
"... | 38.433071 | 25.220472 |
def remember_order(self):
"""Verify that subsequent :func:`fudge.Fake.expects` are called in the right order.
For example::
>>> import fudge
>>> db = fudge.Fake('db').remember_order().expects('insert').expects('update')
>>> db.update()
Traceback (most re... | [
"def",
"remember_order",
"(",
"self",
")",
":",
"if",
"self",
".",
"_callable",
":",
"raise",
"FakeDeclarationError",
"(",
"\"remember_order() cannot be used for Fake(callable=True) or Fake(expect_call=True)\"",
")",
"self",
".",
"_expected_call_order",
"=",
"ExpectedCallOrde... | 38.578947 | 24.736842 |
def build_recursive_gcs_delocalize_env(source, outputs):
"""Return a multi-line string with export statements for the variables.
Arguments:
source: Folder with the data.
For example /mnt/data
outputs: a list of OutputFileParam
Returns:
a multi-line string with a shell script that sets en... | [
"def",
"build_recursive_gcs_delocalize_env",
"(",
"source",
",",
"outputs",
")",
":",
"filtered_outs",
"=",
"[",
"var",
"for",
"var",
"in",
"outputs",
"if",
"var",
".",
"recursive",
"and",
"var",
".",
"file_provider",
"==",
"job_model",
".",
"P_GCS",
"]",
"r... | 31.5 | 18.590909 |
def shutdown(self, force=False):
"""
Stop executing any further jobs. If the force argument is True,
the function does not wait until any queued jobs are completed but
stops immediately.
After emptying the queue it is restarted, so you may still call run()
after using th... | [
"def",
"shutdown",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
":",
"self",
".",
"join",
"(",
")",
"self",
".",
"_dbg",
"(",
"2",
",",
"'Shutting down queue...'",
")",
"self",
".",
"workqueue",
".",
"shutdown",
"(",
"True... | 32.894737 | 18.368421 |
def from_transitions(cls, initial_state, accepting_states, transition_function):
# type: (State, Set[State], NondeterministicTransitionFunction) -> NFA
"""
Initialize a DFA without explicitly specifying the set of states and the alphabet.
:param initial_state: the initial state.
... | [
"def",
"from_transitions",
"(",
"cls",
",",
"initial_state",
",",
"accepting_states",
",",
"transition_function",
")",
":",
"# type: (State, Set[State], NondeterministicTransitionFunction) -> NFA",
"states",
",",
"alphabet",
"=",
"_extract_states_from_nondeterministic_transition_fu... | 51.538462 | 30.615385 |
def Rx(rads: Union[float, sympy.Basic]) -> XPowGate:
"""Returns a gate with the matrix e^{-i X rads / 2}."""
pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
return XPowGate(exponent=rads / pi, global_shift=-0.5) | [
"def",
"Rx",
"(",
"rads",
":",
"Union",
"[",
"float",
",",
"sympy",
".",
"Basic",
"]",
")",
"->",
"XPowGate",
":",
"pi",
"=",
"sympy",
".",
"pi",
"if",
"protocols",
".",
"is_parameterized",
"(",
"rads",
")",
"else",
"np",
".",
"pi",
"return",
"XPow... | 58.25 | 13.5 |
def _notify_create_process(self, event):
"""
Notify the creation of a new process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
... | [
"def",
"_notify_create_process",
"(",
"self",
",",
"event",
")",
":",
"# Do not use super() here.",
"bCallHandler",
"=",
"_ThreadContainer",
".",
"_notify_create_process",
"(",
"self",
",",
"event",
")",
"bCallHandler",
"=",
"bCallHandler",
"and",
"_ModuleContainer",
... | 36.166667 | 18.277778 |
def _write(self, fp):
"""Write an .ini-format representation of the configuration state in
git compatible format"""
def write_section(name, section_dict):
fp.write(("[%s]\n" % name).encode(defenc))
for (key, value) in section_dict.items():
if key != "__nam... | [
"def",
"_write",
"(",
"self",
",",
"fp",
")",
":",
"def",
"write_section",
"(",
"name",
",",
"section_dict",
")",
":",
"fp",
".",
"write",
"(",
"(",
"\"[%s]\\n\"",
"%",
"name",
")",
".",
"encode",
"(",
"defenc",
")",
")",
"for",
"(",
"key",
",",
... | 45.533333 | 15.533333 |
def ratechangebase(self, ratefactor, current_base, new_base):
"""
Local helper function for changing currency base, returns new rate in new base
Defaults to ROUND_HALF_EVEN
"""
if self._multiplier is None:
self.log(logging.WARNING, "CurrencyHandler: changing base ours... | [
"def",
"ratechangebase",
"(",
"self",
",",
"ratefactor",
",",
"current_base",
",",
"new_base",
")",
":",
"if",
"self",
".",
"_multiplier",
"is",
"None",
":",
"self",
".",
"log",
"(",
"logging",
".",
"WARNING",
",",
"\"CurrencyHandler: changing base ourselves\"",... | 57.916667 | 24.25 |
def add_value_check(self, field_name, value_check,
code=VALUE_CHECK_FAILED,
message=MESSAGES[VALUE_CHECK_FAILED],
modulus=1):
"""
Add a value check function for the specified field.
Arguments
---------
`fie... | [
"def",
"add_value_check",
"(",
"self",
",",
"field_name",
",",
"value_check",
",",
"code",
"=",
"VALUE_CHECK_FAILED",
",",
"message",
"=",
"MESSAGES",
"[",
"VALUE_CHECK_FAILED",
"]",
",",
"modulus",
"=",
"1",
")",
":",
"# guard conditions",
"assert",
"field_name... | 34.09375 | 26.53125 |
def find_all_pistacking_pairs(self):
"""Main analysis function. Analyses each frame in the trajectory in search for pi-pi interactions between previously defined rings on
protein residues and ligand molecule. """
data = namedtuple("pistacking","frame time proteinring ligandring distance angle of... | [
"def",
"find_all_pistacking_pairs",
"(",
"self",
")",
":",
"data",
"=",
"namedtuple",
"(",
"\"pistacking\"",
",",
"\"frame time proteinring ligandring distance angle offset type resname resid segid\"",
")",
"i",
"=",
"0",
"if",
"self",
".",
"trajectory",
"==",
"[",
"]",... | 71.019231 | 41.480769 |
def format_name(self, format_name):
"""Set the default format name.
:param str format_name: The display format name.
:raises ValueError: if the format is not recognized.
"""
if format_name in self.supported_formats:
self._format_name = format_name
else:
... | [
"def",
"format_name",
"(",
"self",
",",
"format_name",
")",
":",
"if",
"format_name",
"in",
"self",
".",
"supported_formats",
":",
"self",
".",
"_format_name",
"=",
"format_name",
"else",
":",
"raise",
"ValueError",
"(",
"'unrecognized format_name \"{}\"'",
".",
... | 33.583333 | 16.583333 |
def generate_sub_codons_right(codons_dict):
"""Generate the sub_codons_right dictionary of codon suffixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
... | [
"def",
"generate_sub_codons_right",
"(",
"codons_dict",
")",
":",
"sub_codons_right",
"=",
"{",
"}",
"for",
"aa",
"in",
"codons_dict",
".",
"keys",
"(",
")",
":",
"sub_codons_right",
"[",
"aa",
"]",
"=",
"list",
"(",
"set",
"(",
"[",
"x",
"[",
"-",
"1"... | 32.47619 | 23.285714 |
def BSF(cpu, dest, src):
"""
Bit scan forward.
Searches the source operand (second operand) for the least significant
set bit (1 bit). If a least significant 1 bit is found, its bit index
is stored in the destination operand (first operand). The source operand
can be a r... | [
"def",
"BSF",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"value",
"=",
"src",
".",
"read",
"(",
")",
"flag",
"=",
"Operators",
".",
"EXTRACT",
"(",
"value",
",",
"0",
",",
"1",
")",
"==",
"1",
"res",
"=",
"0",
"for",
"pos",
"in",
"range",... | 38.076923 | 18.589744 |
def set_label(self, value,callb=None):
"""Convenience method to set the label of the device
This method will send a SetLabel message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param value: The new label
... | [
"def",
"set_label",
"(",
"self",
",",
"value",
",",
"callb",
"=",
"None",
")",
":",
"if",
"len",
"(",
"value",
")",
">",
"32",
":",
"value",
"=",
"value",
"[",
":",
"32",
"]",
"mypartial",
"=",
"partial",
"(",
"self",
".",
"resp_set_label",
",",
... | 42.904762 | 22.857143 |
def matches(self, address, name=None):
"""Check if this slot identifier matches the given tile.
Matching can happen either by address or by module name (not currently implemented).
Returns:
bool: True if there is a match, otherwise False.
"""
if self.controller:
... | [
"def",
"matches",
"(",
"self",
",",
"address",
",",
"name",
"=",
"None",
")",
":",
"if",
"self",
".",
"controller",
":",
"return",
"address",
"==",
"8",
"return",
"self",
".",
"address",
"==",
"address"
] | 29 | 21.692308 |
def check_config(config):
'''
Check the executor config file for consistency.
'''
# Check server URL
url = config.get("Server", "url")
try:
urlopen(url)
except Exception as e:
logger.error(
"The configured OpenSubmit server URL ({0}) seems to be invalid: {1}".... | [
"def",
"check_config",
"(",
"config",
")",
":",
"# Check server URL",
"url",
"=",
"config",
".",
"get",
"(",
"\"Server\"",
",",
"\"url\"",
")",
"try",
":",
"urlopen",
"(",
"url",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
... | 35.347826 | 22.913043 |
def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
"""
dump = dumps(self.query, sort_keys=True)
if isinstance(dump, str):
dump = dump.encode('utf-8')
return md5(dump).hexdigest() | [
"def",
"_hash",
"(",
"self",
")",
":",
"dump",
"=",
"dumps",
"(",
"self",
".",
"query",
",",
"sort_keys",
"=",
"True",
")",
"if",
"isinstance",
"(",
"dump",
",",
"str",
")",
":",
"dump",
"=",
"dump",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
... | 32.888889 | 12.222222 |
def read(self, filename=None, read_detection_catalog=True):
"""
Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_de... | [
"def",
"read",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"read_detection_catalog",
"=",
"True",
")",
":",
"tribe",
"=",
"Tribe",
"(",
")",
"families",
"=",
"[",
"]",
"if",
"filename",
"is",
"None",
":",
"# If there is no filename given, then read the exa... | 41.897059 | 17.044118 |
def remove(mode_id: str) -> bool:
"""
Removes the specified mode identifier from the active modes and returns
whether or not a remove operation was carried out. If the mode identifier
is not in the currently active modes, it does need to be removed.
"""
had_mode = has(mode_id)
if had_mode:... | [
"def",
"remove",
"(",
"mode_id",
":",
"str",
")",
"->",
"bool",
":",
"had_mode",
"=",
"has",
"(",
"mode_id",
")",
"if",
"had_mode",
":",
"_current_modes",
".",
"remove",
"(",
"mode_id",
")",
"return",
"had_mode"
] | 28.307692 | 22.153846 |
def make_anchor(file_path: pathlib.Path,
offset: int,
width: int,
context_width: int,
metadata,
encoding: str = 'utf-8',
handle=None):
"""Construct a new `Anchor`.
Args:
file_path: The absolute path to the t... | [
"def",
"make_anchor",
"(",
"file_path",
":",
"pathlib",
".",
"Path",
",",
"offset",
":",
"int",
",",
"width",
":",
"int",
",",
"context_width",
":",
"int",
",",
"metadata",
",",
"encoding",
":",
"str",
"=",
"'utf-8'",
",",
"handle",
"=",
"None",
")",
... | 34.045455 | 22.204545 |
def apply_boundary_conditions(self, **kwargs):
"""Applies any boundary conditions to the given values (e.g., applying
cyclic conditions, and/or reflecting values off of boundaries). This
is done by running `apply_conditions` of each bounds in self on the
corresponding value. See `boundar... | [
"def",
"apply_boundary_conditions",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"[",
"[",
"p",
",",
"self",
".",
"_bounds",
"[",
"p",
"]",
".",
"apply_conditions",
"(",
"val",
")",
"]",
"for",
"p",
",",
"val",
"in",
"kwar... | 42.045455 | 25.909091 |
def tlog(x, th=1, r=_display_max, d=_l_mmax):
"""
Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed v... | [
"def",
"tlog",
"(",
"x",
",",
"th",
"=",
"1",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"if",
"th",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Threshold value must be positive. %s given.'",
"%",
"th",
")",
"return",
"where",
... | 26.875 | 17.541667 |
def GreaterThan(self, value):
"""Sets the type of the WHERE clause as "greater than".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
"""
self._awql = self._CreateSingleValueCondition(value, '>')
return self._qu... | [
"def",
"GreaterThan",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_awql",
"=",
"self",
".",
"_CreateSingleValueCondition",
"(",
"value",
",",
"'>'",
")",
"return",
"self",
".",
"_query_builder"
] | 29.181818 | 19.545455 |
def ipv6_prefix_to_mask(prefix):
"""
ipv6 cidr prefix to net mask
:param prefix: cidr prefix, rang in (0, 128)
:type prefix: int
:return: comma separated ipv6 net mask code,
eg: ffff:ffff:ffff:ffff:0000:0000:0000:0000
:rtype: str
"""
if prefix > 128 or prefix < 0:
r... | [
"def",
"ipv6_prefix_to_mask",
"(",
"prefix",
")",
":",
"if",
"prefix",
">",
"128",
"or",
"prefix",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"invalid cidr prefix for ipv6\"",
")",
"else",
":",
"mask",
"=",
"(",
"(",
"1",
"<<",
"128",
")",
"-",
"1",
... | 32.681818 | 13.681818 |
def extract(input, output):
"""Extract public key from private key.
Given INPUT a private paillier key file as generated by generate, extract the
public key portion to OUTPUT.
Use "-" to output to stdout.
"""
log("Loading paillier keypair")
priv = json.load(input)
error_msg = "Invalid ... | [
"def",
"extract",
"(",
"input",
",",
"output",
")",
":",
"log",
"(",
"\"Loading paillier keypair\"",
")",
"priv",
"=",
"json",
".",
"load",
"(",
"input",
")",
"error_msg",
"=",
"\"Invalid private key\"",
"assert",
"'pub'",
"in",
"priv",
",",
"error_msg",
"as... | 31.875 | 13.5 |
def send_note(self, to, subject="", body="", noetid=""):
"""Send a note
:param to: The username(s) that this note is to
:param subject: The subject of the note
:param body: The body of the note
:param noetid: The UUID of the note that is being responded to
"""
... | [
"def",
"send_note",
"(",
"self",
",",
"to",
",",
"subject",
"=",
"\"\"",
",",
"body",
"=",
"\"\"",
",",
"noetid",
"=",
"\"\"",
")",
":",
"if",
"self",
".",
"standard_grant_type",
"is",
"not",
"\"authorization_code\"",
":",
"raise",
"DeviantartError",
"(",
... | 30.258065 | 22.16129 |
def import_gtfs(gtfs_sources, output, preserve_connection=False,
print_progress=True, location_name=None, **kwargs):
"""Import a GTFS database
gtfs_sources: str, dict, list
Paths to the gtfs zip file or to the directory containing the GTFS data.
Alternatively, a dict can be prov... | [
"def",
"import_gtfs",
"(",
"gtfs_sources",
",",
"output",
",",
"preserve_connection",
"=",
"False",
",",
"print_progress",
"=",
"True",
",",
"location_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"output",
",",
"sqlite3",
... | 37.370079 | 17.84252 |
def _cb_inform_sensor_status(self, msg):
"""Update received for an sensor."""
timestamp = msg.arguments[0]
num_sensors = int(msg.arguments[1])
assert len(msg.arguments) == 2 + num_sensors * 3
for n in xrange(num_sensors):
name = msg.arguments[2 + n * 3]
st... | [
"def",
"_cb_inform_sensor_status",
"(",
"self",
",",
"msg",
")",
":",
"timestamp",
"=",
"msg",
".",
"arguments",
"[",
"0",
"]",
"num_sensors",
"=",
"int",
"(",
"msg",
".",
"arguments",
"[",
"1",
"]",
")",
"assert",
"len",
"(",
"msg",
".",
"arguments",
... | 45 | 6 |
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.... | [
"def",
"sizeHint",
"(",
"self",
")",
":",
"font_metrics",
"=",
"QtGui",
".",
"QFontMetrics",
"(",
"self",
".",
"font",
")",
"margin",
"=",
"(",
"self",
".",
"_control",
".",
"frameWidth",
"(",
")",
"+",
"self",
".",
"_control",
".",
"document",
"(",
... | 44.12 | 18.08 |
def f_inv(self, z, max_iterations=250, y=None):
"""
Calculate the numerical inverse of f. This should be
overwritten for specific warping functions where the
inverse can be found in closed form.
:param max_iterations: maximum number of N.R. iterations
"""
z = z.... | [
"def",
"f_inv",
"(",
"self",
",",
"z",
",",
"max_iterations",
"=",
"250",
",",
"y",
"=",
"None",
")",
":",
"z",
"=",
"z",
".",
"copy",
"(",
")",
"y",
"=",
"np",
".",
"ones_like",
"(",
"z",
")",
"it",
"=",
"0",
"update",
"=",
"np",
".",
"inf... | 32.791667 | 17.958333 |
def send_result(self, additional_dict):
'''
Send a result to the RPC client
:param additional_dict: the dictionary with the response
'''
self.send_response(200)
self.send_header("Content-type", "application/json")
response = {
'jsonrpc': self.req_rpc_... | [
"def",
"send_result",
"(",
"self",
",",
"additional_dict",
")",
":",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"\"Content-type\"",
",",
"\"application/json\"",
")",
"response",
"=",
"{",
"'jsonrpc'",
":",
"self",
".",
"r... | 33.294118 | 14.941176 |
def write_recording(recording, save_path):
'''
Save recording extractor to MEArec format.
Parameters
----------
recording: RecordingExtractor
Recording extractor object to be saved
save_path: str
.h5 or .hdf5 path
'''
assert HAVE_MR... | [
"def",
"write_recording",
"(",
"recording",
",",
"save_path",
")",
":",
"assert",
"HAVE_MREX",
",",
"\"To use the MEArec extractors, install MEArec: \\n\\n pip install MEArec\\n\\n\"",
"save_path",
"=",
"Path",
"(",
"save_path",
")",
"if",
"save_path",
".",
"is_dir",
"(",... | 50.884615 | 24.423077 |
def exposure_notes(self):
"""Get the exposure specific notes defined in definitions.
This method will do a lookup in definitions and return the
exposure definition specific notes dictionary.
This is a helper function to make it
easy to get exposure specific notes from the defin... | [
"def",
"exposure_notes",
"(",
"self",
")",
":",
"notes",
"=",
"[",
"]",
"exposure",
"=",
"definition",
"(",
"self",
".",
"exposure",
".",
"keywords",
".",
"get",
"(",
"'exposure'",
")",
")",
"if",
"'notes'",
"in",
"exposure",
":",
"notes",
"+=",
"expos... | 38.038462 | 19.153846 |
def stop_notifications(self):
"""Stop the notifications thread.
:returns:
"""
with self._notifications_lock:
if not self.has_active_notification_thread:
return
thread = self._notifications_thread
self._notifications_thread = None
... | [
"def",
"stop_notifications",
"(",
"self",
")",
":",
"with",
"self",
".",
"_notifications_lock",
":",
"if",
"not",
"self",
".",
"has_active_notification_thread",
":",
"return",
"thread",
"=",
"self",
".",
"_notifications_thread",
"self",
".",
"_notifications_thread",... | 33.571429 | 10.428571 |
def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False):
"""
Run filename
args: command line arguments (string)
wdir: working directory
post_mortem: boolean, whether to enter post-mortem mode on error
"""
try:
filename = filename.decode('utf-8')
except (Uni... | [
"def",
"runfile",
"(",
"filename",
",",
"args",
"=",
"None",
",",
"wdir",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"post_mortem",
"=",
"False",
")",
":",
"try",
":",
"filename",
"=",
"filename",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"... | 33.156863 | 17.745098 |
def grayify_cmap(cmap):
"""Return a grayscale version of the colormap.
`Source`__
__ https://jakevdp.github.io/blog/2014/10/16/how-bad-is-your-colormap/
"""
cmap = plt.cm.get_cmap(cmap)
colors = cmap(np.arange(cmap.N))
# convert RGBA to perceived greyscale luminance
# cf. http://alienr... | [
"def",
"grayify_cmap",
"(",
"cmap",
")",
":",
"cmap",
"=",
"plt",
".",
"cm",
".",
"get_cmap",
"(",
"cmap",
")",
"colors",
"=",
"cmap",
"(",
"np",
".",
"arange",
"(",
"cmap",
".",
"N",
")",
")",
"# convert RGBA to perceived greyscale luminance",
"# cf. http... | 38.133333 | 17.933333 |
def active_time(self):
"""
The length of time (in seconds) that the device has been active for.
When the device is inactive, this is :data:`None`.
"""
if self._active_event.is_set():
return self.pin_factory.ticks_diff(self.pin_factory.ticks(),
... | [
"def",
"active_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"_active_event",
".",
"is_set",
"(",
")",
":",
"return",
"self",
".",
"pin_factory",
".",
"ticks_diff",
"(",
"self",
".",
"pin_factory",
".",
"ticks",
"(",
")",
",",
"self",
".",
"_last_ch... | 39.1 | 17.5 |
def check_guest_exist(check_index=0):
"""Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0
"""
def outer(f):
@six.wraps(f)
def inner(self, *args, **kw):
userids = args[check_index]
if isinstance(userids, list):
... | [
"def",
"check_guest_exist",
"(",
"check_index",
"=",
"0",
")",
":",
"def",
"outer",
"(",
"f",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"userids",
"=",
"args... | 31.655172 | 17.793103 |
def get_file(self, target, path, offset=None, length=None):
"""Get the contents of a file on the device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The... | [
"def",
"get_file",
"(",
"self",
",",
"target",
",",
"path",
",",
"offset",
"=",
"None",
",",
"length",
"=",
"None",
")",
":",
"command_block",
"=",
"FileSystemServiceCommandBlock",
"(",
")",
"command_block",
".",
"add_command",
"(",
"GetCommand",
"(",
"path"... | 60.346154 | 29.269231 |
def infer_typing_namedtuple_class(class_node, context=None):
"""Infer a subclass of typing.NamedTuple"""
# Check if it has the corresponding bases
annassigns_fields = [
annassign.target.name
for annassign in class_node.body
if isinstance(annassign, nodes.AnnAssign)
]
code = d... | [
"def",
"infer_typing_namedtuple_class",
"(",
"class_node",
",",
"context",
"=",
"None",
")",
":",
"# Check if it has the corresponding bases",
"annassigns_fields",
"=",
"[",
"annassign",
".",
"target",
".",
"name",
"for",
"annassign",
"in",
"class_node",
".",
"body",
... | 38 | 11 |
def makeFigFromFile(filename,*args,**kwargs):
"""
Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots
"""
import matplotlib.pyplot as plt
img = plt.imread(filename)
fig,ax = plt.subplots(*args,**kwargs)
ax.axis('off')
ax.... | [
"def",
"makeFigFromFile",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"img",
"=",
"plt",
".",
"imread",
"(",
"filename",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",... | 30.545455 | 12 |
def post(self):
'''
Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
... | [
"def",
"post",
"(",
"self",
")",
":",
"# if you aren't authenticated, redirect to login",
"if",
"not",
"self",
".",
"_verify_auth",
"(",
")",
":",
"self",
".",
"redirect",
"(",
"'/login'",
")",
"return",
"# verify that all lowstates are the correct client type",
"for",
... | 29.114286 | 19.057143 |
def pull(self, url):
"""
Tries to pull changes from external location.
"""
url = self._get_url(url)
try:
pull(self.baseui, self._repo, url)
except Abort, err:
# Propagate error but with vcs's type
raise RepositoryError(str(err)) | [
"def",
"pull",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"url",
")",
"try",
":",
"pull",
"(",
"self",
".",
"baseui",
",",
"self",
".",
"_repo",
",",
"url",
")",
"except",
"Abort",
",",
"err",
":",
"# Propagate e... | 30.3 | 10.1 |
def between(self, left, right, inclusive=True):
"""
Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are tr... | [
"def",
"between",
"(",
"self",
",",
"left",
",",
"right",
",",
"inclusive",
"=",
"True",
")",
":",
"if",
"inclusive",
":",
"lmask",
"=",
"self",
">=",
"left",
"rmask",
"=",
"self",
"<=",
"right",
"else",
":",
"lmask",
"=",
"self",
">",
"left",
"rma... | 24.864865 | 22.135135 |
def flatten_tree(tree, nested_attr='replies', depth_first=False):
"""Return a flattened version of the passed in tree.
:param nested_attr: The attribute name that contains the nested items.
Defaults to ``replies`` which is suitable for comments.
:param depth_first: When true, add to the list in a d... | [
"def",
"flatten_tree",
"(",
"tree",
",",
"nested_attr",
"=",
"'replies'",
",",
"depth_first",
"=",
"False",
")",
":",
"stack",
"=",
"deque",
"(",
"tree",
")",
"extend",
"=",
"stack",
".",
"extend",
"if",
"depth_first",
"else",
"stack",
".",
"extendleft",
... | 35.526316 | 20.421053 |
def _ge_from_lt(self, other):
"""Return a >= b. Computed by @total_ordering from (not a < b)."""
op_result = self.__lt__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result | [
"def",
"_ge_from_lt",
"(",
"self",
",",
"other",
")",
":",
"op_result",
"=",
"self",
".",
"__lt__",
"(",
"other",
")",
"if",
"op_result",
"is",
"NotImplemented",
":",
"return",
"NotImplemented",
"return",
"not",
"op_result"
] | 37 | 8.166667 |
def main():
"""Main method that runs the build"""
data = Common.open_file(F_INFO)
config = Common.open_file(F_CONFIG)
file_full_path = ""
env = load_jinja2_env(config['p_template'])
for index, page in data.iteritems():
logging.info('Creating ' + index + ' page:')
template = en... | [
"def",
"main",
"(",
")",
":",
"data",
"=",
"Common",
".",
"open_file",
"(",
"F_INFO",
")",
"config",
"=",
"Common",
".",
"open_file",
"(",
"F_CONFIG",
")",
"file_full_path",
"=",
"\"\"",
"env",
"=",
"load_jinja2_env",
"(",
"config",
"[",
"'p_template'",
... | 36.393939 | 21.151515 |
def isServiceNameAvailable(self,
name,
serviceType):
"""
Checks to see if a given service name and type are available for
publishing a new service. true indicates that the name and type is
not found in the organization's servi... | [
"def",
"isServiceNameAvailable",
"(",
"self",
",",
"name",
",",
"serviceType",
")",
":",
"_allowedTypes",
"=",
"[",
"'Feature Service'",
",",
"\"Map Service\"",
"]",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/isServiceNameAvailable\"",
"params",
"=",
"{",
"\"f\""... | 41.307692 | 17.230769 |
def fetch_open_data(cls, ifo, start, end, sample_rate=4096,
tag=None, version=None,
format='hdf5', host=GWOSC_DEFAULT_HOST,
verbose=False, cache=None, **kwargs):
"""Fetch open-access data from the LIGO Open Science Center
Parameter... | [
"def",
"fetch_open_data",
"(",
"cls",
",",
"ifo",
",",
"start",
",",
"end",
",",
"sample_rate",
"=",
"4096",
",",
"tag",
"=",
"None",
",",
"version",
"=",
"None",
",",
"format",
"=",
"'hdf5'",
",",
"host",
"=",
"GWOSC_DEFAULT_HOST",
",",
"verbose",
"="... | 42.589744 | 21.273504 |
def precmd(self, line):
"""Handle alias expansion and ';;' separator."""
if not line.strip():
return line
args = line.split()
while args[0] in self.aliases:
line = self.aliases[args[0]]
ii = 1
for tmpArg in args[1:]:
line = ... | [
"def",
"precmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"return",
"line",
"args",
"=",
"line",
".",
"split",
"(",
")",
"while",
"args",
"[",
"0",
"]",
"in",
"self",
".",
"aliases",
":",
"line",
"="... | 36.333333 | 9.333333 |
def warn_deprecated(
since, message='', name='', alternative='', pending=False,
obj_type='attribute', addendum='', removal=''):
"""
Used to display deprecation in a standard way.
Parameters
----------
since : str
The release at which this API became deprecated.
message : ... | [
"def",
"warn_deprecated",
"(",
"since",
",",
"message",
"=",
"''",
",",
"name",
"=",
"''",
",",
"alternative",
"=",
"''",
",",
"pending",
"=",
"False",
",",
"obj_type",
"=",
"'attribute'",
",",
"addendum",
"=",
"''",
",",
"removal",
"=",
"''",
")",
"... | 44.659574 | 19.382979 |
def parse_network_osm_query(data):
"""
Convert OSM query data to DataFrames of ways and way-nodes.
Parameters
----------
data : dict
Result of an OSM query.
Returns
-------
nodes, ways, waynodes : pandas.DataFrame
"""
if len(data['elements']) == 0:
raise Runtim... | [
"def",
"parse_network_osm_query",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
"[",
"'elements'",
"]",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"'OSM query results contain no data.'",
")",
"nodes",
"=",
"[",
"]",
"ways",
"=",
"[",
"]",
"wayno... | 24.352941 | 20.058824 |
def find_expired_nodes(self, node_ids=None):
"""
Detects connections that have held a reference for longer than its
process_ttl without refreshing its session. This function does not
actually removed them from the hash. (See remove_expired_nodes.)
:param list node_ids: optional,... | [
"def",
"find_expired_nodes",
"(",
"self",
",",
"node_ids",
"=",
"None",
")",
":",
"if",
"node_ids",
":",
"nodes",
"=",
"zip",
"(",
"node_ids",
",",
"[",
"int",
"(",
"t",
")",
"for",
"t",
"in",
"self",
".",
"conn",
".",
"client",
".",
"hmget",
"(",
... | 47.333333 | 26.222222 |
def setHeight(self, personID, height):
"""setHeight(string, double) -> None
Sets the height in m for this person.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_PERSON_VARIABLE, tc.VAR_HEIGHT, personID, height) | [
"def",
"setHeight",
"(",
"self",
",",
"personID",
",",
"height",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_PERSON_VARIABLE",
",",
"tc",
".",
"VAR_HEIGHT",
",",
"personID",
",",
"height",
")"
] | 35.714286 | 11.285714 |
def derive(self, path):
"""
:param path: a path like "m/44'/0'/1'/0/10" if deriving from a master key,
or a relative path like "./0/10"
:return: the derived ExtendedPublicKey if deriving from an ExtendedPublicKey,
the derived ExtendedPrivateKey if deriving f... | [
"def",
"derive",
"(",
"self",
",",
"path",
")",
":",
"steps",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"if",
"steps",
"[",
"0",
"]",
"not",
"in",
"{",
"'m'",
",",
"'.'",
"}",
":",
"raise",
"ValueError",
"(",
"'Invalid derivation path: {}'",
".",
... | 36.28 | 21.24 |
def all_network_files():
"""All network files"""
# TODO: list explicitly since some are missing?
network_types = [
'AND-circle',
'MAJ-specialized',
'MAJ-complete',
'iit-3.0-modular'
]
network_sizes = range(5, 8)
network_files = []
for n in network_sizes:
... | [
"def",
"all_network_files",
"(",
")",
":",
"# TODO: list explicitly since some are missing?",
"network_types",
"=",
"[",
"'AND-circle'",
",",
"'MAJ-specialized'",
",",
"'MAJ-complete'",
",",
"'iit-3.0-modular'",
"]",
"network_sizes",
"=",
"range",
"(",
"5",
",",
"8",
... | 27.466667 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.