text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
async def send_script_message(self, message, context):
"""Handle a send_script message.
See :meth:`AbstractDeviceAdapter.send_script`.
"""
script = message.get('script')
conn_string = message.get('connection_string')
client_id = context.user_data
if message.get... | [
"async",
"def",
"send_script_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"script",
"=",
"message",
".",
"get",
"(",
"'script'",
")",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"client_id",
"=",
"context",... | 36.714286 | 22.357143 |
def get_user_config_filename(appname='notify'):
"""
Get user config filename.
It will return operating system dependent config filename.
Parameters
----------
appname : string
An application name used for filename
Returns
-------
string
A filename of user configura... | [
"def",
"get_user_config_filename",
"(",
"appname",
"=",
"'notify'",
")",
":",
"import",
"platform",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"if",
"system",
"==",
"'Windows'",
":",
"rootname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".... | 29.851064 | 16.489362 |
def create_or_update(self, resource_group, name, container_group):
"""
Create a new container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:param container_group... | [
"def",
"create_or_update",
"(",
"self",
",",
"resource_group",
",",
"name",
",",
"container_group",
")",
":",
"self",
".",
"connection",
".",
"container_groups",
".",
"create_or_update",
"(",
"resource_group",
",",
"name",
",",
"container_group",
")"
] | 46.642857 | 20.5 |
def get_indices(self, src, ridx, mag):
"""
:param src: an UCERF source
:param ridx: a set of rupture indices
:param mag: magnitude to use to compute the integration distance
:returns: array with the IDs of the sites close to the ruptures
"""
centroids = src.get_ce... | [
"def",
"get_indices",
"(",
"self",
",",
"src",
",",
"ridx",
",",
"mag",
")",
":",
"centroids",
"=",
"src",
".",
"get_centroids",
"(",
"ridx",
")",
"mindistance",
"=",
"min_geodetic_distance",
"(",
"(",
"centroids",
"[",
":",
",",
"0",
"]",
",",
"centro... | 43.615385 | 11.923077 |
def list_product_releases(page_size=200, page_index=0, sort="", q=""):
"""
List all ProductReleases
"""
data = list_product_releases_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_product_releases",
"(",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_product_releases_raw",
"(",
"page_size",
",",
"page_index",
",",
"sort",
",",
"q",
")... | 33.571429 | 14.428571 |
def entry_at(cls, filepath, index):
""":return: RefLogEntry at the given index
:param filepath: full path to the index file from which to read the entry
:param index: python list compatible index, i.e. it may be negative to
specify an entry counted from the end of the list
:... | [
"def",
"entry_at",
"(",
"cls",
",",
"filepath",
",",
"index",
")",
":",
"fp",
"=",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"if",
"index",
"<",
"0",
":",
"return",
"RefLogEntry",
".",
"from_line",
"(",
"fp",
".",
"readlines",
"(",
")",
"[",
"inde... | 37.586207 | 18.172414 |
def export_to_storage_bucket(self, bucket, namespace=None, entity_filter=None, labels=None):
"""
Export entities from Cloud Datastore to Cloud Storage for backup.
.. note::
Keep in mind that this requests the Admin API not the Data API.
.. seealso::
https://clou... | [
"def",
"export_to_storage_bucket",
"(",
"self",
",",
"bucket",
",",
"namespace",
"=",
"None",
",",
"entity_filter",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"admin_conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"output_uri_prefix",
"=",
"'gs://'",
... | 35.717949 | 21.717949 |
def isreshapeable(new, old):
"""
Check to see if a proposed tuple of axes is a valid reshaping of
the old axes by ensuring that they can be factored.
Parameters
----------
new : tuple
tuple of proposed axes
old : tuple
tuple of old axes
"""
new, old = tupleize(new)... | [
"def",
"isreshapeable",
"(",
"new",
",",
"old",
")",
":",
"new",
",",
"old",
"=",
"tupleize",
"(",
"new",
")",
",",
"tupleize",
"(",
"old",
")",
"if",
"not",
"prod",
"(",
"new",
")",
"==",
"prod",
"(",
"old",
")",
":",
"raise",
"ValueError",
"(",... | 23.722222 | 21.277778 |
def _get_computer_object():
'''
A helper function to get the object for the local machine
Returns:
object: Returns the computer object for the local machine
'''
with salt.utils.winapi.Com():
nt = win32com.client.Dispatch('AdsNameSpaces')
return nt.GetObject('', 'WinNT://.,comput... | [
"def",
"_get_computer_object",
"(",
")",
":",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"nt",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"'AdsNameSpaces'",
")",
"return",
"nt",
".",
"GetObject",
"(",
"''",
",",
... | 31.5 | 22.3 |
def authenticate(url, account, key, by='name', expires=0, timestamp=None,
timeout=None, request_type="xml", admin_auth=False,
use_password=False, raise_on_error=False):
""" Authenticate to the Zimbra server
:param url: URL of Zimbra SOAP service
:param account: The accoun... | [
"def",
"authenticate",
"(",
"url",
",",
"account",
",",
"key",
",",
"by",
"=",
"'name'",
",",
"expires",
"=",
"0",
",",
"timestamp",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"request_type",
"=",
"\"xml\"",
",",
"admin_auth",
"=",
"False",
",",
... | 26.028571 | 23.933333 |
def normalize_job_id(job_id):
"""
Convert a value to a job id.
:param job_id: Value to convert.
:type job_id: int, str
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not isinstance(job_id, uuid.UUID):
job_id = uuid.UUID(job_id)
return job_id | [
"def",
"normalize_job_id",
"(",
"job_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"job_id",
",",
"uuid",
".",
"UUID",
")",
":",
"job_id",
"=",
"uuid",
".",
"UUID",
"(",
"job_id",
")",
"return",
"job_id"
] | 21.083333 | 12.916667 |
def operations(self):
"""Instance depends on the API version:
* 2017-03-01: :class:`Operations<azure.mgmt.containerregistry.v2017_03_01.operations.Operations>`
* 2017-10-01: :class:`Operations<azure.mgmt.containerregistry.v2017_10_01.operations.Operations>`
* 2018-02-01-preview... | [
"def",
"operations",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'operations'",
")",
"if",
"api_version",
"==",
"'2017-03-01'",
":",
"from",
".",
"v2017_03_01",
".",
"operations",
"import",
"Operations",
"as",
"OperationClas... | 65.8 | 35.6 |
def row_cells(self, row_idx):
"""
Sequence of cells in the row at *row_idx* in this table.
"""
column_count = self._column_count
start = row_idx * column_count
end = start + column_count
return self._cells[start:end] | [
"def",
"row_cells",
"(",
"self",
",",
"row_idx",
")",
":",
"column_count",
"=",
"self",
".",
"_column_count",
"start",
"=",
"row_idx",
"*",
"column_count",
"end",
"=",
"start",
"+",
"column_count",
"return",
"self",
".",
"_cells",
"[",
"start",
":",
"end",... | 33.125 | 5.875 |
def angle_iter(self, g_nums, ats_1, ats_2, ats_3, invalid_error=False):
""" Iterator over selected atomic angles.
Angles are in degrees as with :meth:`angle_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g... | [
"def",
"angle_iter",
"(",
"self",
",",
"g_nums",
",",
"ats_1",
",",
"ats_2",
",",
"ats_3",
",",
"invalid_error",
"=",
"False",
")",
":",
"# Suitability of ats_n indices will be checked within the",
"# self.angle_single() calls and thus no check is needed here.",
"# Import th... | 30.464286 | 21.178571 |
def name(self):
""" Returns name of the digest """
if not hasattr(self, 'digest_name'):
self.digest_name = Oid(libcrypto.EVP_MD_type(self.digest)
).longname()
return self.digest_name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'digest_name'",
")",
":",
"self",
".",
"digest_name",
"=",
"Oid",
"(",
"libcrypto",
".",
"EVP_MD_type",
"(",
"self",
".",
"digest",
")",
")",
".",
"longname",
"(",
")",
... | 41.166667 | 12.166667 |
def _ping_loop(self):
"""This background task sends a PING to the server at the requested
interval.
"""
self.pong_received = True
self.ping_loop_event.clear()
while self.state == 'connected':
if not self.pong_received:
self.logger.info(
... | [
"def",
"_ping_loop",
"(",
"self",
")",
":",
"self",
".",
"pong_received",
"=",
"True",
"self",
".",
"ping_loop_event",
".",
"clear",
"(",
")",
"while",
"self",
".",
"state",
"==",
"'connected'",
":",
"if",
"not",
"self",
".",
"pong_received",
":",
"self"... | 38.666667 | 10 |
def cmvnw(vec, win_size=301, variance_normalization=False):
""" This function is aimed to perform local cepstral mean and
variance normalization on a sliding window. The code assumes that
there is one observation per row.
Args:
vec (array): input feature matrix
(size:(num_observatio... | [
"def",
"cmvnw",
"(",
"vec",
",",
"win_size",
"=",
"301",
",",
"variance_normalization",
"=",
"False",
")",
":",
"# Get the shapes",
"eps",
"=",
"2",
"**",
"-",
"30",
"rows",
",",
"cols",
"=",
"vec",
".",
"shape",
"# Windows size must be odd.",
"assert",
"i... | 35.925926 | 19.407407 |
def copy(self):
"""Copy a reaction
The referenced metabolites and genes are also copied.
"""
# no references to model when copying
model = self._model
self._model = None
for i in self._metabolites:
i._model = None
for i in self._genes:
... | [
"def",
"copy",
"(",
"self",
")",
":",
"# no references to model when copying",
"model",
"=",
"self",
".",
"_model",
"self",
".",
"_model",
"=",
"None",
"for",
"i",
"in",
"self",
".",
"_metabolites",
":",
"i",
".",
"_model",
"=",
"None",
"for",
"i",
"in",... | 27.136364 | 13.272727 |
def delete(self, network):
"""
Wraps the standard delete() method to catch expected exceptions and
raise the appropriate pyrax exceptions.
"""
try:
return super(CloudNetworkClient, self).delete(network)
except exc.Forbidden as e:
# Network is in us... | [
"def",
"delete",
"(",
"self",
",",
"network",
")",
":",
"try",
":",
"return",
"super",
"(",
"CloudNetworkClient",
",",
"self",
")",
".",
"delete",
"(",
"network",
")",
"except",
"exc",
".",
"Forbidden",
"as",
"e",
":",
"# Network is in use",
"raise",
"ex... | 39.4 | 16.6 |
def assign_power_curve(self, weather_df):
r"""
Calculates the power curve of the wind turbine cluster.
The power curve is aggregated from the wind farms' and wind turbines'
power curves by using :func:`power_plant.assign_power_curve`. Depending
on the parameters of the WindTurbi... | [
"def",
"assign_power_curve",
"(",
"self",
",",
"weather_df",
")",
":",
"# Set turbulence intensity for assigning power curve",
"turbulence_intensity",
"=",
"(",
"weather_df",
"[",
"'turbulence_intensity'",
"]",
".",
"values",
".",
"mean",
"(",
")",
"if",
"'turbulence_in... | 46.892308 | 23.092308 |
def _show_message(self, text):
"""Show message on splash screen."""
self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter |
Qt.AlignAbsolute, QColor(Qt.white)) | [
"def",
"_show_message",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"splash",
".",
"showMessage",
"(",
"text",
",",
"Qt",
".",
"AlignBottom",
"|",
"Qt",
".",
"AlignCenter",
"|",
"Qt",
".",
"AlignAbsolute",
",",
"QColor",
"(",
"Qt",
".",
"white",
... | 53.75 | 17 |
def split_args_list(tokens, loc):
"""Splits function definition arguments."""
req_args, def_args, star_arg, kwd_args, dubstar_arg = [], [], None, [], None
pos = 0
for arg in tokens:
if len(arg) == 1:
if arg[0] == "*":
# star sep (pos = 3)
if pos >= 3:
... | [
"def",
"split_args_list",
"(",
"tokens",
",",
"loc",
")",
":",
"req_args",
",",
"def_args",
",",
"star_arg",
",",
"kwd_args",
",",
"dubstar_arg",
"=",
"[",
"]",
",",
"[",
"]",
",",
"None",
",",
"[",
"]",
",",
"None",
"pos",
"=",
"0",
"for",
"arg",
... | 43.302326 | 21.139535 |
def main(args=None):
"""Start application."""
Config.options, Config.args = parse(args)
logger()
if Config.options.aeidon or Config.options.fix:
start_aeidon()
else:
start_srt()
if Config.options.fix:
sys.exit(0)
if not Config.results:
basenames = [os.pat... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"Config",
".",
"options",
",",
"Config",
".",
"args",
"=",
"parse",
"(",
"args",
")",
"logger",
"(",
")",
"if",
"Config",
".",
"options",
".",
"aeidon",
"or",
"Config",
".",
"options",
".",
"fix",
... | 24.434783 | 23.478261 |
def rouge_l(hypotheses, references):
"""
Calculate ROUGE-L F1, precision, recall scores
"""
rouge_l = [
rouge_l_sentence_level([hyp], [ref])
for hyp, ref in zip(hypotheses, references)
]
rouge_l_f, _, _ = map(np.mean, zip(*rouge_l))
return rouge_l_f | [
"def",
"rouge_l",
"(",
"hypotheses",
",",
"references",
")",
":",
"rouge_l",
"=",
"[",
"rouge_l_sentence_level",
"(",
"[",
"hyp",
"]",
",",
"[",
"ref",
"]",
")",
"for",
"hyp",
",",
"ref",
"in",
"zip",
"(",
"hypotheses",
",",
"references",
")",
"]",
"... | 28.4 | 11.8 |
def resolve(self, *keys):
'''
Returns resolved instances for given provider keys.
If only one positional argument is given, only one is returned.
:param keys: Provider keys
:type keys: tuple
:return: Resolved instance(s); if only one key given, otherwise list of them.
... | [
"def",
"resolve",
"(",
"self",
",",
"*",
"keys",
")",
":",
"instances",
"=",
"list",
"(",
"self",
".",
"iresolve",
"(",
"*",
"keys",
")",
")",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"return",
"instances",
"[",
"0",
"]",
"return",
"instanc... | 31.866667 | 21.6 |
def send_file(self,
path,
contents,
shutit_pexpect_child=None,
truncate=False,
note=None,
user=None,
echo=False,
group=None,
loglevel=logging.INFO,
encoding=None):
"""S... | [
"def",
"send_file",
"(",
"self",
",",
"path",
",",
"contents",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"truncate",
"=",
"False",
",",
"note",
"=",
"None",
",",
"user",
"=",
"None",
",",
"echo",
"=",
"False",
",",
"group",
"=",
"None",
",",
"lo... | 42.027778 | 17.777778 |
def plots_html_page():
"""Generate general statistics
Output is an html page, rendered to 'plots_html_page.html' in the output directory.
"""
# page template
template = jenv.get_template("plots_html_page.html")
# container for template context
context = dict()
# a database client/sess... | [
"def",
"plots_html_page",
"(",
")",
":",
"# page template",
"template",
"=",
"jenv",
".",
"get_template",
"(",
"\"plots_html_page.html\"",
")",
"# container for template context",
"context",
"=",
"dict",
"(",
")",
"# a database client/session to run queries in",
"cl",
"="... | 34.446429 | 23.294643 |
def parse_roles(self, fetched_role, params):
"""
Parse a single IAM role and fetch additional data
"""
role = {}
role['instances_count'] = 'N/A'
# When resuming upon throttling error, skip if already fetched
if fetched_role['RoleName'] in self.roles:
r... | [
"def",
"parse_roles",
"(",
"self",
",",
"fetched_role",
",",
"params",
")",
":",
"role",
"=",
"{",
"}",
"role",
"[",
"'instances_count'",
"]",
"=",
"'N/A'",
"# When resuming upon throttling error, skip if already fetched",
"if",
"fetched_role",
"[",
"'RoleName'",
"]... | 51.242424 | 20.636364 |
def authenticate(self, is_global=True):
"""Authenticates against the API server.
:param is_global: If True, authenticate globally. Local login if False.
:raise AuthenticationException: Raises if there was an issue with authenticating or logging in.
:raise MyGeotabException: Raises when ... | [
"def",
"authenticate",
"(",
"self",
",",
"is_global",
"=",
"True",
")",
":",
"auth_data",
"=",
"dict",
"(",
"database",
"=",
"self",
".",
"credentials",
".",
"database",
",",
"userName",
"=",
"self",
".",
"credentials",
".",
"username",
",",
"password",
... | 55.129032 | 23.935484 |
def clr(args):
"""
%prog blastfile fastafiles
Calculate the vector clear range file based BLAST to the vectors.
"""
p = OptionParser(clr.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
blastfile = args[0]
fastafiles = args[1:]
s... | [
"def",
"clr",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"clr",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"sys",
".",
"exit",
"(",
"not",
... | 24.075 | 19.075 |
def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in obje... | [
"def",
"FloatField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default... | 47.75 | 19.625 |
def as_compatible_data(data, fastpath=False):
"""Prepare and wrap data to put in a Variable.
- If data does not have the necessary attributes, convert it to ndarray.
- If data has dtype=datetime64, ensure that it has ns precision. If it's a
pandas.Timestamp, convert it to datetime64.
- If data is... | [
"def",
"as_compatible_data",
"(",
"data",
",",
"fastpath",
"=",
"False",
")",
":",
"if",
"fastpath",
"and",
"getattr",
"(",
"data",
",",
"'ndim'",
",",
"0",
")",
">",
"0",
":",
"# can't use fastpath (yet) for scalars",
"return",
"_maybe_wrap_data",
"(",
"data"... | 33.654545 | 17.236364 |
def on_close(self):
'''
Called when client closes this connection. Cleanup
is done here.
'''
if self.id in self.funcserver.websocks:
self.funcserver.websocks[self.id] = None
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_callback(lambda:... | [
"def",
"on_close",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
"in",
"self",
".",
"funcserver",
".",
"websocks",
":",
"self",
".",
"funcserver",
".",
"websocks",
"[",
"self",
".",
"id",
"]",
"=",
"None",
"ioloop",
"=",
"tornado",
".",
"ioloop",
... | 37.3125 | 22.4375 |
def _translate_str(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a STR instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > op... | [
"def",
"_translate_str",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"op3_var",
",",
"op3_var_co... | 36.6875 | 17.375 |
def _new_stream(self, idx):
'''Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# Don't activate the stream if the weight is 0 or None
if self.stream_weights_[idx]:
... | [
"def",
"_new_stream",
"(",
"self",
",",
"idx",
")",
":",
"# Don't activate the stream if the weight is 0 or None",
"if",
"self",
".",
"stream_weights_",
"[",
"idx",
"]",
":",
"self",
".",
"streams_",
"[",
"idx",
"]",
"=",
"self",
".",
"streamers",
"[",
"idx",
... | 30.4375 | 16.4375 |
def glossary_path(cls, project, location, glossary):
"""Return a fully-qualified glossary string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/glossaries/{glossary}",
project=project,
location=location,
glossary=... | [
"def",
"glossary_path",
"(",
"cls",
",",
"project",
",",
"location",
",",
"glossary",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/locations/{location}/glossaries/{glossary}\"",
",",
"project",
"=",
"... | 41.5 | 15.375 |
def parse(readDataInstance):
"""
Returns a new L{NetMetaDataTableHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{NetMetaDataTableHeader} object.
@rtype: L{NetMetaDataTableHeader}
... | [
"def",
"parse",
"(",
"readDataInstance",
")",
":",
"th",
"=",
"NetMetaDataTableHeader",
"(",
")",
"th",
".",
"reserved_1",
".",
"value",
"=",
"readDataInstance",
".",
"readDword",
"(",
")",
"th",
".",
"majorVersion",
".",
"value",
"=",
"readDataInstance",
".... | 40.380952 | 19.714286 |
def uf_pelo_codigo(codigo_ibge):
"""Retorna a UF para o código do IBGE informado."""
idx = [i for s, i, n, r in UNIDADES_FEDERACAO].index(codigo_ibge)
return UNIDADES_FEDERACAO[idx][_UF_SIGLA] | [
"def",
"uf_pelo_codigo",
"(",
"codigo_ibge",
")",
":",
"idx",
"=",
"[",
"i",
"for",
"s",
",",
"i",
",",
"n",
",",
"r",
"in",
"UNIDADES_FEDERACAO",
"]",
".",
"index",
"(",
"codigo_ibge",
")",
"return",
"UNIDADES_FEDERACAO",
"[",
"idx",
"]",
"[",
"_UF_SI... | 50.25 | 10.5 |
def ListMigrationsToProcess(migrations_root,
current_migration_number
):
"""Lists filenames of migrations with numbers bigger than a given one."""
migrations = []
for m in os.listdir(migrations_root):
if (current_migration_number is None or
_Migra... | [
"def",
"ListMigrationsToProcess",
"(",
"migrations_root",
",",
"current_migration_number",
")",
":",
"migrations",
"=",
"[",
"]",
"for",
"m",
"in",
"os",
".",
"listdir",
"(",
"migrations_root",
")",
":",
"if",
"(",
"current_migration_number",
"is",
"None",
"or",... | 40.363636 | 13.363636 |
def p_created_1(self, p):
"""created : CREATED DATE"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.set_created_date(self.document, value)
except CardinalityError:
self.more_... | [
"def",
"p_created_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"value",
"=",
"p",
"[",
"2",
"]",
".",
"decode",
"(",
"encoding",
"=",
"'utf-8'",
")",
"else",
":",
"value",
"=",
"p",
"[",
"2",
"]",
"self",
"."... | 34.9 | 15.9 |
def format_string(format, *cols):
"""
Formats the arguments in printf-style and returns the result as a string column.
:param col: the column name of the numeric value to be formatted
:param d: the N decimal places
>>> df = spark.createDataFrame([(5, "hello")], ['a', 'b'])
>>> df.select(format... | [
"def",
"format_string",
"(",
"format",
",",
"*",
"cols",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"format_string",
"(",
"format",
",",
"_to_seq",
"(",
"sc",
",",
... | 40.692308 | 22.692308 |
def resource_from_etree(self, etree, resource_class):
"""Construct a Resource from an etree.
Parameters:
etree - the etree to parse
resource_class - class of Resource object to create
The parsing is properly namespace aware but we search just
for the elements wanted a... | [
"def",
"resource_from_etree",
"(",
"self",
",",
"etree",
",",
"resource_class",
")",
":",
"loc_elements",
"=",
"etree",
".",
"findall",
"(",
"'{'",
"+",
"SITEMAP_NS",
"+",
"\"}loc\"",
")",
"if",
"(",
"len",
"(",
"loc_elements",
")",
">",
"1",
")",
":",
... | 48.079365 | 17.587302 |
def get_size(
self,
bucket: str,
key: str
) -> int:
"""
Retrieves the filesize
:param bucket: the bucket the object resides in.
:param key: the key of the object for which size is being retrieved.
:return: integer equal to filesize in bytes... | [
"def",
"get_size",
"(",
"self",
",",
"bucket",
":",
"str",
",",
"key",
":",
"str",
")",
"->",
"int",
":",
"blob_obj",
"=",
"self",
".",
"_get_blob_obj",
"(",
"bucket",
",",
"key",
")",
"return",
"blob_obj",
".",
"size"
] | 30.769231 | 16 |
def remove_filter_set(self, filter_name):
"""
Remove filter set by name
:param filter_name: str
"""
if filter_name in self._filter_sets:
del self._filter_sets[filter_name]
else:
raise ValueError('Unknown filter set name.') | [
"def",
"remove_filter_set",
"(",
"self",
",",
"filter_name",
")",
":",
"if",
"filter_name",
"in",
"self",
".",
"_filter_sets",
":",
"del",
"self",
".",
"_filter_sets",
"[",
"filter_name",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown filter set name.'"... | 31.777778 | 7.777778 |
def write_array(self, outfile, pixels):
"""
Write an array that holds all the image values
as a PNG file on the output file.
See also :meth:`write` method.
"""
if self.interlace:
if type(pixels) != array:
# Coerce to array type
... | [
"def",
"write_array",
"(",
"self",
",",
"outfile",
",",
"pixels",
")",
":",
"if",
"self",
".",
"interlace",
":",
"if",
"type",
"(",
"pixels",
")",
"!=",
"array",
":",
"# Coerce to array type",
"fmt",
"=",
"'BH'",
"[",
"self",
".",
"bitdepth",
">",
"8",... | 36.133333 | 11.866667 |
def fmtinfo(value):
"""Returns (typetag, text, is_imprecise). Unlike other functions that operate
on measurements, this also operates on bools, ints, and strings.
"""
if value is None:
raise ValueError('cannot format None!')
if isinstance(value, text_type):
return '', value, False
... | [
"def",
"fmtinfo",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'cannot format None!'",
")",
"if",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"return",
"''",
",",
"value",
",",
"False",
"if",
"isinsta... | 30.407407 | 19.222222 |
def dnsdumpster(domain, output_dir):
"""Query dnsdumpster.com."""
response = requests.Session().get('https://dnsdumpster.com/').text
csrf_token = re.search(
r"name='csrfmiddlewaretoken' value='(.*?)'", response).group(1)
cookies = {'csrftoken': csrf_token}
headers = {'Referer': 'https://dns... | [
"def",
"dnsdumpster",
"(",
"domain",
",",
"output_dir",
")",
":",
"response",
"=",
"requests",
".",
"Session",
"(",
")",
".",
"get",
"(",
"'https://dnsdumpster.com/'",
")",
".",
"text",
"csrf_token",
"=",
"re",
".",
"search",
"(",
"r\"name='csrfmiddlewaretoken... | 45.125 | 19.75 |
def load_febrl4(return_links=False):
"""Load the FEBRL 4 datasets.
The Freely Extensible Biomedical Record Linkage (Febrl) package is
distributed with a dataset generator and four datasets generated
with the generator. This function returns the fourth Febrl dataset
as a :class:`pandas.DataFrame`.
... | [
"def",
"load_febrl4",
"(",
"return_links",
"=",
"False",
")",
":",
"df_a",
"=",
"_febrl_load_data",
"(",
"'dataset4a.csv'",
")",
"df_b",
"=",
"_febrl_load_data",
"(",
"'dataset4b.csv'",
")",
"if",
"return_links",
":",
"links",
"=",
"pandas",
".",
"MultiIndex",
... | 35.756098 | 22.195122 |
def compare(expr, value, regex_expr=False):
"""
Compares an string or regular expression againast a given value.
Arguments:
expr (str|regex): string or regular expression value to compare.
value (str): value to compare against to.
regex_expr (bool, optional): enables string based re... | [
"def",
"compare",
"(",
"expr",
",",
"value",
",",
"regex_expr",
"=",
"False",
")",
":",
"# Strict equality comparison",
"if",
"expr",
"==",
"value",
":",
"return",
"True",
"# Infer negate expression to match, if needed",
"negate",
"=",
"False",
"if",
"isinstance",
... | 25.714286 | 21.085714 |
def rvir(self,H=70.,Om=0.3,overdens=200.,wrtcrit=False,ro=None,vo=None,
use_physical=False): # use_physical necessary bc of pop=False, does nothing inside
"""
NAME:
rvir
PURPOSE:
calculate the virial radius for this density distribution
INPUT:
... | [
"def",
"rvir",
"(",
"self",
",",
"H",
"=",
"70.",
",",
"Om",
"=",
"0.3",
",",
"overdens",
"=",
"200.",
",",
"wrtcrit",
"=",
"False",
",",
"ro",
"=",
"None",
",",
"vo",
"=",
"None",
",",
"use_physical",
"=",
"False",
")",
":",
"# use_physical necess... | 32.222222 | 29.555556 |
def resample(self, data, input_rate):
"""
Microphone may not support our native processing sampling rate, so
resample from input_rate to RATE_PROCESS here for webrtcvad and
deepspeech
Args:
data (binary): Input audio stream
input_rate (int): Input audio r... | [
"def",
"resample",
"(",
"self",
",",
"data",
",",
"input_rate",
")",
":",
"data16",
"=",
"np",
".",
"fromstring",
"(",
"string",
"=",
"data",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"resample_size",
"=",
"int",
"(",
"len",
"(",
"data16",
")",
"... | 41.866667 | 18.533333 |
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):
"""Calculate Jensen-Shannon divergence between query and reference gene expression profile.
"""
gene_jsd_dict = dict()
reference_genes = ref_gene_expression_dict.keys()
assert len(reference_genes) != 'Reference g... | [
"def",
"njsd",
"(",
"network",
",",
"ref_gene_expression_dict",
",",
"query_gene_expression_dict",
",",
"gene_set",
")",
":",
"gene_jsd_dict",
"=",
"dict",
"(",
")",
"reference_genes",
"=",
"ref_gene_expression_dict",
".",
"keys",
"(",
")",
"assert",
"len",
"(",
... | 45.111111 | 29.407407 |
def copy_figure_to_clipboard(figure='gcf'):
"""
Copies the specified figure to the system clipboard. Specifying 'gcf'
will use the current figure.
"""
try:
import pyqtgraph as _p
# Get the current figure if necessary
if figure is 'gcf': figure = _s.pylab.gcf(... | [
"def",
"copy_figure_to_clipboard",
"(",
"figure",
"=",
"'gcf'",
")",
":",
"try",
":",
"import",
"pyqtgraph",
"as",
"_p",
"# Get the current figure if necessary ",
"if",
"figure",
"is",
"'gcf'",
":",
"figure",
"=",
"_s",
".",
"pylab",
".",
"gcf",
"(",
")... | 37.285714 | 20.809524 |
def parse_set(string):
"""Parse set from comma separated string."""
string = string.strip()
if string:
return set(string.split(","))
else:
return set() | [
"def",
"parse_set",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"strip",
"(",
")",
"if",
"string",
":",
"return",
"set",
"(",
"string",
".",
"split",
"(",
"\",\"",
")",
")",
"else",
":",
"return",
"set",
"(",
")"
] | 25.285714 | 15.857143 |
def not_query(expression):
"""Apply logical not operator to expression."""
compiled_expression = compile_query(expression)
def _not(index, expression=compiled_expression):
"""Return store key for documents that satisfy expression."""
all_keys = index.get_all_keys()
returned_keys = e... | [
"def",
"not_query",
"(",
"expression",
")",
":",
"compiled_expression",
"=",
"compile_query",
"(",
"expression",
")",
"def",
"_not",
"(",
"index",
",",
"expression",
"=",
"compiled_expression",
")",
":",
"\"\"\"Return store key for documents that satisfy expression.\"\"\"... | 37.454545 | 15.636364 |
def check_assumptions(
self, training_df, advice=True, show_plots=False, p_value_threshold=0.01, plot_n_bootstraps=10
):
"""
Use this function to test the proportional hazards assumption. See usage example at
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%2... | [
"def",
"check_assumptions",
"(",
"self",
",",
"training_df",
",",
"advice",
"=",
"True",
",",
"show_plots",
"=",
"False",
",",
"p_value_threshold",
"=",
"0.01",
",",
"plot_n_bootstraps",
"=",
"10",
")",
":",
"if",
"not",
"training_df",
".",
"index",
".",
"... | 45.990148 | 27.152709 |
def run(self, default=None):
"""Parse the command line arguments.
default:
Name of default command to run if no arguments are passed.
"""
parent, *sys_args = sys.argv
self.parent = Path(parent).stem
cmd_name = default
if sys_args:
cmd_nam... | [
"def",
"run",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"parent",
",",
"",
"*",
"sys_args",
"=",
"sys",
".",
"argv",
"self",
".",
"parent",
"=",
"Path",
"(",
"parent",
")",
".",
"stem",
"cmd_name",
"=",
"default",
"if",
"sys_args",
":",
... | 28.76 | 17.44 |
def prepare_communication (self):
"""
Prepare the buffers to be used for later communications
"""
RectPartitioner.prepare_communication (self)
if self.lower_neighbors[0]>=0:
self.in_lower_buffers = [zeros(1, float)]
self.out_lower_buffers... | [
"def",
"prepare_communication",
"(",
"self",
")",
":",
"RectPartitioner",
".",
"prepare_communication",
"(",
"self",
")",
"if",
"self",
".",
"lower_neighbors",
"[",
"0",
"]",
">=",
"0",
":",
"self",
".",
"in_lower_buffers",
"=",
"[",
"zeros",
"(",
"1",
","... | 36.615385 | 12.615385 |
def _xml(self):
"""
Returns the color information as XML.
The XML has the following structure:
<colors query="">
<color name="" weight="" />
<rgb r="" g="" b="" />
<shade name="" weight="" />
</color>
</colors>
Not... | [
"def",
"_xml",
"(",
"self",
")",
":",
"grouped",
"=",
"self",
".",
"_weight_by_hue",
"(",
")",
"xml",
"=",
"\"<colors query=\\\"\"",
"+",
"self",
".",
"name",
"+",
"\"\\\" tags=\\\"\"",
"+",
"\", \"",
".",
"join",
"(",
"self",
".",
"tags",
")",
"+",
"\... | 42.818182 | 22.818182 |
def delete(name):
'''Delete the given virtual folder. This operation is irreversible!
NAME: Name of a virtual folder.
'''
with Session() as session:
try:
session.VFolder(name).delete()
print_done('Deleted.')
except Exception as e:
print_error(e)
... | [
"def",
"delete",
"(",
"name",
")",
":",
"with",
"Session",
"(",
")",
"as",
"session",
":",
"try",
":",
"session",
".",
"VFolder",
"(",
"name",
")",
".",
"delete",
"(",
")",
"print_done",
"(",
"'Deleted.'",
")",
"except",
"Exception",
"as",
"e",
":",
... | 27.25 | 18.25 |
def get_text(self, deserialized_json):
"""Recursively get text from subcomponents of a deserialized json. To
enforce the same order on the documents, make sure to read keys of
deserialized_json in a consistent (alphabetical) order.
"""
if isinstance(deserialized_json, dict):
... | [
"def",
"get_text",
"(",
"self",
",",
"deserialized_json",
")",
":",
"if",
"isinstance",
"(",
"deserialized_json",
",",
"dict",
")",
":",
"result",
"=",
"''",
"for",
"key",
"in",
"sorted",
"(",
"deserialized_json",
")",
":",
"result",
"+=",
"self",
".",
"... | 37.761905 | 16.047619 |
def load_batch_x(path_batch,
flatten = False,
time_major = False):
""" Loads a batch of input features given a list of paths to numpy
arrays in that batch."""
utterances = [np.load(str(path)) for path in path_batch]
utter_lens = [utterance.shape[0] for utterance in utt... | [
"def",
"load_batch_x",
"(",
"path_batch",
",",
"flatten",
"=",
"False",
",",
"time_major",
"=",
"False",
")",
":",
"utterances",
"=",
"[",
"np",
".",
"load",
"(",
"str",
"(",
"path",
")",
")",
"for",
"path",
"in",
"path_batch",
"]",
"utter_lens",
"=",
... | 39 | 12.176471 |
def interm_size(self)-> Sequence[Sequence[int]]:
'''The size of each intermediate fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent.
'''
fluents = self.domain.intermediate_flue... | [
"def",
"interm_size",
"(",
"self",
")",
"->",
"Sequence",
"[",
"Sequence",
"[",
"int",
"]",
"]",
":",
"fluents",
"=",
"self",
".",
"domain",
".",
"intermediate_fluents",
"ordering",
"=",
"self",
".",
"domain",
".",
"interm_fluent_ordering",
"return",
"self",... | 42 | 20.6 |
def distance2_to_line(pt, l0, l1):
'''The perpendicular distance squared from a point to a line
pt - point in question
l0 - one point on the line
l1 - another point on the line
'''
pt = np.atleast_1d(pt)
l0 = np.atleast_1d(l0)
l1 = np.atleast_1d(l1)
reshape = pt.ndim == 1
if... | [
"def",
"distance2_to_line",
"(",
"pt",
",",
"l0",
",",
"l1",
")",
":",
"pt",
"=",
"np",
".",
"atleast_1d",
"(",
"pt",
")",
"l0",
"=",
"np",
".",
"atleast_1d",
"(",
"l0",
")",
"l1",
"=",
"np",
".",
"atleast_1d",
"(",
"l1",
")",
"reshape",
"=",
"... | 31.052632 | 17.578947 |
def record_context(self, space, frame):
"""Record a __context__ for this exception from the current
frame if one exists.
__context__ is otherwise lazily determined from the
traceback. However the current frame.last_exception must be
checked for a __context__ before this Operatio... | [
"def",
"record_context",
"(",
"self",
",",
"space",
",",
"frame",
")",
":",
"last_exception",
"=",
"frame",
".",
"last_exception",
"if",
"(",
"last_exception",
"is",
"not",
"None",
"and",
"not",
"frame",
".",
"hide",
"(",
")",
"or",
"last_exception",
"is",... | 52.166667 | 18.166667 |
def artist_versions(self, name=None, updater_name=None, updater_id=None,
artist_id=None, is_active=None, is_banned=None,
order=None):
"""Get list of artist versions (Requires login).
Parameters:
name (str):
updater_name (str):
... | [
"def",
"artist_versions",
"(",
"self",
",",
"name",
"=",
"None",
",",
"updater_name",
"=",
"None",
",",
"updater_id",
"=",
"None",
",",
"artist_id",
"=",
"None",
",",
"is_active",
"=",
"None",
",",
"is_banned",
"=",
"None",
",",
"order",
"=",
"None",
"... | 38.25 | 13.458333 |
def train(self, sentences, save_loc=None, nr_iter=5):
'''Train a model from sentences, and save it at ``save_loc``. ``nr_iter``
controls the number of Perceptron training iterations.
:param sentences: A list of (words, tags) tuples.
:param save_loc: If not ``None``, saves a pickled mode... | [
"def",
"train",
"(",
"self",
",",
"sentences",
",",
"save_loc",
"=",
"None",
",",
"nr_iter",
"=",
"5",
")",
":",
"self",
".",
"_make_tagdict",
"(",
"sentences",
")",
"self",
".",
"model",
".",
"classes",
"=",
"self",
".",
"classes",
"for",
"iter_",
"... | 45.885714 | 17.428571 |
def setup(self, paths=None): # pylint: disable=arguments-differ
"""Sets up the _paths attribute.
Args:
paths: Comma-separated list of strings representing the paths to collect.
"""
if not paths:
self.state.add_error(
'No `paths` argument provided in recipe, bailing', critical=Tru... | [
"def",
"setup",
"(",
"self",
",",
"paths",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"if",
"not",
"paths",
":",
"self",
".",
"state",
".",
"add_error",
"(",
"'No `paths` argument provided in recipe, bailing'",
",",
"critical",
"=",
"True",
")",
... | 35.818182 | 24.272727 |
def set_tracking_id(self, data, clear=False):
""" Add tracking-id data to the tracking_id group.
:param data: A dictionary of key/value pairs. Keys must be strings.
Values can be strings or numeric values.
:param clear: If set, any existing tracking-id data will be removed. ... | [
"def",
"set_tracking_id",
"(",
"self",
",",
"data",
",",
"clear",
"=",
"False",
")",
":",
"self",
".",
"assert_writeable",
"(",
")",
"self",
".",
"_add_attributes",
"(",
"self",
".",
"global_key",
"+",
"'tracking_id'",
",",
"data",
",",
"clear",
")",
"re... | 44.5 | 19 |
def _cache_update_needed(self, courseid):
"""
:param courseid: the (valid) course id of the course
:raise InvalidNameException, CourseNotFoundException
:return: True if an update of the cache is needed, False else
"""
if courseid not in self._cache:
return Tru... | [
"def",
"_cache_update_needed",
"(",
"self",
",",
"courseid",
")",
":",
"if",
"courseid",
"not",
"in",
"self",
".",
"_cache",
":",
"return",
"True",
"try",
":",
"descriptor_name",
"=",
"self",
".",
"_get_course_descriptor_path",
"(",
"courseid",
")",
"last_upda... | 44.481481 | 23.222222 |
def get_compositions_by_repository(self, repository_id):
"""Gets the list of ``Compositions`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.CompositionList) - list of related
compositions
raise... | [
"def",
"get_compositions_by_repository",
"(",
"self",
",",
"repository_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_resources_by_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'REPOSITORY'",
",",
"local",
"=",
"True"... | 52.052632 | 21.368421 |
def expunge(self, instance):
'''Remove *instance* from the :class:`Session`. Instance could be a
:class:`Model` or an id.
:parameter instance: a :class:`Model` or an *id*
:rtype: the :class:`Model` removed from session or ``None`` if
it was not in the session.
'''
instance = self.pop(instan... | [
"def",
"expunge",
"(",
"self",
",",
"instance",
")",
":",
"instance",
"=",
"self",
".",
"pop",
"(",
"instance",
")",
"instance",
".",
"session",
"=",
"None",
"return",
"instance"
] | 33.727273 | 18.636364 |
def get_user(email, password, *args, **kwargs):
"""Get user for grant type password.
Needed for grant type 'password'. Note, grant type password is by default
disabled.
:param email: User email.
:param password: Password.
:returns: The user instance or ``None``.
"""
user = datastore.fi... | [
"def",
"get_user",
"(",
"email",
",",
"password",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user",
"=",
"datastore",
".",
"find_user",
"(",
"email",
"=",
"email",
")",
"if",
"user",
"and",
"user",
".",
"active",
"and",
"verify_password",
... | 32.461538 | 17.923077 |
def path_trace(map_projection, pts, closed=False, meta_data=None):
'''
path_trace(proj, points) yields a path-trace object that represents the given path of points on
the given map projection proj.
The following options may be given:
* closed (default: False) specifies whether the points fo... | [
"def",
"path_trace",
"(",
"map_projection",
",",
"pts",
",",
"closed",
"=",
"False",
",",
"meta_data",
"=",
"None",
")",
":",
"return",
"PathTrace",
"(",
"map_projection",
",",
"pts",
",",
"closed",
"=",
"closed",
",",
"meta_data",
"=",
"meta_data",
")"
] | 54.692308 | 35 |
def get_data_checksum(proc_input, proc_slug, proc_version):
"""Compute checksum of processor inputs, name and version."""
checksum = hashlib.sha256()
checksum.update(json.dumps(proc_input, sort_keys=True).encode('utf-8'))
checksum.update(proc_slug.encode('utf-8'))
checksum.update(str(proc_version).e... | [
"def",
"get_data_checksum",
"(",
"proc_input",
",",
"proc_slug",
",",
"proc_version",
")",
":",
"checksum",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"checksum",
".",
"update",
"(",
"json",
".",
"dumps",
"(",
"proc_input",
",",
"sort_keys",
"=",
"True",
")"... | 51.571429 | 13.142857 |
def like_button_js_tag(context):
""" This tag will check to see if they have the FACEBOOK_LIKE_APP_ID setup
correctly in the django settings, if so then it will pass the data
along to the intercom_tag template to be displayed.
If something isn't perfect we will return False, which will then... | [
"def",
"like_button_js_tag",
"(",
"context",
")",
":",
"if",
"FACEBOOK_APP_ID",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"FACEBOOK_APP_ID isn't setup correctly in your settings\"",
")",
"# make sure FACEBOOK_APP_ID is setup correct and user is authenticated",
"if",
"FAC... | 42.363636 | 21.681818 |
def to_image(self, filename='palette.png', band_width=1, length=60,
max_width=0, vertical=True, alpha_channel=False):
"""
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the ... | [
"def",
"to_image",
"(",
"self",
",",
"filename",
"=",
"'palette.png'",
",",
"band_width",
"=",
"1",
",",
"length",
"=",
"60",
",",
"max_width",
"=",
"0",
",",
"vertical",
"=",
"True",
",",
"alpha_channel",
"=",
"False",
")",
":",
"# max_width is approximat... | 38.851064 | 21.829787 |
def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5):
"""Drag the left mouse button without modifiers pressed.
Parameters: coordinates to click on screen (tuple (x, y))
dest coordinates to drag to (tuple (x, y))
interval to send event of btn down, drag ... | [
"def",
"dragMouseButtonLeft",
"(",
"self",
",",
"coord",
",",
"dest_coord",
",",
"interval",
"=",
"0.5",
")",
":",
"modFlags",
"=",
"0",
"self",
".",
"_queueMouseButton",
"(",
"coord",
",",
"Quartz",
".",
"kCGMouseButtonLeft",
",",
"modFlags",
",",
"dest_coo... | 42.230769 | 20.923077 |
def add_data_to_attribute(scenario_id, resource_attr_id, dataset,**kwargs):
"""
Add data to a resource scenario outside of a network update
"""
user_id = kwargs.get('user_id')
_check_can_edit_scenario(scenario_id, user_id)
scenario_i = _get_scenario(scenario_id, user_id)
try:
... | [
"def",
"add_data_to_attribute",
"(",
"scenario_id",
",",
"resource_attr_id",
",",
"dataset",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"_check_can_edit_scenario",
"(",
"scenario_id",
",",
"user_id",
")",
"s... | 41.282051 | 27.692308 |
def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"underflow",
"=",
"self",
".",
"_audio_stream",
".",
"write",
"(",
"buf",
")",
"if",
"underflow",
":",
"logging",
".",
"warning",
"(",
"'SoundDeviceStream write underflow (size: %d)'",
",",
"len",
"(",
"buf"... | 38 | 14.571429 |
def columns_dataset(self):
"""
Generate the columns and the whole dataset.
"""
data = {}
words_total = {}
for instance, words in self.raw_dataset.items():
words_item_total = {}
for word in words:
words_total.setdefault(word, 0)
... | [
"def",
"columns_dataset",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"words_total",
"=",
"{",
"}",
"for",
"instance",
",",
"words",
"in",
"self",
".",
"raw_dataset",
".",
"items",
"(",
")",
":",
"words_item_total",
"=",
"{",
"}",
"for",
"word",
"i... | 34.36 | 12.04 |
def _has_y(self, kwargs):
'''Returns True if y is explicitly defined in kwargs'''
return (('y' in kwargs) or (self._element_y in kwargs) or
(self._type == 3 and self._element_1my in kwargs)) | [
"def",
"_has_y",
"(",
"self",
",",
"kwargs",
")",
":",
"return",
"(",
"(",
"'y'",
"in",
"kwargs",
")",
"or",
"(",
"self",
".",
"_element_y",
"in",
"kwargs",
")",
"or",
"(",
"self",
".",
"_type",
"==",
"3",
"and",
"self",
".",
"_element_1my",
"in",
... | 54.75 | 22.25 |
def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
status_pos = 0
for line in response.split("\n"):
if line.startswith('JOBID'):
... | [
"def",
"get_status",
"(",
"self",
",",
"response",
",",
"finished",
"=",
"False",
")",
":",
"status_pos",
"=",
"0",
"for",
"line",
"in",
"response",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'JOBID'",
")",
":",
"t... | 41.933333 | 10.066667 |
def iterative_encoder_decoder(encoder_input,
encoder_self_attention_bias,
encoder_decoder_attention_bias,
query,
hparams):
"""Iterative encoder decoder."""
for _ in range(hparams.num_rec_steps):
... | [
"def",
"iterative_encoder_decoder",
"(",
"encoder_input",
",",
"encoder_self_attention_bias",
",",
"encoder_decoder_attention_bias",
",",
"query",
",",
"hparams",
")",
":",
"for",
"_",
"in",
"range",
"(",
"hparams",
".",
"num_rec_steps",
")",
":",
"with",
"tf",
".... | 29.88 | 15.16 |
def get_events(**kwargs):
"""
Return a list of events matching the passed filter.
Supported kwargs are listed at
http://knowledge25.collegenet.com/display/WSW/events.xml
"""
url = "/r25ws/servlet/wrd/run/events.xml"
if len(kwargs):
url += "?%s" % urlencode(kwargs)
return events_... | [
"def",
"get_events",
"(",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"/r25ws/servlet/wrd/run/events.xml\"",
"if",
"len",
"(",
"kwargs",
")",
":",
"url",
"+=",
"\"?%s\"",
"%",
"urlencode",
"(",
"kwargs",
")",
"return",
"events_from_xml",
"(",
"get_resource",
... | 30.636364 | 11.545455 |
def kind(self):
'''Returns a class representing the 'kind' of optic.'''
optics = [
Equality,
Isomorphism,
Prism,
Review,
Lens,
Traversal,
Getter,
Setter,
Fold,
]
for optic in optic... | [
"def",
"kind",
"(",
"self",
")",
":",
"optics",
"=",
"[",
"Equality",
",",
"Isomorphism",
",",
"Prism",
",",
"Review",
",",
"Lens",
",",
"Traversal",
",",
"Getter",
",",
"Setter",
",",
"Fold",
",",
"]",
"for",
"optic",
"in",
"optics",
":",
"if",
"s... | 23.3125 | 19.5625 |
def parse_ctuple(s,length=2):
'''parse a string of acceptable colors into matplotlib, that is, either
strings, or three tuples of rgb. Don't quote strings.
'''
if parse_utuple(s, colrx_s, length=length) is None:
raise ValueError("{} is not a valid color tuple.".format(s));
#quote strings
... | [
"def",
"parse_ctuple",
"(",
"s",
",",
"length",
"=",
"2",
")",
":",
"if",
"parse_utuple",
"(",
"s",
",",
"colrx_s",
",",
"length",
"=",
"length",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"{} is not a valid color tuple.\"",
".",
"format",
"(",
... | 40.777778 | 21.222222 |
def invoke_with_usage (self, args, **kwargs):
"""Invoke the command with standardized usage-help processing. Same calling
convention as `Command.invoke()`.
"""
argv0 = kwargs['argv0']
usage = self._usage (argv0)
argv = [argv0] + args
uina = 'long' if self.help_if... | [
"def",
"invoke_with_usage",
"(",
"self",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"argv0",
"=",
"kwargs",
"[",
"'argv0'",
"]",
"usage",
"=",
"self",
".",
"_usage",
"(",
"argv0",
")",
"argv",
"=",
"[",
"argv0",
"]",
"+",
"args",
"uina",
"=",
... | 34.266667 | 12.266667 |
def mvarica(x, var, cl=None, reducedim=0.99, optimize_var=False, backend=None,
varfit='ensemble', random_state=None):
""" Performs joint VAR model fitting and ICA source separation.
This function implements the MVARICA procedure [1]_.
Parameters
----------
x : array-like, shape... | [
"def",
"mvarica",
"(",
"x",
",",
"var",
",",
"cl",
"=",
"None",
",",
"reducedim",
"=",
"0.99",
",",
"optimize_var",
"=",
"False",
",",
"backend",
"=",
"None",
",",
"varfit",
"=",
"'ensemble'",
",",
"random_state",
"=",
"None",
")",
":",
"x",
"=",
"... | 39.507813 | 26.070313 |
def __post(self, path, **kargs):
'''
Make a HTTP POST request to the Dominos UK API with the given
parameters for the current session.
:param string path: The API endpoint path.
:params list kargs: A list of arguments.
:return: A response from the Dominos UK API.
... | [
"def",
"__post",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kargs",
")",
":",
"return",
"self",
".",
"__call_api",
"(",
"self",
".",
"session",
".",
"post",
",",
"path",
",",
"*",
"*",
"kargs",
")"
] | 37.545455 | 18.090909 |
def is_output(self, stream):
"""Check if a stream is a sensor graph output.
Return:
bool
"""
for streamer in self.streamers:
if streamer.selector.matches(stream):
return True
return False | [
"def",
"is_output",
"(",
"self",
",",
"stream",
")",
":",
"for",
"streamer",
"in",
"self",
".",
"streamers",
":",
"if",
"streamer",
".",
"selector",
".",
"matches",
"(",
"stream",
")",
":",
"return",
"True",
"return",
"False"
] | 21.583333 | 18.666667 |
def get_first_property(elt, key, default=None, ctx=None):
"""Get first property related to one input key.
:param elt: first property elt. Not None methods.
:param str key: property key to get.
:param default: default value to return if key does not exist in elt.
properties
:param ctx: elt c... | [
"def",
"get_first_property",
"(",
"elt",
",",
"key",
",",
"default",
"=",
"None",
",",
"ctx",
"=",
"None",
")",
":",
"result",
"=",
"default",
"properties",
"=",
"_get_properties",
"(",
"elt",
",",
"keys",
"=",
"(",
"key",
",",
")",
",",
"ctx",
"=",
... | 33.571429 | 22.047619 |
def _fetch_objects(self, key, value):
"""Fetch Multiple linked objects"""
return self.to_cls.query.filter(**{key: value}) | [
"def",
"_fetch_objects",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"to_cls",
".",
"query",
".",
"filter",
"(",
"*",
"*",
"{",
"key",
":",
"value",
"}",
")"
] | 45 | 6 |
def main():
"""Use pip to find pip installed packages in a given prefix."""
pip_packages = {}
for package in pip.get_installed_distributions():
name = package.project_name
version = package.version
full_name = "{0}-{1}-pip".format(name.lower(), version)
pip_packages[full_name... | [
"def",
"main",
"(",
")",
":",
"pip_packages",
"=",
"{",
"}",
"for",
"package",
"in",
"pip",
".",
"get_installed_distributions",
"(",
")",
":",
"name",
"=",
"package",
".",
"project_name",
"version",
"=",
"package",
".",
"version",
"full_name",
"=",
"\"{0}-... | 38.7 | 14 |
def process_nxml_file(fname, output_fmt='json', outbuf=None, cleanup=True,
**kwargs):
"""Return processor with Statements extracted by reading an NXML file.
Parameters
----------
fname : str
The path to the NXML file to be read.
output_fmt: Optional[str]
The ou... | [
"def",
"process_nxml_file",
"(",
"fname",
",",
"output_fmt",
"=",
"'json'",
",",
"outbuf",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"sp",
"=",
"None",
"out_fname",
"=",
"None",
"try",
":",
"out_fname",
"=",
"run_spar... | 33.085714 | 21.914286 |
def append(self, report):
"""Append a new CSP report."""
assert report not in self.examples
self.count += 1
if len(self.examples) < self.top:
self.examples.append(report) | [
"def",
"append",
"(",
"self",
",",
"report",
")",
":",
"assert",
"report",
"not",
"in",
"self",
".",
"examples",
"self",
".",
"count",
"+=",
"1",
"if",
"len",
"(",
"self",
".",
"examples",
")",
"<",
"self",
".",
"top",
":",
"self",
".",
"examples",... | 34.833333 | 5.833333 |
def run(self):
"""
Execute all current and future payloads
Blocks and executes payloads until :py:meth:`stop` is called.
It is an error for any orphaned payload to return or raise.
"""
self._logger.info('runner started: %s', self)
try:
with self._lock... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'runner started: %s'",
",",
"self",
")",
"try",
":",
"with",
"self",
".",
"_lock",
":",
"assert",
"not",
"self",
".",
"running",
".",
"is_set",
"(",
")",
"and",
"self",
... | 34.695652 | 18.26087 |
def _load_profile_imports(self, symbol_table):
"""
profile_imports is a list of module names or tuples
of (module_name, names to import)
in the form of ('.', names) it behaces like:
from . import name1, name2, name3
or similarly
import .name1, .name2, .name3
i.e. "name" in names becomes... | [
"def",
"_load_profile_imports",
"(",
"self",
",",
"symbol_table",
")",
":",
"results",
"=",
"[",
"]",
"if",
"'profile_imports'",
"not",
"in",
"symbol_table",
":",
"return",
"results",
"package",
"=",
"self",
".",
"_get_package",
"(",
"symbol_table",
")",
"prof... | 36.037736 | 17.509434 |
def chunker(ensemble_list, ncpu):
"""
Generate successive chunks of ensemble_list.
"""
# determine sublist lengths
length = int(len(ensemble_list) / ncpu)
# generator
for i in range(0, len(ensemble_list), length):
yield ensemble_list[i:i + length] | [
"def",
"chunker",
"(",
"ensemble_list",
",",
"ncpu",
")",
":",
"# determine sublist lengths",
"length",
"=",
"int",
"(",
"len",
"(",
"ensemble_list",
")",
"/",
"ncpu",
")",
"# generator",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"ensemble_list... | 24.454545 | 12.727273 |
def get_stock_list(self):
""" 回傳日常交易的代碼與名稱
:rtype: dict
.. versionadded:: 0.5.6
"""
all_stock = self.all_stock
industry_comps = self.industry_comps
result = {}
for comps_no in self.get_stock_comps_list():
if comps_no in industry_comp... | [
"def",
"get_stock_list",
"(",
"self",
")",
":",
"all_stock",
"=",
"self",
".",
"all_stock",
"industry_comps",
"=",
"self",
".",
"industry_comps",
"result",
"=",
"{",
"}",
"for",
"comps_no",
"in",
"self",
".",
"get_stock_comps_list",
"(",
")",
":",
"if",
"c... | 28.375 | 16.4375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.