text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def default_tree_traversal(root, leaves):
""" default tree traversal """
objs = [('#', root)]
while len(objs) > 0:
path, obj = objs.pop()
# name of child are json-pointer encoded, we don't have
# to encode it again.
if obj.__class__ not in leaves:
objs.extend(map... | [
"def",
"default_tree_traversal",
"(",
"root",
",",
"leaves",
")",
":",
"objs",
"=",
"[",
"(",
"'#'",
",",
"root",
")",
"]",
"while",
"len",
"(",
"objs",
")",
">",
"0",
":",
"path",
",",
"obj",
"=",
"objs",
".",
"pop",
"(",
")",
"# name of child are... | 39.214286 | 21.214286 |
def text2text_distill_iterator(source_txt_path, target_txt_path,
distill_txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of files."""
for inputs, targets, dist_targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path),
... | [
"def",
"text2text_distill_iterator",
"(",
"source_txt_path",
",",
"target_txt_path",
",",
"distill_txt_path",
")",
":",
"for",
"inputs",
",",
"targets",
",",
"dist_targets",
"in",
"zip",
"(",
"txt_line_iterator",
"(",
"source_txt_path",
")",
",",
"txt_line_iterator",
... | 61.714286 | 16.285714 |
def incr(l, cap): # to increment a list up to a max-list of 'cap'
"""
Simulate a counting system from an n-dimensional list.
Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n
Returns: next set of values for list l, OR -1 (if overflow)
"""
l[0] = l[0] + 1 # e.g., [0,0,0]... | [
"def",
"incr",
"(",
"l",
",",
"cap",
")",
":",
"# to increment a list up to a max-list of 'cap'",
"l",
"[",
"0",
"]",
"=",
"l",
"[",
"0",
"]",
"+",
"1",
"# e.g., [0,0,0] --> [2,4,3] (=cap)",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"l",
")",
")",
":",... | 40.6 | 22.333333 |
def _spikes_in_clusters(spike_clusters, clusters):
"""Return the ids of all spikes belonging to the specified clusters."""
if len(spike_clusters) == 0 or len(clusters) == 0:
return np.array([], dtype=np.int)
return np.nonzero(np.in1d(spike_clusters, clusters))[0] | [
"def",
"_spikes_in_clusters",
"(",
"spike_clusters",
",",
"clusters",
")",
":",
"if",
"len",
"(",
"spike_clusters",
")",
"==",
"0",
"or",
"len",
"(",
"clusters",
")",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"np... | 55.8 | 8.8 |
def html_path(builder, pagename=None):
"""Calculate the relative path to the Slides for pagename."""
return builder.get_relative_uri(
pagename or builder.current_docname,
os.path.join(
builder.app.config.slide_html_relative_path,
pagename or builder.current_docname,
... | [
"def",
"html_path",
"(",
"builder",
",",
"pagename",
"=",
"None",
")",
":",
"return",
"builder",
".",
"get_relative_uri",
"(",
"pagename",
"or",
"builder",
".",
"current_docname",
",",
"os",
".",
"path",
".",
"join",
"(",
"builder",
".",
"app",
".",
"con... | 35.333333 | 13.666667 |
def setTreeDoc(self, doc):
"""update all nodes under the tree to point to the right
document """
if doc is None: doc__o = None
else: doc__o = doc._o
libxml2mod.xmlSetTreeDoc(self._o, doc__o) | [
"def",
"setTreeDoc",
"(",
"self",
",",
"doc",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"libxml2mod",
".",
"xmlSetTreeDoc",
"(",
"self",
".",
"_o",
",",
"doc__o",
")"
] | 38 | 6.166667 |
def release(self, connection):
"Releases the connection back to the pool"
self._checkpid()
if connection.pid != self.pid:
return
self._in_use_connections.remove(connection)
# discard connection with unread response
if connection.awaiting_response:
... | [
"def",
"release",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"_checkpid",
"(",
")",
"if",
"connection",
".",
"pid",
"!=",
"self",
".",
"pid",
":",
"return",
"self",
".",
"_in_use_connections",
".",
"remove",
"(",
"connection",
")",
"# discard... | 37.333333 | 11 |
def from_dict(data, ctx):
"""
Instantiate a new CalculatedTradeState from a dict (generally from
loading a JSON response). The data used to instantiate the
CalculatedTradeState is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately.
... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'unrealizedPL'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'unrealizedPL'",
"]",
"=",
"ctx",
".",
"convert_decimal_n... | 33.761905 | 19.857143 |
def to_op(self):
"""
Extracts the modification operation from the set.
:rtype: dict, None
"""
if not self._adds and not self._removes:
return None
changes = {}
if self._adds:
changes['adds'] = list(self._adds)
if self._removes:
... | [
"def",
"to_op",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_adds",
"and",
"not",
"self",
".",
"_removes",
":",
"return",
"None",
"changes",
"=",
"{",
"}",
"if",
"self",
".",
"_adds",
":",
"changes",
"[",
"'adds'",
"]",
"=",
"list",
"(",
"s... | 27.071429 | 14.928571 |
def get_account_details(self, account):
"""
This method can be used in a number of scenarios:
1. When it is necessary to very account information
2. When there's a need to filter transactions by an account id
3. When account details (e.g. name of account) are needed
"""
... | [
"def",
"get_account_details",
"(",
"self",
",",
"account",
")",
":",
"_form",
"=",
"mechanize",
".",
"HTMLForm",
"(",
"self",
".",
"SEARCH_MEMBERS_URL",
",",
"method",
"=",
"\"POST\"",
")",
"_form",
".",
"new_control",
"(",
"'text'",
",",
"'username'",
",",
... | 40.111111 | 19.37037 |
def _bcrypt_generate_pair(algorithm, bit_size=None, curve=None):
"""
Generates a public/private key pair using CNG
:param algorithm:
The key algorithm - "rsa", "dsa" or "ec"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or ... | [
"def",
"_bcrypt_generate_pair",
"(",
"algorithm",
",",
"bit_size",
"=",
"None",
",",
"curve",
"=",
"None",
")",
":",
"if",
"algorithm",
"==",
"'rsa'",
":",
"alg_constant",
"=",
"BcryptConst",
".",
"BCRYPT_RSA_ALGORITHM",
"struct_type",
"=",
"'BCRYPT_RSAKEY_BLOB'",... | 38.648438 | 25.523438 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(self, 'normalized') and self.normalized is not None:
_dict['normalized'] = self.normaliz... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'text'",
")",
"and",
"self",
".",
"text",
"is",
"not",
"None",
":",
"_dict",
"[",
"'text'",
"]",
"=",
"self",
".",
"text",
"if",
"hasattr",
"(",... | 44.3 | 15.2 |
def ca_bundle(self, ca_bundle):
"""Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:par... | [
"def",
"ca_bundle",
"(",
"self",
",",
"ca_bundle",
")",
":",
"if",
"ca_bundle",
"is",
"not",
"None",
"and",
"not",
"re",
".",
"search",
"(",
"r'^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$'",
",",
"ca_bundle",
")",
":",
"# noqa: E501",
"rai... | 67.583333 | 52.166667 |
def login(config, username=None, password=None, email=None, url=None, client=None, *args, **kwargs):
'''
Wrapper to the docker.py login method
'''
try:
c = (_get_client(config) if not client else client)
lg = c.login(username, password, email, url)
print "%s logged to %s"%(userna... | [
"def",
"login",
"(",
"config",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"email",
"=",
"None",
",",
"url",
"=",
"None",
",",
"client",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"c",
"="... | 42.25 | 28.416667 |
def cumulative_distribution(self, X):
"""Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative density for X.
"""
self.check_fit()
return norm.cdf(X, loc=self.mean,... | [
"def",
"cumulative_distribution",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"return",
"norm",
".",
"cdf",
"(",
"X",
",",
"loc",
"=",
"self",
".",
"mean",
",",
"scale",
"=",
"self",
".",
"std",
")"
] | 29.636364 | 15.909091 |
def rename_event_type(self, name, new_name):
"""Rename event type."""
if name not in self.event_types:
lg.info('Event type ' + name + ' was not found.')
events = self.rater.find('events')
for e in list(events):
if e.get('type') == name:
e.set('t... | [
"def",
"rename_event_type",
"(",
"self",
",",
"name",
",",
"new_name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"event_types",
":",
"lg",
".",
"info",
"(",
"'Event type '",
"+",
"name",
"+",
"' was not found.'",
")",
"events",
"=",
"self",
".",
... | 26.461538 | 17.076923 |
def _import(self, record_key, record_data, overwrite=True, last_modified=0.0, **kwargs):
'''
a helper method for other storage clients to import into appdata
:param record_key: string with key for record
:param record_data: byte data for body of record
... | [
"def",
"_import",
"(",
"self",
",",
"record_key",
",",
"record_data",
",",
"overwrite",
"=",
"True",
",",
"last_modified",
"=",
"0.0",
",",
"*",
"*",
"kwargs",
")",
":",
"# construct and validate file path\r",
"file_path",
"=",
"os",
".",
"path",
".",
"join"... | 36.454545 | 19.409091 |
def connect_ws(self, path: str) -> _WSRequestContextManager:
"""
Connect to a websocket in order to use API parameters
:param path: the url path
:return:
"""
client = API(self.endpoint.conn_handler(self.session, self.proxy))
return client.connect_ws(path) | [
"def",
"connect_ws",
"(",
"self",
",",
"path",
":",
"str",
")",
"->",
"_WSRequestContextManager",
":",
"client",
"=",
"API",
"(",
"self",
".",
"endpoint",
".",
"conn_handler",
"(",
"self",
".",
"session",
",",
"self",
".",
"proxy",
")",
")",
"return",
... | 33.777778 | 16.444444 |
def note_emojis(self, item_type, item_id, note_id):
"""Get emojis of a note"""
payload = {
'order_by': 'updated_at',
'sort': 'asc',
'per_page': PER_PAGE
}
path = urijoin(item_type, str(item_id), GitLabClient.NOTES,
str(note_id)... | [
"def",
"note_emojis",
"(",
"self",
",",
"item_type",
",",
"item_id",
",",
"note_id",
")",
":",
"payload",
"=",
"{",
"'order_by'",
":",
"'updated_at'",
",",
"'sort'",
":",
"'asc'",
",",
"'per_page'",
":",
"PER_PAGE",
"}",
"path",
"=",
"urijoin",
"(",
"ite... | 29 | 19.769231 |
def prepare_resampler(source_area, destination_area, resampler=None, **resample_kwargs):
"""Instantiate and return a resampler."""
if resampler is None:
LOG.info("Using default KDTree resampler")
resampler = 'kd_tree'
if isinstance(resampler, BaseResampler):
raise ValueError("Trying... | [
"def",
"prepare_resampler",
"(",
"source_area",
",",
"destination_area",
",",
"resampler",
"=",
"None",
",",
"*",
"*",
"resample_kwargs",
")",
":",
"if",
"resampler",
"is",
"None",
":",
"LOG",
".",
"info",
"(",
"\"Using default KDTree resampler\"",
")",
"resampl... | 37.347826 | 16.608696 |
def get_subgraph(self, subvertices, normalize=False):
"""Constructs a subgraph of the current graph
Arguments:
| ``subvertices`` -- The vertices that should be retained.
| ``normalize`` -- Whether or not the vertices should renumbered and
reduced to the given... | [
"def",
"get_subgraph",
"(",
"self",
",",
"subvertices",
",",
"normalize",
"=",
"False",
")",
":",
"if",
"normalize",
":",
"revorder",
"=",
"dict",
"(",
"(",
"j",
",",
"i",
")",
"for",
"i",
",",
"j",
"in",
"enumerate",
"(",
"subvertices",
")",
")",
... | 46.208955 | 23.343284 |
def write_vmware_file(path, pairs):
"""
Write a VMware file (excepting VMX file).
:param path: path to the VMware file
:param pairs: settings to write
"""
encoding = "utf-8"
if ".encoding" in pairs:
file_encoding = pairs[".encoding"]
try:... | [
"def",
"write_vmware_file",
"(",
"path",
",",
"pairs",
")",
":",
"encoding",
"=",
"\"utf-8\"",
"if",
"\".encoding\"",
"in",
"pairs",
":",
"file_encoding",
"=",
"pairs",
"[",
"\".encoding\"",
"]",
"try",
":",
"codecs",
".",
"lookup",
"(",
"file_encoding",
")"... | 36.25 | 14.25 |
def can_create_asset_content(self, asset_id=None):
"""Tests if this user can create content for ``Assets``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating an ``Asset``
will result in a ``PermissionDenied``. This is int... | [
"def",
"can_create_asset_content",
"(",
"self",
",",
"asset_id",
"=",
"None",
")",
":",
"url_path",
"=",
"construct_url",
"(",
"'authorization'",
",",
"bank_id",
"=",
"self",
".",
"_catalog_idstr",
")",
"return",
"self",
".",
"_get_request",
"(",
"url_path",
"... | 45.619048 | 22.52381 |
def servicestore_factory(registry, database=None):
"""
Creates a service store with the interface of :class:`twitcher.store.ServiceStore`.
By default the mongodb implementation will be used.
:return: An instance of :class:`twitcher.store.ServiceStore`.
"""
database = database or 'mongodb'
i... | [
"def",
"servicestore_factory",
"(",
"registry",
",",
"database",
"=",
"None",
")",
":",
"database",
"=",
"database",
"or",
"'mongodb'",
"if",
"database",
"==",
"'mongodb'",
":",
"db",
"=",
"_mongodb",
"(",
"registry",
")",
"store",
"=",
"MongodbServiceStore",
... | 34.785714 | 17.071429 |
def _draw_lines(self, bg, colour, extent, line, xo, yo):
"""Draw a set of lines from a vector tile."""
coords = [self._scale_coords(x, y, extent, xo, yo) for x, y in line]
self._draw_lines_internal(coords, colour, bg) | [
"def",
"_draw_lines",
"(",
"self",
",",
"bg",
",",
"colour",
",",
"extent",
",",
"line",
",",
"xo",
",",
"yo",
")",
":",
"coords",
"=",
"[",
"self",
".",
"_scale_coords",
"(",
"x",
",",
"y",
",",
"extent",
",",
"xo",
",",
"yo",
")",
"for",
"x",... | 59.5 | 16.25 |
def update_clusterer(self, inst):
"""
Updates the clusterer with the instance.
:param inst: the Instance to update the clusterer with
:type inst: Instance
"""
if self.is_updateable:
javabridge.call(self.jobject, "updateClusterer", "(Lweka/core/Instance;)V", i... | [
"def",
"update_clusterer",
"(",
"self",
",",
"inst",
")",
":",
"if",
"self",
".",
"is_updateable",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"updateClusterer\"",
",",
"\"(Lweka/core/Instance;)V\"",
",",
"inst",
".",
"jobject",
")",
... | 38.636364 | 21.363636 |
def t_istringquotes_css_string(self, t):
r'[^"@]+'
t.lexer.lineno += t.value.count('\n')
return t | [
"def",
"t_istringquotes_css_string",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"t",
".",
"value",
".",
"count",
"(",
"'\\n'",
")",
"return",
"t"
] | 29.5 | 13 |
def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
... | [
"def",
"atlas_find_missing_zonefile_availability",
"(",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"missing_zonefile_info",
"=",
"None",
")",
":",
"# which zonefiles do we have?",
"bit_offset",
"=",
"0",
"bit_count",
"=",
"1... | 33.333333 | 21.288889 |
def _PrintVSSStoreIdentifiersOverview(
self, volume_system, volume_identifiers):
"""Prints an overview of VSS store identifiers.
Args:
volume_system (dfvfs.VShadowVolumeSystem): volume system.
volume_identifiers (list[str]): allowed volume identifiers.
Raises:
SourceScannerError: i... | [
"def",
"_PrintVSSStoreIdentifiersOverview",
"(",
"self",
",",
"volume_system",
",",
"volume_identifiers",
")",
":",
"header",
"=",
"'The following Volume Shadow Snapshots (VSS) were found:\\n'",
"self",
".",
"_output_writer",
".",
"Write",
"(",
"header",
")",
"column_names"... | 36.368421 | 21.105263 |
def optional_manga_logged_in(func):
"""Check if andoid manga API is logged in and login if credentials were provided,
implies `require_session_started`
"""
@functools.wraps(func)
@require_session_started
def inner_func(self, *pargs, **kwargs):
if not self._manga_api.logged_in and self.ha... | [
"def",
"optional_manga_logged_in",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"@",
"require_session_started",
"def",
"inner_func",
"(",
"self",
",",
"*",
"pargs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
... | 45.461538 | 12.692308 |
def top(**kwargs):
'''
Query |reclass| for the top data (states of the minions).
'''
# If reclass is installed, __virtual__ put it onto the search path, so we
# don't need to protect against ImportError:
# pylint: disable=3rd-party-module-not-gated
from reclass.adapters.salt import top as r... | [
"def",
"top",
"(",
"*",
"*",
"kwargs",
")",
":",
"# If reclass is installed, __virtual__ put it onto the search path, so we",
"# don't need to protect against ImportError:",
"# pylint: disable=3rd-party-module-not-gated",
"from",
"reclass",
".",
"adapters",
".",
"salt",
"import",
... | 39.076923 | 23.6 |
def set_datarate(self, rate, rfm=1):
"""Set datarate (baudrate)."""
cmds = {1: 'r', 2: 'R'}
self._write_cmd('{}{}'.format(rate, cmds[rfm])) | [
"def",
"set_datarate",
"(",
"self",
",",
"rate",
",",
"rfm",
"=",
"1",
")",
":",
"cmds",
"=",
"{",
"1",
":",
"'r'",
",",
"2",
":",
"'R'",
"}",
"self",
".",
"_write_cmd",
"(",
"'{}{}'",
".",
"format",
"(",
"rate",
",",
"cmds",
"[",
"rfm",
"]",
... | 40 | 7 |
def output_directory(self) -> str:
"""
Returns the directory where the project results files will be written
"""
return os.path.join(self.results_path, 'reports', self.uuid, 'latest') | [
"def",
"output_directory",
"(",
"self",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_path",
",",
"'reports'",
",",
"self",
".",
"uuid",
",",
"'latest'",
")"
] | 35.166667 | 20.166667 |
def assert_iter(**kw):
"""
Asserts if a given values implements a valid iterable interface.
Arguments:
**kw (mixed): value to check if it is an iterable.
Raises:
TypeError: if assertion fails.
"""
for name, value in kw.items():
if not isiter(value):
raise Ty... | [
"def",
"assert_iter",
"(",
"*",
"*",
"kw",
")",
":",
"for",
"name",
",",
"value",
"in",
"kw",
".",
"items",
"(",
")",
":",
"if",
"not",
"isiter",
"(",
"value",
")",
":",
"raise",
"TypeError",
"(",
"'paco: {} must be an iterable object'",
".",
"format",
... | 27.357143 | 18.357143 |
def key(**kwargs):
''' Display system key. '''
output, err = cli_syncthing_adapter.key(device=True)
click.echo("%s" % output, err=err) | [
"def",
"key",
"(",
"*",
"*",
"kwargs",
")",
":",
"output",
",",
"err",
"=",
"cli_syncthing_adapter",
".",
"key",
"(",
"device",
"=",
"True",
")",
"click",
".",
"echo",
"(",
"\"%s\"",
"%",
"output",
",",
"err",
"=",
"err",
")"
] | 27.6 | 18 |
def set_pre_handler(self, handler):
'''pre handler push
return: ret_error or ret_ok
'''
set_flag = False
for protoc in self._pre_handler_table:
if isinstance(handler, self._pre_handler_table[protoc]["type"]):
self._pre_handler_table[protoc]["obj"] = ha... | [
"def",
"set_pre_handler",
"(",
"self",
",",
"handler",
")",
":",
"set_flag",
"=",
"False",
"for",
"protoc",
"in",
"self",
".",
"_pre_handler_table",
":",
"if",
"isinstance",
"(",
"handler",
",",
"self",
".",
"_pre_handler_table",
"[",
"protoc",
"]",
"[",
"... | 33.666667 | 17.333333 |
def _iter_sims(self):
"""iterate on similarities among all files, by making a cartesian
product
"""
for idx, lineset in enumerate(self.linesets[:-1]):
for lineset2 in self.linesets[idx + 1 :]:
for sim in self._find_common(lineset, lineset2):
... | [
"def",
"_iter_sims",
"(",
"self",
")",
":",
"for",
"idx",
",",
"lineset",
"in",
"enumerate",
"(",
"self",
".",
"linesets",
"[",
":",
"-",
"1",
"]",
")",
":",
"for",
"lineset2",
"in",
"self",
".",
"linesets",
"[",
"idx",
"+",
"1",
":",
"]",
":",
... | 40.5 | 13.75 |
def payload(self):
"""
Returns:
`str` when not json.
`dict` when json.
"""
if self.is_json:
if not self._body_parsed:
if hasattr(self._body, 'decode'):
body = self._body.decode('utf-8')
else:
... | [
"def",
"payload",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_json",
":",
"if",
"not",
"self",
".",
"_body_parsed",
":",
"if",
"hasattr",
"(",
"self",
".",
"_body",
",",
"'decode'",
")",
":",
"body",
"=",
"self",
".",
"_body",
".",
"decode",
"(",... | 25.777778 | 14.777778 |
def fixed_interval_scheduler(interval):
"""
A scheduler that ticks at fixed intervals of "interval" seconds
"""
start = time.time()
next_tick = start
while True:
next_tick += interval
yield next_tick | [
"def",
"fixed_interval_scheduler",
"(",
"interval",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"next_tick",
"=",
"start",
"while",
"True",
":",
"next_tick",
"+=",
"interval",
"yield",
"next_tick"
] | 23.1 | 15.7 |
def gsod_day_parser(line, SI=True, to_datetime=True):
'''One line (one file) parser of data in the format of the GSOD database.
Returns all parsed results as a namedtuple for reduced memory consumption.
Will convert all data to base SI units unless the `SI` flag is set to
False. As the values are round... | [
"def",
"gsod_day_parser",
"(",
"line",
",",
"SI",
"=",
"True",
",",
"to_datetime",
"=",
"True",
")",
":",
"# Ignore STN--- and WBAN, 8-12 characters",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
"2",
":",
"]",
"# For the cas... | 38.172043 | 18.430108 |
def _validate_obj_by_schema(self, obj, obj_nex_id, vc):
"""Creates:
errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET,
warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET,
or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET.
... | [
"def",
"_validate_obj_by_schema",
"(",
"self",
",",
"obj",
",",
"obj_nex_id",
",",
"vc",
")",
":",
"return",
"self",
".",
"_validate_id_obj_list_by_schema",
"(",
"[",
"(",
"obj_nex_id",
",",
"obj",
")",
"]",
",",
"vc",
",",
"group_by_warning",
"=",
"False",
... | 60.857143 | 28 |
def ping(
self,
destination,
source=c.PING_SOURCE,
ttl=c.PING_TTL,
timeout=c.PING_TIMEOUT,
size=c.PING_SIZE,
count=c.PING_COUNT,
vrf=c.PING_VRF,
):
"""
Execute ping on the device and returns a dictionary with the result.
Output ... | [
"def",
"ping",
"(",
"self",
",",
"destination",
",",
"source",
"=",
"c",
".",
"PING_SOURCE",
",",
"ttl",
"=",
"c",
".",
"PING_TTL",
",",
"timeout",
"=",
"c",
".",
"PING_TIMEOUT",
",",
"size",
"=",
"c",
".",
"PING_SIZE",
",",
"count",
"=",
"c",
".",... | 37.516949 | 14.211864 |
def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta,
save_memory=False):
"""wrappe calling cpp splitting function"""
return CSP.best_split_full_model(X, Uy, C, S, U, noderange, delta) | [
"def",
"cpp_best_split_full_model",
"(",
"X",
",",
"Uy",
",",
"C",
",",
"S",
",",
"U",
",",
"noderange",
",",
"delta",
",",
"save_memory",
"=",
"False",
")",
":",
"return",
"CSP",
".",
"best_split_full_model",
"(",
"X",
",",
"Uy",
",",
"C",
",",
"S",... | 57.25 | 15.5 |
def glance_create_image(self, glance, image_name, image_url,
download_dir='tests',
hypervisor_type=None,
disk_format='qcow2',
architecture='x86_64',
container_format='bare'):
... | [
"def",
"glance_create_image",
"(",
"self",
",",
"glance",
",",
"image_name",
",",
"image_url",
",",
"download_dir",
"=",
"'tests'",
",",
"hypervisor_type",
"=",
"None",
",",
"disk_format",
"=",
"'qcow2'",
",",
"architecture",
"=",
"'x86_64'",
",",
"container_for... | 42.458333 | 18.125 |
def add(self, requester: int, track: dict):
""" Adds a track to the queue. """
self.queue.append(AudioTrack().build(track, requester)) | [
"def",
"add",
"(",
"self",
",",
"requester",
":",
"int",
",",
"track",
":",
"dict",
")",
":",
"self",
".",
"queue",
".",
"append",
"(",
"AudioTrack",
"(",
")",
".",
"build",
"(",
"track",
",",
"requester",
")",
")"
] | 50 | 9 |
def run(self, value, model=None, context=None):
"""
Run validation
Wraps concrete implementation to ensure custom validators return
proper type of result.
:param value: a value to validate
:param model: parent model of the property
:pa... | [
"def",
"run",
"(",
"self",
",",
"value",
",",
"model",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"res",
"=",
"self",
".",
"validate",
"(",
"value",
",",
"model",
",",
"context",
")",
"if",
"not",
"isinstance",
"(",
"res",
",",
"Error",
... | 36.333333 | 17.285714 |
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# Check if we have the tped and the tfam files",
"for",
"filename",
"in",
"[",
"args",
".",
"bfile",
"+",
"i",
"for",
"i",
"in",
"[",
"\".bed\"",
",",
"\".bim\"",
",",
"\".fam\"",
"]",
"]",
":",
"if",
"not",
"os"... | 33.5 | 22.541667 |
def make_app(global_conf, full_stack=True, **app_conf):
"""
Set tg2-raptorized up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for tg2-raptorized (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:... | [
"def",
"make_app",
"(",
"global_conf",
",",
"full_stack",
"=",
"True",
",",
"*",
"*",
"app_conf",
")",
":",
"app",
"=",
"make_base_app",
"(",
"global_conf",
",",
"full_stack",
"=",
"True",
",",
"*",
"*",
"app_conf",
")",
"# Wrap your base TurboGears 2 applicat... | 34.192308 | 24.807692 |
def _evaluatelinearForces(Pot,x,t=0.):
"""Raw, undecorated function for internal use"""
if isinstance(Pot,list):
sum= 0.
for pot in Pot:
sum+= pot._force_nodecorator(x,t=t)
return sum
elif isinstance(Pot,linearPotential):
return Pot._force_nodecorator(x,t=t)
e... | [
"def",
"_evaluatelinearForces",
"(",
"Pot",
",",
"x",
",",
"t",
"=",
"0.",
")",
":",
"if",
"isinstance",
"(",
"Pot",
",",
"list",
")",
":",
"sum",
"=",
"0.",
"for",
"pot",
"in",
"Pot",
":",
"sum",
"+=",
"pot",
".",
"_force_nodecorator",
"(",
"x",
... | 41.454545 | 16.909091 |
def print_exception(etype, value, tb, limit=None, file=None, chain=True):
"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
This differs from print_tb() in the following ways: (1) if
traceback is not None, it prints a header "Traceback (most recent
call last):"; (2) it prints th... | [
"def",
"print_exception",
"(",
"etype",
",",
"value",
",",
"tb",
",",
"limit",
"=",
"None",
",",
"file",
"=",
"None",
",",
"chain",
"=",
"True",
")",
":",
"import",
"traceback",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stderr",
"i... | 42.4 | 20.2 |
def _generate_atom_feed(self, feed):
"""
A function returning a feed like `feedgen.feed.FeedGenerator`.
The function can be overwritten when used in other applications.
:param feed: a feed object
:return: an atom feed `feedgen.feed.FeedGenerator`
"""
atom_feed = ... | [
"def",
"_generate_atom_feed",
"(",
"self",
",",
"feed",
")",
":",
"atom_feed",
"=",
"self",
".",
"init_atom_feed",
"(",
"feed",
")",
"atom_feed",
".",
"title",
"(",
"\"Feed\"",
")",
"return",
"atom_feed"
] | 35.636364 | 14.545455 |
def getKeyName(username, date, blob_key):
"""Returns the internal key for a particular item in the database.
Our items are stored with keys of the form 'user/date/blob_key' ('/' is
not the real separator, but __SEP is).
Args:
username: The given user's e-mail address.
date: A datetime obje... | [
"def",
"getKeyName",
"(",
"username",
",",
"date",
",",
"blob_key",
")",
":",
"sep",
"=",
"FileMetadata",
".",
"__SEP",
"return",
"str",
"(",
"username",
"+",
"sep",
"+",
"str",
"(",
"date",
")",
"+",
"sep",
"+",
"blob_key",
")"
] | 37.777778 | 21.055556 |
def _get_mx_exchanges(domain):
"""Fetch the MX records for the specified domain
:param str domain: The domain to get the MX records for
:rtype: list
"""
try:
answer = resolver.query(domain, 'MX')
return [str(record.exchange).lower()[:-1] for record in answer]
except (resolver.N... | [
"def",
"_get_mx_exchanges",
"(",
"domain",
")",
":",
"try",
":",
"answer",
"=",
"resolver",
".",
"query",
"(",
"domain",
",",
"'MX'",
")",
"return",
"[",
"str",
"(",
"record",
".",
"exchange",
")",
".",
"lower",
"(",
")",
"[",
":",
"-",
"1",
"]",
... | 37.571429 | 23.214286 |
def increment(self, name, value):
"""
Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter.
"""
counter = self.get(name, CounterType.Increment)
counter.count = counter.count + value if coun... | [
"def",
"increment",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"Increment",
")",
"counter",
".",
"count",
"=",
"counter",
".",
"count",
"+",
"value",
"if",
"counter",
".... | 32.818182 | 17.181818 |
def flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5, shape='sine', phase=25, interp='linear'):
"""TODO Add docstring."""
raise NotImplementedError() | [
"def",
"flanger",
"(",
"self",
",",
"delay",
"=",
"0",
",",
"depth",
"=",
"2",
",",
"regen",
"=",
"0",
",",
"width",
"=",
"71",
",",
"speed",
"=",
"0.5",
",",
"shape",
"=",
"'sine'",
",",
"phase",
"=",
"25",
",",
"interp",
"=",
"'linear'",
")",... | 58.333333 | 24 |
def auth_remove(name, drop, **kwargs):
"""
Removes an authorization group.
Removes an authorization group with or without excluding associated members depending on --drop
flag (disabled by default).
"""
ctx = Context(**kwargs)
ctx.execute_action('auth:group:remove', **{
'storage': c... | [
"def",
"auth_remove",
"(",
"name",
",",
"drop",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'auth:group:remove'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo"... | 30.769231 | 17.538462 |
def decode_metadata_response(cls, data):
"""
Decode bytes to a MetadataResponse
:param bytes data: bytes to decode
"""
((correlation_id, numbrokers), cur) = relative_unpack('>ii', data, 0)
# In testing, I saw this routine swap my machine to death when
# passed b... | [
"def",
"decode_metadata_response",
"(",
"cls",
",",
"data",
")",
":",
"(",
"(",
"correlation_id",
",",
"numbrokers",
")",
",",
"cur",
")",
"=",
"relative_unpack",
"(",
"'>ii'",
",",
"data",
",",
"0",
")",
"# In testing, I saw this routine swap my machine to death ... | 38.921569 | 21.117647 |
def _get_bounds(self, layers):
"""Return the bounds of all data layers involved in a cartoframes map.
Args:
layers (list): List of cartoframes layers. See `cartoframes.layers`
for all types.
Returns:
dict: Dictionary of northern, southern, eastern, and w... | [
"def",
"_get_bounds",
"(",
"self",
",",
"layers",
")",
":",
"extent_query",
"=",
"(",
"'SELECT ST_EXTENT(the_geom) AS the_geom '",
"'FROM ({query}) AS t{idx}\\n'",
")",
"union_query",
"=",
"'UNION ALL\\n'",
".",
"join",
"(",
"[",
"extent_query",
".",
"format",
"(",
... | 38.647059 | 16.441176 |
def last_day(year=_year, month=_month):
"""
get the current month's last day
:param year: default to current year
:param month: default to current month
:return: month's last day
"""
last_day = calendar.monthrange(year, month)[1]
return datetime.date(year=year, month=month, day=last_da... | [
"def",
"last_day",
"(",
"year",
"=",
"_year",
",",
"month",
"=",
"_month",
")",
":",
"last_day",
"=",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
"return",
"datetime",
".",
"date",
"(",
"year",
"=",
"year",
",",
"m... | 34.888889 | 5.777778 |
def min(self):
""" Return the minimum element (or element-based computation).
"""
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(min(self.obj)) | [
"def",
"min",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_clean",
".",
"isDict",
"(",
")",
")",
":",
"return",
"self",
".",
"_wrap",
"(",
"list",
"(",
")",
")",
"return",
"self",
".",
"_wrap",
"(",
"min",
"(",
"self",
".",
"obj",
")",
")... | 34.166667 | 6 |
def delete_audit_sink(self, name, **kwargs):
"""
delete an AuditSink
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_audit_sink(name, async_req=True)
>>> result = thread.get(... | [
"def",
"delete_audit_sink",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_audit_sink_with_htt... | 91.153846 | 64.076923 |
def session(self, auth=None):
"""Get a dict of the current authenticated user's session information.
:param auth: Tuple of username and password.
:type auth: Optional[Tuple[str,str]]
:rtype: User
"""
url = '{server}{auth_url}'.format(**self._options)
if isinst... | [
"def",
"session",
"(",
"self",
",",
"auth",
"=",
"None",
")",
":",
"url",
"=",
"'{server}{auth_url}'",
".",
"format",
"(",
"*",
"*",
"self",
".",
"_options",
")",
"if",
"isinstance",
"(",
"self",
".",
"_session",
".",
"auth",
",",
"tuple",
")",
"or",... | 33.636364 | 20.5 |
def get_link_attribute(self, link_text, attribute, hard_fail=True):
""" Finds a link by link text and then returns the attribute's value.
If the link text or attribute cannot be found, an exception will
get raised if hard_fail is True (otherwise None is returned). """
soup = self... | [
"def",
"get_link_attribute",
"(",
"self",
",",
"link_text",
",",
"attribute",
",",
"hard_fail",
"=",
"True",
")",
":",
"soup",
"=",
"self",
".",
"get_beautiful_soup",
"(",
")",
"html_links",
"=",
"soup",
".",
"find_all",
"(",
"'a'",
")",
"for",
"html_link"... | 47.380952 | 14.428571 |
def expire(self, key, timeout):
"""Set a timeout on key. After the timeout has expired, the key will
automatically be deleted. A key with an associated timeout is often
said to be volatile in Redis terminology.
The timeout is cleared only when the key is removed using the
:meth:... | [
"def",
"expire",
"(",
"self",
",",
"key",
",",
"timeout",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'EXPIRE'",
",",
"key",
",",
"ascii",
"(",
"timeout",
")",
".",
"encode",
"(",
"'ascii'",
")",
"]",
",",
"1",
")"
] | 48.95122 | 27.463415 |
def get_dataset_files(self, dataset_id, glob=".", is_dir=False, version_number=None):
"""
Retrieves URLs for the files matched by a glob or a path to a directory
in a given dataset.
:param dataset_id: The id of the dataset to retrieve files from
:type dataset_id: int
:pa... | [
"def",
"get_dataset_files",
"(",
"self",
",",
"dataset_id",
",",
"glob",
"=",
"\".\"",
",",
"is_dir",
"=",
"False",
",",
"version_number",
"=",
"None",
")",
":",
"if",
"version_number",
"is",
"None",
":",
"latest",
"=",
"True",
"else",
":",
"latest",
"="... | 37.75 | 25.958333 |
def OnSquareSelected(self, event):
"""Update all views to show selection children/parents"""
self.selected_node = event.node
self.calleeListControl.integrateRecords(self.adapter.children( event.node) )
self.callerListControl.integrateRecords(self.adapter.parents( event.node) ) | [
"def",
"OnSquareSelected",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"selected_node",
"=",
"event",
".",
"node",
"self",
".",
"calleeListControl",
".",
"integrateRecords",
"(",
"self",
".",
"adapter",
".",
"children",
"(",
"event",
".",
"node",
")"... | 61 | 18.8 |
def select_relevant_id_columns(rows):
"""
Find out which of the entries in Row.id are equal for all given rows.
@return: A list of True/False values according to whether the i-th part of the id is always equal.
"""
relevant_id_columns = [True] # first column (file name) is always relevant
if row... | [
"def",
"select_relevant_id_columns",
"(",
"rows",
")",
":",
"relevant_id_columns",
"=",
"[",
"True",
"]",
"# first column (file name) is always relevant",
"if",
"rows",
":",
"prototype_id",
"=",
"rows",
"[",
"0",
"]",
".",
"id",
"for",
"column",
"in",
"range",
"... | 43.857143 | 21.142857 |
def prepare_cew_for_windows():
"""
Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ... | [
"def",
"prepare_cew_for_windows",
"(",
")",
":",
"try",
":",
"# copy espeak_sapi.dll to C:\\Windows\\System32\\espeak.dll",
"espeak_dll_win_path",
"=",
"\"C:\\\\Windows\\\\System32\\\\espeak.dll\"",
"espeak_dll_dst_path",
"=",
"\"aeneas\\\\cew\\\\espeak.dll\"",
"espeak_dll_src_paths",
... | 50.636364 | 27.987013 |
def __set_method(self, value):
'''
Sets the method to use.
@param value: str
'''
if value not in [DELIVERY_METHOD_EMAIL, DELIVERY_METHOD_SMS,
DELIVERY_METHOD_SNAILMAIL]:
raise ValueError("Invalid deliveries method '%s'" % value)
self.... | [
"def",
"__set_method",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"[",
"DELIVERY_METHOD_EMAIL",
",",
"DELIVERY_METHOD_SMS",
",",
"DELIVERY_METHOD_SNAILMAIL",
"]",
":",
"raise",
"ValueError",
"(",
"\"Invalid deliveries method '%s'\"",
"%",
"valu... | 32.7 | 21.3 |
def get_implicit_constraints(self,relations):
''' An implicit constraint is one in which you are unifying a constant to a position of the relation
E.G. R(X,2) specifies that R.2 == 2'''
constraints = []
for relation in [r for r in relations if not r.is_negated()] :
cons... | [
"def",
"get_implicit_constraints",
"(",
"self",
",",
"relations",
")",
":",
"constraints",
"=",
"[",
"]",
"for",
"relation",
"in",
"[",
"r",
"for",
"r",
"in",
"relations",
"if",
"not",
"r",
".",
"is_negated",
"(",
")",
"]",
":",
"const_dict",
"=",
"rel... | 50.153846 | 24 |
def localcorr(self, size=2):
"""
Correlate every pixel in an image sequence to the average of its local neighborhood.
This algorithm computes, for every pixel, the correlation coefficient
between the sequence of values for that pixel, and the average of all pixels
in a local nei... | [
"def",
"localcorr",
"(",
"self",
",",
"size",
"=",
"2",
")",
":",
"from",
"thunder",
".",
"images",
".",
"readers",
"import",
"fromarray",
",",
"fromrdd",
"from",
"numpy",
"import",
"corrcoef",
",",
"concatenate",
"nimages",
"=",
"self",
".",
"shape",
"[... | 43.102564 | 27.051282 |
def strip_dbm_tx_power(self, idx):
"""strip(1 byte) dbm_tx_power
:return: int
idx
:return: int
"""
idx = Radiotap.align(idx, 1)
dbm_tx_power, = struct.unpack_from('<b', self._rtap, idx)
return idx + 1, dbm_tx_power | [
"def",
"strip_dbm_tx_power",
"(",
"self",
",",
"idx",
")",
":",
"idx",
"=",
"Radiotap",
".",
"align",
"(",
"idx",
",",
"1",
")",
"dbm_tx_power",
",",
"=",
"struct",
".",
"unpack_from",
"(",
"'<b'",
",",
"self",
".",
"_rtap",
",",
"idx",
")",
"return"... | 30.444444 | 11.555556 |
def get_federation_service(domain, allow_http=False):
"""Retrieve the FEDERATION_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that... | [
"def",
"get_federation_service",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"st",
"=",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
")",
"if",
"not",
"st",
":",
"return",
"None",
"return",
"st",
".",
"get",
"(",
"'FEDERATION_SERVER'",... | 38.846154 | 18.615385 |
def channels_twitter_ticket_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/twitter_channel#create-ticket-from-tweet"
api_path = "/api/v2/channels/twitter/tickets.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"channels_twitter_ticket_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/channels/twitter/tickets.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
... | 71 | 31 |
def generate_direct_deps(self, target: Target):
"""Generate only direct dependencies of `target`."""
yield from (self.targets[dep_name] for dep_name in sorted(target.deps)) | [
"def",
"generate_direct_deps",
"(",
"self",
",",
"target",
":",
"Target",
")",
":",
"yield",
"from",
"(",
"self",
".",
"targets",
"[",
"dep_name",
"]",
"for",
"dep_name",
"in",
"sorted",
"(",
"target",
".",
"deps",
")",
")"
] | 62 | 15.333333 |
def _pdf_value(pdf, population, fitnesses, fitness_threshold):
"""Give the value of a pdf.
This represents the likelihood of a pdf generating solutions
that exceed the threshold.
"""
# Add the chance of obtaining a solution from the pdf
# when the fitness for that solution exceeds a threshold
... | [
"def",
"_pdf_value",
"(",
"pdf",
",",
"population",
",",
"fitnesses",
",",
"fitness_threshold",
")",
":",
"# Add the chance of obtaining a solution from the pdf",
"# when the fitness for that solution exceeds a threshold",
"value",
"=",
"0.0",
"for",
"solution",
",",
"fitness... | 42.055556 | 19.833333 |
def _toRtl(self, targetPlatform: DummyPlatform):
"""
synthesize all subunits, make connections between them,
build entity and component for this unit
"""
assert not self._wasSynthetised()
self._targetPlatform = targetPlatform
if not hasattr(self, "_name"):
... | [
"def",
"_toRtl",
"(",
"self",
",",
"targetPlatform",
":",
"DummyPlatform",
")",
":",
"assert",
"not",
"self",
".",
"_wasSynthetised",
"(",
")",
"self",
".",
"_targetPlatform",
"=",
"targetPlatform",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_name\"",
")",... | 30.78 | 16.7 |
def get_version(self):
"""
Returns a tuple representing the installed HAProxy version.
The value of the tuple is (<major>, <minor>, <patch>), e.g. if HAProxy
version 1.5.3 is installed, this will return `(1, 5, 3)`.
"""
command = ["haproxy", "-v"]
try:
... | [
"def",
"get_version",
"(",
"self",
")",
":",
"command",
"=",
"[",
"\"haproxy\"",
",",
"\"-v\"",
"]",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
")",
"version_line",
"=",
"output",
".",
"split",
"(",
"\"\\n\"",
")",
"[",... | 32 | 20.275862 |
def get_dataset(self, dataset_id, ds_info, xslice=slice(None), yslice=slice(None)):
"""Load data array and metadata from file on disk."""
var_path = ds_info.get('file_key', '{}'.format(dataset_id.name))
metadata = self.get_metadata(dataset_id, ds_info)
shape = metadata['shape']
f... | [
"def",
"get_dataset",
"(",
"self",
",",
"dataset_id",
",",
"ds_info",
",",
"xslice",
"=",
"slice",
"(",
"None",
")",
",",
"yslice",
"=",
"slice",
"(",
"None",
")",
")",
":",
"var_path",
"=",
"ds_info",
".",
"get",
"(",
"'file_key'",
",",
"'{}'",
".",... | 47.097561 | 19.073171 |
def runMultiplePassSPonly(df, model, nMultiplePass, nTrain):
"""
run CLA model SP through data record 0:nTrain nMultiplePass passes
"""
predictedField = model.getInferenceArgs()['predictedField']
print "run TM through the train data multiple times"
for nPass in xrange(nMultiplePass):
for j in xrange(nT... | [
"def",
"runMultiplePassSPonly",
"(",
"df",
",",
"model",
",",
"nMultiplePass",
",",
"nTrain",
")",
":",
"predictedField",
"=",
"model",
".",
"getInferenceArgs",
"(",
")",
"[",
"'predictedField'",
"]",
"print",
"\"run TM through the train data multiple times\"",
"for",... | 32.625 | 16.5 |
def rolling_vwap(bars, window=200, min_periods=None):
"""
calculate vwap using moving window
(input can be pandas series or numpy array)
bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
"""
min_periods = window if min_periods is None else min_periods
typical = ((bars['high'] + bars... | [
"def",
"rolling_vwap",
"(",
"bars",
",",
"window",
"=",
"200",
",",
"min_periods",
"=",
"None",
")",
":",
"min_periods",
"=",
"window",
"if",
"min_periods",
"is",
"None",
"else",
"min_periods",
"typical",
"=",
"(",
"(",
"bars",
"[",
"'high'",
"]",
"+",
... | 41.75 | 22.75 |
def is_playing_tv(self):
"""bool: Is the playbar speaker input from TV?"""
response = self.avTransport.GetPositionInfo([
('InstanceID', 0),
('Channel', 'Master')
])
track_uri = response['TrackURI']
return re.match(r'^x-sonos-htastream:', track_uri) is not ... | [
"def",
"is_playing_tv",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"avTransport",
".",
"GetPositionInfo",
"(",
"[",
"(",
"'InstanceID'",
",",
"0",
")",
",",
"(",
"'Channel'",
",",
"'Master'",
")",
"]",
")",
"track_uri",
"=",
"response",
"[",
... | 39.625 | 13.25 |
def eval(self, x, y, z):
"""Evaluate the function in (x, y, z)."""
xc, yc, zc = self.rc
sx, sy, sz = self.s
## Method1: direct evaluation
#return exp(-(((x-xc)**2)/(2*sx**2) + ((y-yc)**2)/(2*sy**2) +\
# ((z-zc)**2)/(2*sz**2)))
## Method2: evaluation using... | [
"def",
"eval",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"xc",
",",
"yc",
",",
"zc",
"=",
"self",
".",
"rc",
"sx",
",",
"sy",
",",
"sz",
"=",
"self",
".",
"s",
"## Method1: direct evaluation",
"#return exp(-(((x-xc)**2)/(2*sx**2) + ((y-yc)**2)... | 36 | 16.071429 |
def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, CachedMessage]]:
"""Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set.
"""
if seq_set.uid:
all_uids = s... | [
"def",
"get_all",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"int",
",",
"CachedMessage",
"]",
"]",
":",
"if",
"seq_set",
".",
"uid",
":",
"all_uids",
"=",
"seq_set",
".",
"flatten",
"(",
"self",
".",
"... | 37 | 14.210526 |
def GetNumberOfRows(self):
"""Retrieves the number of rows in the table.
Returns:
int: number of rows.
Raises:
BackEndError: when the SQLite blob file-like object is missing.
"""
file_object = self.GetFileObject()
if not file_object:
raise errors.BackEndError(
'Unab... | [
"def",
"GetNumberOfRows",
"(",
"self",
")",
":",
"file_object",
"=",
"self",
".",
"GetFileObject",
"(",
")",
"if",
"not",
"file_object",
":",
"raise",
"errors",
".",
"BackEndError",
"(",
"'Unable to retrieve SQLite blob file-like object.'",
")",
"try",
":",
"# TOD... | 26.142857 | 20.904762 |
def removecallback(window_name):
"""
Remove registered callback on window create
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@return: 1 if registration was successful, 0 if not.
@rtype: integer
"""
... | [
"def",
"removecallback",
"(",
"window_name",
")",
":",
"if",
"window_name",
"in",
"_pollEvents",
".",
"_callback",
":",
"del",
"_pollEvents",
".",
"_callback",
"[",
"window_name",
"]",
"return",
"_remote_removecallback",
"(",
"window_name",
")"
] | 29.466667 | 15.2 |
def _decode(s, encoding=None, errors=None):
"""Decodes *s*."""
if encoding is None:
encoding = ENCODING
if errors is None:
errors = ENCODING_ERRORS
return s if isinstance(s, unicode) else s.decode(encoding, errors) | [
"def",
"_decode",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"ENCODING",
"if",
"errors",
"is",
"None",
":",
"errors",
"=",
"ENCODING_ERRORS",
"return",
"s",
"if",
... | 34.285714 | 12.571429 |
def ODF(odf_obj):
"""
Create a Dataframe with the contents of the ODF file
For more information on the ODF format see:
http://software.broadinstitute.org/cancer/software/genepattern/file-formats-guide
:odf_obj: The ODF file. Accepts a file-like object, a file path, a URL to the file
... | [
"def",
"ODF",
"(",
"odf_obj",
")",
":",
"# Handle all the various initialization types and get an IO object",
"odf_io",
"=",
"_obtain_io",
"(",
"odf_obj",
")",
"# Read the file as an array of lines",
"raw_lines",
"=",
"odf_io",
".",
"readlines",
"(",
")",
"# Convert byte st... | 29.685185 | 21.351852 |
def validate_column_specs(events, columns):
"""
Verify that the columns of ``events`` can be used by a
EarningsEstimatesLoader to serve the BoundColumns described by
`columns`.
"""
required = required_estimates_fields(columns)
received = set(events.columns)
missing = required - received
... | [
"def",
"validate_column_specs",
"(",
"events",
",",
"columns",
")",
":",
"required",
"=",
"required_estimates_fields",
"(",
"columns",
")",
"received",
"=",
"set",
"(",
"events",
".",
"columns",
")",
"missing",
"=",
"required",
"-",
"received",
"if",
"missing"... | 34.789474 | 12.789474 |
def create(self, body=values.unset, media_url=values.unset):
"""
Create a new MessageInteractionInstance
:param unicode body: Message body
:param unicode media_url: Reserved
:returns: Newly created MessageInteractionInstance
:rtype: twilio.rest.proxy.v1.service.session.... | [
"def",
"create",
"(",
"self",
",",
"body",
"=",
"values",
".",
"unset",
",",
"media_url",
"=",
"values",
".",
"unset",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'Body'",
":",
"body",
",",
"'MediaUrl'",
":",
"serialize",
".",
"map",
"("... | 34.08 | 21.52 |
def colorize(string, stack):
'''Apply optimal ANSI escape sequences to the string.'''
codes = optimize(stack)
if len(codes):
prefix = SEQ % ';'.join(map(str, codes))
suffix = SEQ % STYLE.reset
return prefix + string + suffix
else:
return string | [
"def",
"colorize",
"(",
"string",
",",
"stack",
")",
":",
"codes",
"=",
"optimize",
"(",
"stack",
")",
"if",
"len",
"(",
"codes",
")",
":",
"prefix",
"=",
"SEQ",
"%",
"';'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"codes",
")",
")",
"suffix",
... | 28.888889 | 16 |
def mimetype_from_path(path):
"""
Return a mimetype from the file extension.
:param string path: the file path
:rtype: string
"""
extension = file_extension(path)
if extension is not None:
extension = extension.lower()
if extension in gc.MIMETYPE_MAP:
return gc.M... | [
"def",
"mimetype_from_path",
"(",
"path",
")",
":",
"extension",
"=",
"file_extension",
"(",
"path",
")",
"if",
"extension",
"is",
"not",
"None",
":",
"extension",
"=",
"extension",
".",
"lower",
"(",
")",
"if",
"extension",
"in",
"gc",
".",
"MIMETYPE_MAP"... | 26.615385 | 10 |
def _send_request(self, request):
"""Establishes connection and returns http response based off of request.
:param request: HTTPRequest object
:type request: :class:`tincan.http_request.HTTPRequest`
:returns: LRS Response object
:rtype: :class:`tincan.lrs_response.LRSResponse`
... | [
"def",
"_send_request",
"(",
"self",
",",
"request",
")",
":",
"headers",
"=",
"{",
"\"X-Experience-API-Version\"",
":",
"self",
".",
"version",
"}",
"if",
"self",
".",
"auth",
"is",
"not",
"None",
":",
"headers",
"[",
"\"Authorization\"",
"]",
"=",
"self"... | 29.375 | 17.041667 |
def parse_compound_file(f, context=None):
"""Iterate over the compound entries in the given file"""
f.readline() # Skip header
for lineno, row in enumerate(csv.reader(f, delimiter='\t')):
compound_id, names, formula = row[:3]
names = (decode_name(name) for name in names.split(',<br>'))
... | [
"def",
"parse_compound_file",
"(",
"f",
",",
"context",
"=",
"None",
")",
":",
"f",
".",
"readline",
"(",
")",
"# Skip header",
"for",
"lineno",
",",
"row",
"in",
"enumerate",
"(",
"csv",
".",
"reader",
"(",
"f",
",",
"delimiter",
"=",
"'\\t'",
")",
... | 38.375 | 18 |
def down(queue, user=None, group=None, mode=None, host=None) :
'''Down a queue, by creating a down file'''
# default our owners and mode
user, group, mode = _dflts(user, group, mode)
down_path = fsq_path.down(queue, host=host)
fd = None
created = False
try:
# try to guarentee creatio... | [
"def",
"down",
"(",
"queue",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"host",
"=",
"None",
")",
":",
"# default our owners and mode",
"user",
",",
"group",
",",
"mode",
"=",
"_dflts",
"(",
"user",
",",
"grou... | 34.37037 | 15.185185 |
def concat(self, *others):
"""
Concatenate expression lists
Returns
-------
combined : ExprList
"""
import ibis.expr.operations as ops
exprs = list(self.exprs())
for o in others:
if not isinstance(o, ExprList):
raise T... | [
"def",
"concat",
"(",
"self",
",",
"*",
"others",
")",
":",
"import",
"ibis",
".",
"expr",
".",
"operations",
"as",
"ops",
"exprs",
"=",
"list",
"(",
"self",
".",
"exprs",
"(",
")",
")",
"for",
"o",
"in",
"others",
":",
"if",
"not",
"isinstance",
... | 25.1875 | 13.0625 |
def setup_cmd_parser(cls):
"""Returns the Gerrit argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
from_date=True,
archive=True)
# Gerrit options
group = parser.p... | [
"def",
"setup_cmd_parser",
"(",
"cls",
")",
":",
"parser",
"=",
"BackendCommandArgumentParser",
"(",
"cls",
".",
"BACKEND",
".",
"CATEGORIES",
",",
"from_date",
"=",
"True",
",",
"archive",
"=",
"True",
")",
"# Gerrit options",
"group",
"=",
"parser",
".",
"... | 48.035714 | 23.714286 |
def _py_ctype(parameter):
"""Returns the ctypes type name for the specified fortran parameter.
"""
ctype = parameter.ctype
if ctype is None:
raise ValueError("Can't bind ctypes py_parameter for parameter"
" {}".format(parameter.definition()))
return ctype.lower() | [
"def",
"_py_ctype",
"(",
"parameter",
")",
":",
"ctype",
"=",
"parameter",
".",
"ctype",
"if",
"ctype",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Can't bind ctypes py_parameter for parameter\"",
"\" {}\"",
".",
"format",
"(",
"parameter",
".",
"definition"... | 38.625 | 14.5 |
def _send(self, msg):
"""Transmits message either in binary or UTF-8 text mode,
depending on its type."""
if isinstance(msg, six.binary_type):
method = uwsgi.websocket_send_binary
else:
method = uwsgi.websocket_send
if self._req_ctx is not None:
... | [
"def",
"_send",
"(",
"self",
",",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"six",
".",
"binary_type",
")",
":",
"method",
"=",
"uwsgi",
".",
"websocket_send_binary",
"else",
":",
"method",
"=",
"uwsgi",
".",
"websocket_send",
"if",
"self",
... | 35.636364 | 10.909091 |
def get_name(self):
"""Get name using taxid"""
if len(self.taxid2asscs) == 1:
return '{BASE}_{TAXID}'.format(
BASE=self.name, TAXID=next(iter(self.taxid2asscs.keys())))
return '{BASE}_various'.format(BASE=self.name) | [
"def",
"get_name",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"taxid2asscs",
")",
"==",
"1",
":",
"return",
"'{BASE}_{TAXID}'",
".",
"format",
"(",
"BASE",
"=",
"self",
".",
"name",
",",
"TAXID",
"=",
"next",
"(",
"iter",
"(",
"self",
".... | 43.666667 | 12.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.