text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def session(connection_string=None):
"""Gets a SQLAlchemy session"""
global _session_makers
connection_string = connection_string or oz.settings["db"]
if not connection_string in _session_makers:
_session_makers[connection_string] = sessionmaker(bind=engine(connection_string=connection_string))... | [
"def",
"session",
"(",
"connection_string",
"=",
"None",
")",
":",
"global",
"_session_makers",
"connection_string",
"=",
"connection_string",
"or",
"oz",
".",
"settings",
"[",
"\"db\"",
"]",
"if",
"not",
"connection_string",
"in",
"_session_makers",
":",
"_sessio... | 40.111111 | 0.00813 |
def setup(args):
"""Returns the JobManager and sets up the basic infrastructure"""
kwargs = {'wrapper_script' : args.wrapper_script, 'debug' : args.verbose==3, 'database' : args.database}
if args.local:
jm = local.JobManagerLocal(**kwargs)
else:
jm = sge.JobManagerSGE(**kwargs)
# set-up logging
if... | [
"def",
"setup",
"(",
"args",
")",
":",
"kwargs",
"=",
"{",
"'wrapper_script'",
":",
"args",
".",
"wrapper_script",
",",
"'debug'",
":",
"args",
".",
"verbose",
"==",
"3",
",",
"'database'",
":",
"args",
".",
"database",
"}",
"if",
"args",
".",
"local",... | 31.888889 | 0.024803 |
def start_new_paragraph(self):
"""Make sure to create an empty line. This is overridden, if the previous
text ends with the special marker ''. In that case, nothing is done.
"""
if self.pieces[-1:] == ['']: # respect special marker
return
elif self.pieces == []: # fir... | [
"def",
"start_new_paragraph",
"(",
"self",
")",
":",
"if",
"self",
".",
"pieces",
"[",
"-",
"1",
":",
"]",
"==",
"[",
"''",
"]",
":",
"# respect special marker",
"return",
"elif",
"self",
".",
"pieces",
"==",
"[",
"]",
":",
"# first paragraph, add '\\n', o... | 46.5 | 0.017575 |
def _update_physics(self):
"""r
Update physics using the current value of 'quantity'
Notes
-----
The algorithm directly writes the value of 'quantity' into the phase.
This method was implemented relaxing one of the OpenPNM rules of
algorithms not being able to wr... | [
"def",
"_update_physics",
"(",
"self",
")",
":",
"phase",
"=",
"self",
".",
"project",
".",
"phases",
"(",
")",
"[",
"self",
".",
"settings",
"[",
"'phase'",
"]",
"]",
"physics",
"=",
"self",
".",
"project",
".",
"find_physics",
"(",
"phase",
"=",
"p... | 43.238095 | 0.002155 |
def get_bboxes_pathcollection(sc, ax):
"""Function to return a list of bounding boxes in data coordinates
for a scatter plot
Thank you to ImportanceOfBeingErnest
https://stackoverflow.com/a/55007838/1304161"""
# ax.figure.canvas.draw() # need to draw before the transforms are set.
transform = sc.... | [
"def",
"get_bboxes_pathcollection",
"(",
"sc",
",",
"ax",
")",
":",
"# ax.figure.canvas.draw() # need to draw before the transforms are set.",
"transform",
"=",
"sc",
".",
"get_transform",
"(",
")",
"transOffset",
"=",
"sc",
".",
"get_offset_transform",
"(",
")",
"of... | 37.769231 | 0.000662 |
def note_create(self, post_id, coor_x, coor_y, width, height, body):
"""Function to create a note (Requires login) (UNTESTED).
Parameters:
post_id (int):
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the i... | [
"def",
"note_create",
"(",
"self",
",",
"post_id",
",",
"coor_x",
",",
"coor_y",
",",
"width",
",",
"height",
",",
"body",
")",
":",
"params",
"=",
"{",
"'note[post_id]'",
":",
"post_id",
",",
"'note[x]'",
":",
"coor_x",
",",
"'note[y]'",
":",
"coor_y",
... | 42.272727 | 0.002103 |
def add(self, resource):
"""Add a resource to the context"""
if isinstance(resource, Resource):
if isinstance(resource, Secret) and \
resource.mount != 'cubbyhole':
ensure_backend(resource,
SecretBackend,
... | [
"def",
"add",
"(",
"self",
",",
"resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"Resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"Secret",
")",
"and",
"resource",
".",
"mount",
"!=",
"'cubbyhole'",
":",
"ensure_backend",
"(... | 44.545455 | 0.001998 |
def filter_lclist(lc_catalog,
objectidcol='objectid',
racol='ra',
declcol='decl',
xmatchexternal=None,
xmatchdistarcsec=3.0,
externalcolnums=(0,1,2),
externalcolnames=['objectid','ra','decl'],
... | [
"def",
"filter_lclist",
"(",
"lc_catalog",
",",
"objectidcol",
"=",
"'objectid'",
",",
"racol",
"=",
"'ra'",
",",
"declcol",
"=",
"'decl'",
",",
"xmatchexternal",
"=",
"None",
",",
"xmatchdistarcsec",
"=",
"3.0",
",",
"externalcolnums",
"=",
"(",
"0",
",",
... | 38.087607 | 0.001585 |
def cmd_isn(ip, port, count, iface, graph, verbose):
"""Create TCP connections and print the TCP initial sequence
numbers for each one.
\b
$ sudo habu.isn -c 5 www.portantier.com
1962287220
1800895007
589617930
3393793979
469428558
Note: You can get a graphical representation (... | [
"def",
"cmd_isn",
"(",
"ip",
",",
"port",
",",
"count",
",",
"iface",
",",
"graph",
",",
"verbose",
")",
":",
"conf",
".",
"verb",
"=",
"False",
"if",
"iface",
":",
"conf",
".",
"iface",
"=",
"iface",
"isn_values",
"=",
"[",
"]",
"for",
"_",
"in"... | 23.326531 | 0.001679 |
def configure_firewall(self, server, firewall_rule_bodies):
"""
Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies.
"""
server_uuid, server_instance = uuid_and_instance(server)
return [
self.create_firewall_rule(server_uuid, rule)
... | [
"def",
"configure_firewall",
"(",
"self",
",",
"server",
",",
"firewall_rule_bodies",
")",
":",
"server_uuid",
",",
"server_instance",
"=",
"uuid_and_instance",
"(",
"server",
")",
"return",
"[",
"self",
".",
"create_firewall_rule",
"(",
"server_uuid",
",",
"rule"... | 36.3 | 0.008065 |
def default(self, line):
"""Called on an input line when the command prefix is not recognized."""
args = self._split_args(line, 0, 99)
d1_cli.impl.util.print_error("Unknown command: {}".format(args[0])) | [
"def",
"default",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"_split_args",
"(",
"line",
",",
"0",
",",
"99",
")",
"d1_cli",
".",
"impl",
".",
"util",
".",
"print_error",
"(",
"\"Unknown command: {}\"",
".",
"format",
"(",
"args",
... | 55.75 | 0.013274 |
def _build_pipeline_request(self, task_view):
"""Returns a Pipeline objects for the task."""
job_metadata = task_view.job_metadata
job_params = task_view.job_params
job_resources = task_view.job_resources
task_metadata = task_view.task_descriptors[0].task_metadata
task_params = task_view.task_de... | [
"def",
"_build_pipeline_request",
"(",
"self",
",",
"task_view",
")",
":",
"job_metadata",
"=",
"task_view",
".",
"job_metadata",
"job_params",
"=",
"task_view",
".",
"job_params",
"job_resources",
"=",
"task_view",
".",
"job_resources",
"task_metadata",
"=",
"task_... | 39.084 | 0.000898 |
def _get_parser_call_method(func):
"""Returns the method that is linked to the 'call' method of the parser
Args:
func: the decorated function
Raises:
ParseThisError if the decorated method is __init__, __init__ can
only be decorated in a class decorated by parse_class
"""
f... | [
"def",
"_get_parser_call_method",
"(",
"func",
")",
":",
"func_name",
"=",
"func",
".",
"__name__",
"parser",
"=",
"func",
".",
"parser",
"def",
"inner_call",
"(",
"instance",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"\"\"\"This is method attached to <... | 39.222222 | 0.000691 |
def get_parser():
"""Return the parser object for this script."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-m", "--model",
... | [
"def",
"get_parser",
"(",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
",",
"ArgumentDefaultsHelpFormatter",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
... | 49.75 | 0.001645 |
def CreateDirectory(directory):
'''
Create directory including any missing intermediate directory.
:param unicode directory:
:return unicode|urlparse.ParseResult:
Returns the created directory or url (see urlparse).
:raises NotImplementedProtocol:
If protocol is not local or FTP.
... | [
"def",
"CreateDirectory",
"(",
"directory",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"directory_url",
"=",
"urlparse",
"(",
"directory",
")",
"# Handle local",
"if",
"_UrlIsLocal",
"(",
"directory_url",
")",
":"... | 31.033333 | 0.002083 |
def generate_latex_table(sampled_hmm, conf=0.95, dt=1, time_unit='ms', obs_name='force', obs_units='pN',
caption='', outfile=None):
"""
Generate a LaTeX column-wide table showing various computed properties and uncertainties.
Parameters
----------
conf : float
confi... | [
"def",
"generate_latex_table",
"(",
"sampled_hmm",
",",
"conf",
"=",
"0.95",
",",
"dt",
"=",
"1",
",",
"time_unit",
"=",
"'ms'",
",",
"obs_name",
"=",
"'force'",
",",
"obs_units",
"=",
"'pN'",
",",
"caption",
"=",
"''",
",",
"outfile",
"=",
"None",
")"... | 34.491935 | 0.01 |
def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0):
"""given a datetime.date, gives back a datetime.datetime"""
# don't mess with datetimes
if isinstance(plain_date, datetime.datetime):
return plain_date
return datetime.datetime(
plain_date.year,
plain_date.month,
... | [
"def",
"to_datetime",
"(",
"plain_date",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
",",
"ms",
"=",
"0",
")",
":",
"# don't mess with datetimes",
"if",
"isinstance",
"(",
"plain_date",
",",
"datetime",
".",
"datetime",
")... | 28.285714 | 0.002445 |
def count(self, filter=None, **kwargs):
"""Get the number of documents in this collection.
All optional count parameters should be passed as keyword arguments
to this method. Valid options include:
- `hint` (string or list of tuples): The index to use. Specify either
the ... | [
"def",
"count",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"SON",
"(",
"[",
"(",
"\"count\"",
",",
"self",
".",
"__name",
")",
"]",
")",
"if",
"filter",
"is",
"not",
"None",
":",
"if",
"\"query\"",
"... | 45.075 | 0.001629 |
def check_cmms_affection_status(self, ind_object):
"""
Check if the affection status is correct.
Args:
ind_object : An Individuals object
Yields:
bool : True if affection status is correct
False otherwise
"""
... | [
"def",
"check_cmms_affection_status",
"(",
"self",
",",
"ind_object",
")",
":",
"valid_affection_statuses",
"=",
"[",
"'A'",
",",
"'U'",
",",
"'X'",
"]",
"ind_id",
"=",
"ind_object",
".",
"individual_id",
".",
"split",
"(",
"'-'",
")",
"phenotype",
"=",
"ind... | 36.576923 | 0.012295 |
def calculate_imf_steadiness(inst, steady_window=15, min_window_frac=0.75,
max_clock_angle_std=90.0/np.pi, max_bmag_cv=0.5):
""" Calculate IMF steadiness using clock angle standard deviation and
the coefficient of variation of the IMF magnitude in the GSM Y-Z plane
Parameters
... | [
"def",
"calculate_imf_steadiness",
"(",
"inst",
",",
"steady_window",
"=",
"15",
",",
"min_window_frac",
"=",
"0.75",
",",
"max_clock_angle_std",
"=",
"90.0",
"/",
"np",
".",
"pi",
",",
"max_bmag_cv",
"=",
"0.5",
")",
":",
"# We are not going to interpolate throug... | 44.376812 | 0.001917 |
def leader_set(settings=None, **kwargs):
"""Juju leader set value(s)"""
# Don't log secrets.
# log("Juju leader-set '%s'" % (settings), level=DEBUG)
cmd = ['leader-set']
settings = settings or {}
settings.update(kwargs)
for k, v in settings.items():
if v is None:
cmd.appe... | [
"def",
"leader_set",
"(",
"settings",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Don't log secrets.",
"# log(\"Juju leader-set '%s'\" % (settings), level=DEBUG)",
"cmd",
"=",
"[",
"'leader-set'",
"]",
"settings",
"=",
"settings",
"or",
"{",
"}",
"settings",
... | 32.076923 | 0.002331 |
def default_blockstack_opts( working_dir, config_file=None ):
"""
Get our default blockstack opts from a config file
or from sane defaults.
"""
global RPC_SERVER_IP, RPC_SERVER_PORT
from .util import url_to_host_port
from .scripts import is_name_valid
if config_file is None:
config_file... | [
"def",
"default_blockstack_opts",
"(",
"working_dir",
",",
"config_file",
"=",
"None",
")",
":",
"global",
"RPC_SERVER_IP",
",",
"RPC_SERVER_PORT",
"from",
".",
"util",
"import",
"url_to_host_port",
"from",
".",
"scripts",
"import",
"is_name_valid",
"if",
"config_fi... | 35.578378 | 0.024978 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'xpaths') and self.xpaths is not None:
_dict['xpaths'] = self.xpaths
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'xpaths'",
")",
"and",
"self",
".",
"xpaths",
"is",
"not",
"None",
":",
"_dict",
"[",
"'xpaths'",
"]",
"=",
"self",
".",
"xpaths",
"return",
"_dic... | 37.333333 | 0.008734 |
def set_predicted_log_arr(self, value):
''' setter '''
if isinstance(value, np.ndarray):
self.__predicted_log_arr = value
else:
raise TypeError() | [
"def",
"set_predicted_log_arr",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"np",
".",
"ndarray",
")",
":",
"self",
".",
"__predicted_log_arr",
"=",
"value",
"else",
":",
"raise",
"TypeError",
"(",
")"
] | 31.333333 | 0.010363 |
def draw_image(self, image, xmin=0, ymin=0, xmax=None, ymax=None):
"""Draw an image.
Do not forget to use :meth:`set_axis_equal` to preserve the
aspect ratio of the image, or change the aspect ratio of the
plot to the aspect ratio of the image.
:param image: Pillow Image object... | [
"def",
"draw_image",
"(",
"self",
",",
"image",
",",
"xmin",
"=",
"0",
",",
"ymin",
"=",
"0",
",",
"xmax",
"=",
"None",
",",
"ymax",
"=",
"None",
")",
":",
"if",
"xmax",
"is",
"None",
":",
"xmax",
"=",
"xmin",
"+",
"image",
".",
"size",
"[",
... | 37.615385 | 0.001329 |
def drawForeground(self, painter, rect):
"""
Draws the foreground for this scene.
:param painter | <QPainter>
rect | <QRect>
"""
gantt = self.ganttWidget()
header = gantt.treeWidget().header()
width = self.sceneRect(... | [
"def",
"drawForeground",
"(",
"self",
",",
"painter",
",",
"rect",
")",
":",
"gantt",
"=",
"self",
".",
"ganttWidget",
"(",
")",
"header",
"=",
"gantt",
".",
"treeWidget",
"(",
")",
".",
"header",
"(",
")",
"width",
"=",
"self",
".",
"sceneRect",
"("... | 36.052632 | 0.009957 |
def _step1ab(self, word):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
sties -> sti
tie -> tie (--NEW--: see below)
caress -> caress
cats -> cat
feed ... | [
"def",
"_step1ab",
"(",
"self",
",",
"word",
")",
":",
"if",
"word",
"[",
"-",
"1",
"]",
"==",
"'s'",
":",
"if",
"word",
".",
"endswith",
"(",
"\"sses\"",
")",
":",
"word",
"=",
"word",
"[",
":",
"-",
"2",
"]",
"elif",
"word",
".",
"endswith",
... | 31.166667 | 0.002356 |
def IsDecltype(clean_lines, linenum, column):
"""Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is declty... | [
"def",
"IsDecltype",
"(",
"clean_lines",
",",
"linenum",
",",
"column",
")",
":",
"(",
"text",
",",
"_",
",",
"start_col",
")",
"=",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"column",
")",
"if",
"start_col",
"<",
"0",
":",
"retu... | 33.8125 | 0.010791 |
def available_languages(wordlist='best'):
"""
Given a wordlist name, return a dictionary of language codes to filenames,
representing all the languages in which that wordlist is available.
"""
if wordlist == 'best':
available = available_languages('small')
available.update(available_... | [
"def",
"available_languages",
"(",
"wordlist",
"=",
"'best'",
")",
":",
"if",
"wordlist",
"==",
"'best'",
":",
"available",
"=",
"available_languages",
"(",
"'small'",
")",
"available",
".",
"update",
"(",
"available_languages",
"(",
"'large'",
")",
")",
"retu... | 35.086957 | 0.001206 |
def SetupToolBar(self):
"""Create the toolbar for common actions"""
tb = self.CreateToolBar(self.TBFLAGS)
tsize = (24, 24)
tb.ToolBitmapSize = tsize
open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR,
tsize)
tb... | [
"def",
"SetupToolBar",
"(",
"self",
")",
":",
"tb",
"=",
"self",
".",
"CreateToolBar",
"(",
"self",
".",
"TBFLAGS",
")",
"tsize",
"=",
"(",
"24",
",",
"24",
")",
"tb",
".",
"ToolBitmapSize",
"=",
"tsize",
"open_bmp",
"=",
"wx",
".",
"ArtProvider",
".... | 49.55814 | 0.008283 |
def _process_emerge_err(stdout, stderr):
'''
Used to parse emerge output to provide meaningful output when emerge fails
'''
ret = {}
rexp = re.compile(r'^[<>=][^ ]+/[^ ]+ [^\n]+', re.M)
slot_conflicts = re.compile(r'^[^ \n]+/[^ ]+:[^ ]', re.M).findall(stderr)
if slot_conflicts:
ret[... | [
"def",
"_process_emerge_err",
"(",
"stdout",
",",
"stderr",
")",
":",
"ret",
"=",
"{",
"}",
"rexp",
"=",
"re",
".",
"compile",
"(",
"r'^[<>=][^ ]+/[^ ]+ [^\\n]+'",
",",
"re",
".",
"M",
")",
"slot_conflicts",
"=",
"re",
".",
"compile",
"(",
"r'^[^ \\n]+/[^ ... | 36.484848 | 0.000809 |
def from_polar(r, theta, phi):
"""Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three polar parameters is designed to
match both ISO 31... | [
"def",
"from_polar",
"(",
"r",
",",
"theta",
",",
"phi",
")",
":",
"rxy",
"=",
"r",
"*",
"cos",
"(",
"theta",
")",
"return",
"array",
"(",
"(",
"rxy",
"*",
"cos",
"(",
"phi",
")",
",",
"rxy",
"*",
"sin",
"(",
"phi",
")",
",",
"r",
"*",
"sin... | 41.25 | 0.001481 |
def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__arguments__
for idx, (args, kwargs) in enumerate(arguments):
arg_name = kwargs.get(
'dest', args[... | [
"def",
"has_argument",
"(",
"arg",
",",
"arguments",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"arguments",
"=",
"arguments",
".",
"__arguments__",
"for",
"idx",
",",
"(",
"args",
",",
"kwargs",
")",
"in"... | 30.875 | 0.001965 |
def createDdbTable(region=None, table="credential-store", **kwargs):
'''
create the secret store table in DDB in the specified region
'''
session = get_session(**kwargs)
dynamodb = session.resource("dynamodb", region_name=region)
if table in (t.name for t in dynamodb.tables.all()):
print... | [
"def",
"createDdbTable",
"(",
"region",
"=",
"None",
",",
"table",
"=",
"\"credential-store\"",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"get_session",
"(",
"*",
"*",
"kwargs",
")",
"dynamodb",
"=",
"session",
".",
"resource",
"(",
"\"dynamodb\""... | 26.466667 | 0.000607 |
def from_etree(cls, etree_element):
"""
creates a ``SaltLayer`` instance from the etree representation of an
<layers> element from a SaltXMI file.
"""
ins = SaltElement.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
# convert S... | [
"def",
"from_etree",
"(",
"cls",
",",
"etree_element",
")",
":",
"ins",
"=",
"SaltElement",
".",
"from_etree",
"(",
"etree_element",
")",
"# TODO: this looks dangerous, ask Stackoverflow about it!",
"# convert SaltElement into SaltLayer",
"ins",
".",
"__class__",
"=",
"Sa... | 40.95 | 0.002387 |
def _action_get(self, ids):
"""Get the details for ids
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to get
Notes
-----
If ids is empty, then all IDs are returned.
Returns
-------
list of dict
... | [
"def",
"_action_get",
"(",
"self",
",",
"ids",
")",
":",
"if",
"not",
"ids",
":",
"ids",
"=",
"self",
".",
"jobs",
"result",
"=",
"[",
"]",
"ids",
"=",
"set",
"(",
"ids",
")",
"while",
"ids",
":",
"id_",
"=",
"ids",
".",
"pop",
"(",
")",
"if"... | 22.574468 | 0.001807 |
def createStateText(self):
'''Creates the mode and arm state text.'''
self.modeText = self.axes.text(self.leftPos+(self.vertSize/10.0),0.97,'UNKNOWN',color='grey',size=1.5*self.fontSize,ha='left',va='top')
self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foregr... | [
"def",
"createStateText",
"(",
"self",
")",
":",
"self",
".",
"modeText",
"=",
"self",
".",
"axes",
".",
"text",
"(",
"self",
".",
"leftPos",
"+",
"(",
"self",
".",
"vertSize",
"/",
"10.0",
")",
",",
"0.97",
",",
"'UNKNOWN'",
",",
"color",
"=",
"'g... | 83 | 0.032836 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = settings.engine
with connectable.connect() as connection:
context.configure(
connection=connection,
... | [
"def",
"run_migrations_online",
"(",
")",
":",
"connectable",
"=",
"settings",
".",
"engine",
"with",
"connectable",
".",
"connect",
"(",
")",
"as",
"connection",
":",
"context",
".",
"configure",
"(",
"connection",
"=",
"connection",
",",
"transaction_per_migra... | 27.315789 | 0.001862 |
def main(args=sys.argv[1:]):
"""Run the commandline script"""
usage = "%prog --help"
parser = OptionParser(usage, add_help_option=False)
parser.add_option('-c', '--config', help="Configuration file to use",
action='store', type='string', dest='config_file')
parser.add_option('-... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"usage",
"=",
"\"%prog --help\"",
"parser",
"=",
"OptionParser",
"(",
"usage",
",",
"add_help_option",
"=",
"False",
")",
"parser",
".",
"add_option",
"(",
"'-c'",
",",
... | 37.219512 | 0.000638 |
def curve(self):
"""
Returns information about the curve used for an EC key
:raises:
ValueError - when the key is not an EC key
:return:
A two-element tuple, with the first element being a unicode string
of "implicit_ca", "specified" or "named". If t... | [
"def",
"curve",
"(",
"self",
")",
":",
"if",
"self",
".",
"algorithm",
"!=",
"'ec'",
":",
"raise",
"ValueError",
"(",
"unwrap",
"(",
"'''\n Only EC keys have a curve, this key is %s\n '''",
",",
"self",
".",
"algorithm",
".",
"upper",
"... | 31.4375 | 0.001929 |
async def get_stats(self, battletag: str, regions=(EUROPE, KOREA, AMERICAS, CHINA, JAPAN, ANY),
platform=None, _session=None, handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Returns the stats for the profiles on the specified regions and platform. The format for regions ... | [
"async",
"def",
"get_stats",
"(",
"self",
",",
"battletag",
":",
"str",
",",
"regions",
"=",
"(",
"EUROPE",
",",
"KOREA",
",",
"AMERICAS",
",",
"CHINA",
",",
"JAPAN",
",",
"ANY",
")",
",",
"platform",
"=",
"None",
",",
"_session",
"=",
"None",
",",
... | 77.352941 | 0.009016 |
def minimum_needs(self, input_layer):
"""Compute minimum needs given a layer and a column containing pop.
:param input_layer: Vector layer assumed to contain
population counts.
:type input_layer: QgsVectorLayer
:returns: A tuple containing True and the vector layer if
... | [
"def",
"minimum_needs",
"(",
"self",
",",
"input_layer",
")",
":",
"# Create a new layer for output layer",
"output_layer",
"=",
"self",
".",
"prepare_new_layer",
"(",
"input_layer",
")",
"# count each minimum needs for every features",
"for",
"needs",
"in",
"minimum_needs_... | 39.241379 | 0.001715 |
def authenticate_user(scope, user=[None], password=[None]):
"""
Like authenticate(), but logs in using the given user and password.
If a user and password are not given, the function uses the same
user and password that were used at the last login attempt; it is
an error if no such attempt was made ... | [
"def",
"authenticate_user",
"(",
"scope",
",",
"user",
"=",
"[",
"None",
"]",
",",
"password",
"=",
"[",
"None",
"]",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"user",
"=",
"user",
"[",
"0",
"]",
"if",
"user",
"is",
... | 32.6 | 0.00149 |
async def _call(cmd: List[str]) -> Tuple[str, str]:
"""
Runs the command in a subprocess and returns the captured stdout output.
:param cmd: a list of arguments to nmcli. Should not include nmcli itself.
:return: (stdout, stderr)
"""
to_exec = [quote(c) for c in ['nmcli'] + cmd]
cmd_str = '... | [
"async",
"def",
"_call",
"(",
"cmd",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"to_exec",
"=",
"[",
"quote",
"(",
"c",
")",
"for",
"c",
"in",
"[",
"'nmcli'",
"]",
"+",
"cmd",
"]",
"cmd_str",
"=",
"' '... | 46.347826 | 0.000919 |
def listurl_get(self, q, **kwargs):
'''taobao.taobaoke.listurl.get 淘宝客关键词搜索URL
淘宝客关键词搜索URL'''
request = TOPRequest('taobao.taobaoke.listurl.get')
request['q'] = q
for k, v in kwargs.iteritems():
if k not in ('nick', 'outer_code', 'pid') and v==None: continue
... | [
"def",
"listurl_get",
"(",
"self",
",",
"q",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.taobaoke.listurl.get'",
")",
"request",
"[",
"'q'",
"]",
"=",
"q",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
... | 43.454545 | 0.016393 |
def _generate_badges(self):
"""
Generate download badges. Append them to ``self._badges``.
"""
daycount = self._stats.downloads_per_day
day = self._generate_badge('Downloads', '%d/day' % daycount)
self._badges['per-day'] = day
weekcount = self._stats.downloads_per... | [
"def",
"_generate_badges",
"(",
"self",
")",
":",
"daycount",
"=",
"self",
".",
"_stats",
".",
"downloads_per_day",
"day",
"=",
"self",
".",
"_generate_badge",
"(",
"'Downloads'",
",",
"'%d/day'",
"%",
"daycount",
")",
"self",
".",
"_badges",
"[",
"'per-day'... | 42 | 0.002451 |
async def _send_text(self, request: Request, stack: Stack):
"""
Send text layers to the user. Each layer will go in its own bubble.
Also, Facebook limits messages to 320 chars, so if any message is
longer than that it will be split into as many messages as needed to
be accepted ... | [
"async",
"def",
"_send_text",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"layer",
"in",
"stack",
".",
"layers",
":",
"if",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"MultiText"... | 31.942857 | 0.001736 |
def read(self, n):
"""
Read n bytes from mapped view.
"""
out = ctypes.create_string_buffer(n)
ctypes.windll.kernel32.RtlMoveMemory(out, self.view + self.pos, n)
self.pos += n
return out.raw | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"out",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"n",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"RtlMoveMemory",
"(",
"out",
",",
"self",
".",
"view",
"+",
"self",
".",
"pos",
",",
"n... | 29.875 | 0.00813 |
def _get_path(share_name=None, directory_name=None, file_name=None):
'''
Creates the path to access a file resource.
share_name:
Name of share.
directory_name:
The path to the directory.
file_name:
Name of file.
'''
if share_name and directory_name and file_name:
... | [
"def",
"_get_path",
"(",
"share_name",
"=",
"None",
",",
"directory_name",
"=",
"None",
",",
"file_name",
"=",
"None",
")",
":",
"if",
"share_name",
"and",
"directory_name",
"and",
"file_name",
":",
"return",
"'/{0}/{1}/{2}'",
".",
"format",
"(",
"_str",
"("... | 27.964286 | 0.001235 |
def keywords(self, key, values):
"""Populate the ``keywords`` key.
Also populates the ``energy_ranges`` key through side effects.
"""
keywords = self.get('keywords', [])
energy_ranges = self.get('energy_ranges', [])
for value in force_list(values):
if value.get('a'):
schema... | [
"def",
"keywords",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"keywords",
"=",
"self",
".",
"get",
"(",
"'keywords'",
",",
"[",
"]",
")",
"energy_ranges",
"=",
"self",
".",
"get",
"(",
"'energy_ranges'",
",",
"[",
"]",
")",
"for",
"value",
"... | 32.25 | 0.001075 |
def _get_labels(self, element, locations, mode):
r"""
This is the actual label getter method, but it should not be called
directly. Use ``labels`` instead.
"""
# Parse inputs
locations = self._parse_indices(locations)
element = self._parse_element(element=element... | [
"def",
"_get_labels",
"(",
"self",
",",
"element",
",",
"locations",
",",
"mode",
")",
":",
"# Parse inputs",
"locations",
"=",
"self",
".",
"_parse_indices",
"(",
"locations",
")",
"element",
"=",
"self",
".",
"_parse_element",
"(",
"element",
"=",
"element... | 45.166667 | 0.001445 |
def note_on(self, channel, note, velocity):
"""Return bytes for a 'note_on' event."""
return self.midi_event(NOTE_ON, channel, note, velocity) | [
"def",
"note_on",
"(",
"self",
",",
"channel",
",",
"note",
",",
"velocity",
")",
":",
"return",
"self",
".",
"midi_event",
"(",
"NOTE_ON",
",",
"channel",
",",
"note",
",",
"velocity",
")"
] | 52 | 0.012658 |
def read_extended_header(self, groupby='field', force_type=''):
"""Read the extended header according to `extended_header_type`.
Currently, only the FEI extended header format is supported.
See `print_fei_ext_header_spec` or `this homepage`_ for the format
specification.
The ex... | [
"def",
"read_extended_header",
"(",
"self",
",",
"groupby",
"=",
"'field'",
",",
"force_type",
"=",
"''",
")",
":",
"ext_header_type",
"=",
"str",
"(",
"force_type",
")",
".",
"upper",
"(",
")",
"or",
"self",
".",
"extended_header_type",
"if",
"ext_header_ty... | 39.663717 | 0.000435 |
def circlescan(x0, y0, r1, r2):
"""Scan pixels in a circle pattern around a center point
:param x0: Center x-coordinate
:type x0: float
:param y0: Center y-coordinate
:type y0: float
:param r1: Initial radius
:type r1: float
:param r2: Final radius
:type r2: float
:returns: Coor... | [
"def",
"circlescan",
"(",
"x0",
",",
"y0",
",",
"r1",
",",
"r2",
")",
":",
"# Validate inputs",
"if",
"r1",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Initial radius must be non-negative\"",
")",
"if",
"r2",
"<",
"0",
":",
"raise",
"ValueError",
"(",
... | 32.733333 | 0.008304 |
def iobject_import(self,
id_and_rev_info,
elt_name,
obj_dict,
markings=None,
cybox_id=None):
"""
Derives InfoObjectType and import InfoObjectType
"""
iobject_type_ns = Non... | [
"def",
"iobject_import",
"(",
"self",
",",
"id_and_rev_info",
",",
"elt_name",
",",
"obj_dict",
",",
"markings",
"=",
"None",
",",
"cybox_id",
"=",
"None",
")",
":",
"iobject_type_ns",
"=",
"None",
"# Derive the namespace information",
"if",
"(",
"'@xsi:type'",
... | 58.030303 | 0.009499 |
def from_file(filename, section='matrix'):
"""
Generate a matrix from a .ini file. Configuration is expected to be in a ``[matrix]`` section.
"""
config = parse_config(open(filename), section=section)
return from_config(config) | [
"def",
"from_file",
"(",
"filename",
",",
"section",
"=",
"'matrix'",
")",
":",
"config",
"=",
"parse_config",
"(",
"open",
"(",
"filename",
")",
",",
"section",
"=",
"section",
")",
"return",
"from_config",
"(",
"config",
")"
] | 40.333333 | 0.008097 |
def log_end(path, log_file, sum_time):
"""
append END tag to a log file
"""
with open(path + log_file, "a") as log:
log.seek(2)
log.write("#" * 79 + "\n\n")
log.write("Time : " + time.strftime("%H:%M:%S") + "\n")
log.write("Total build time : {0}\n".format(sum_time))
... | [
"def",
"log_end",
"(",
"path",
",",
"log_file",
",",
"sum_time",
")",
":",
"with",
"open",
"(",
"path",
"+",
"log_file",
",",
"\"a\"",
")",
"as",
"log",
":",
"log",
".",
"seek",
"(",
"2",
")",
"log",
".",
"write",
"(",
"\"#\"",
"*",
"79",
"+",
... | 33.583333 | 0.002415 |
def satisfaction_rating_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#show-satisfaction-rating"
api_path = "/api/v2/satisfaction_ratings/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"satisfaction_rating_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/satisfaction_ratings/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
... | 59.4 | 0.009967 |
def start(self):
"""
create an ec2 reservation if one doesn't already exist and call
start_instance. Update instance attributes to the newly created instance
attributes
"""
if self.instance is None:
reservation = self.ec2_backend.add_instances(
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"instance",
"is",
"None",
":",
"reservation",
"=",
"self",
".",
"ec2_backend",
".",
"add_instances",
"(",
"image_id",
"=",
"self",
".",
"ami_id",
",",
"count",
"=",
"1",
",",
"user_data",
"=",
... | 42.090909 | 0.002111 |
def get_db_prep_save(self, value, connection=None):
"""
Returns field's value prepared for saving into a database.
"""
## convert to settings.TIME_ZONE
if value is not None:
if value.tzinfo is None:
value = default_tz.localize(value)
else:
... | [
"def",
"get_db_prep_save",
"(",
"self",
",",
"value",
",",
"connection",
"=",
"None",
")",
":",
"## convert to settings.TIME_ZONE",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
".",
"tzinfo",
"is",
"None",
":",
"value",
"=",
"default_tz",
".",
"... | 41.818182 | 0.008511 |
def get_revision():
"""
:returns: Revision number of this branch/checkout, if available. None if
no revision number can be determined.
"""
package_dir = os.path.dirname(__file__)
checkout_dir = os.path.normpath(os.path.join(package_dir, '..'))
path = os.path.join(checkout_dir, '.git')
... | [
"def",
"get_revision",
"(",
")",
":",
"package_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"checkout_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"'..'",
")",
")"... | 35.545455 | 0.002494 |
def exact_ratio(x):
"""Convert Real number x exactly to (numerator, denominator) pair.
x is expected to be an int, Fraction, Decimal or float.
"""
try:
try:
# int, Fraction
return x.numerator, x.denominator
except AttributeError:
# float
t... | [
"def",
"exact_ratio",
"(",
"x",
")",
":",
"try",
":",
"try",
":",
"# int, Fraction",
"return",
"x",
".",
"numerator",
",",
"x",
".",
"denominator",
"except",
"AttributeError",
":",
"# float",
"try",
":",
"return",
"x",
".",
"as_integer_ratio",
"(",
")",
... | 32.26087 | 0.001309 |
def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")):
"""Point to a position in source code.
source is the text we're pointing in.
position is a 2-tuple of (line_number, character_number) to point to.
fmt is a 4-tuple of formatting parameters, they are:
name default description... | [
"def",
"point_to_source",
"(",
"source",
",",
"position",
",",
"fmt",
"=",
"(",
"2",
",",
"True",
",",
"\"~~~~~\"",
",",
"\"^\"",
")",
")",
":",
"surrounding_lines",
",",
"show_line_numbers",
",",
"tail_body",
",",
"pointer_char",
"=",
"fmt",
"line_no",
",... | 35.76087 | 0.011243 |
def qlaplace_dd(d):
"""Creates a QTT representation of the Laplace operator"""
res = _matrix.matrix()
d0 = d[::-1]
D = len(d0)
I = _np.eye(2)
J = _np.array([[0, 1], [0, 0]])
cr = []
if D is 1:
for k in xrange(1, d0[0] + 1):
if k is 1:
cur_core = _np.ze... | [
"def",
"qlaplace_dd",
"(",
"d",
")",
":",
"res",
"=",
"_matrix",
".",
"matrix",
"(",
")",
"d0",
"=",
"d",
"[",
":",
":",
"-",
"1",
"]",
"D",
"=",
"len",
"(",
"d0",
")",
"I",
"=",
"_np",
".",
"eye",
"(",
"2",
")",
"J",
"=",
"_np",
".",
"... | 41.703704 | 0.000578 |
def start_service(name, argv = None):
"""
Start the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{stop_service}, L{pause_service}, L{resume_service}
@type name: str
@param name: Service unique name. You can get th... | [
"def",
"start_service",
"(",
"name",
",",
"argv",
"=",
"None",
")",
":",
"with",
"win32",
".",
"OpenSCManager",
"(",
"dwDesiredAccess",
"=",
"win32",
".",
"SC_MANAGER_CONNECT",
")",
"as",
"hSCManager",
":",
"with",
"win32",
".",
"OpenService",
"(",
"hSCManag... | 38.5 | 0.011407 |
def t_FRACTION(self, t):
r'(\d+)(\.\d+)'
t.endlexpos = t.lexpos + len(t.value)
return t | [
"def",
"t_FRACTION",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"endlexpos",
"=",
"t",
".",
"lexpos",
"+",
"len",
"(",
"t",
".",
"value",
")",
"return",
"t"
] | 27 | 0.018018 |
def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None):
""" Inserts a new rule that updates words with tag1 to tag2,
given constraints x and y, e.g., Context.append("TO < NN", "VB")
"""
if " < " in tag1 and not x and not y:
tag1, x = tag1.split(" < "); cmd="prevta... | [
"def",
"insert",
"(",
"self",
",",
"i",
",",
"tag1",
",",
"tag2",
",",
"cmd",
"=",
"\"prevtag\"",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"if",
"\" < \"",
"in",
"tag1",
"and",
"not",
"x",
"and",
"not",
"y",
":",
"tag1",
",",
"... | 53.888889 | 0.01217 |
def __warn_user_if_wd_maybe_unreadable(self, abs_remote_path):
"""
Check directories above the remote module and issue a warning if
they are not traversable by all users.
The reasoning behind this is mainly aimed at set-ups with a
centralized Hadoop cluster, accessed by all user... | [
"def",
"__warn_user_if_wd_maybe_unreadable",
"(",
"self",
",",
"abs_remote_path",
")",
":",
"host",
",",
"port",
",",
"path",
"=",
"hdfs",
".",
"path",
".",
"split",
"(",
"abs_remote_path",
")",
"if",
"host",
"==",
"''",
"and",
"port",
"==",
"0",
":",
"#... | 47.459459 | 0.001116 |
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 | 0.002193 |
def video_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
"""Compute loss numerator and denominator for one shard of output."""
del vocab_size # unused arg
logits = top_out
logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:])
targets = tf.reshape(targets, [-1] + common_laye... | [
"def",
"video_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weights_fn",
")",
":",
"del",
"vocab_size",
"# unused arg",
"logits",
"=",
"top_out",
"logits",
"=",
"tf",
".",
"reshape",
"(",
"logits",
",",
"[",
"-",
"1"... | 43.538462 | 0.013841 |
def update(self, item_id, attributes, silent=False, hook=True):
"""
Updates the item using the supplied attributes. If 'silent' is true, Podio will send
no notifications to subscribed users and not post updates to the stream.
Important: webhooks will still be called.
"""... | [
"def",
"update",
"(",
"self",
",",
"item_id",
",",
"attributes",
",",
"silent",
"=",
"False",
",",
"hook",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"attributes",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Must be of type dict'",
")... | 53.285714 | 0.009223 |
def createLrrBafPlot(raw_dir, problematic_samples, format, dpi, out_prefix):
"""Creates the LRR and BAF plot.
:param raw_dir: the directory containing the intensities.
:param problematic_samples: the file containing the problematic samples.
:param format: the format of the plot.
:param dpi: the DPI... | [
"def",
"createLrrBafPlot",
"(",
"raw_dir",
",",
"problematic_samples",
",",
"format",
",",
"dpi",
",",
"out_prefix",
")",
":",
"# First, we create an output directory",
"dir_name",
"=",
"out_prefix",
"+",
"\".LRR_BAF\"",
"if",
"not",
"os",
".",
"path",
".",
"isdir... | 36.588235 | 0.000783 |
def expand_variables(template_str, value_map, transformer=None):
"""
Expand a template string like "blah blah $FOO blah" using given value mapping.
"""
if template_str is None:
return None
else:
if transformer is None:
transformer = lambda v: v
try:
# Don't bother iterating items for P... | [
"def",
"expand_variables",
"(",
"template_str",
",",
"value_map",
",",
"transformer",
"=",
"None",
")",
":",
"if",
"template_str",
"is",
"None",
":",
"return",
"None",
"else",
":",
"if",
"transformer",
"is",
"None",
":",
"transformer",
"=",
"lambda",
"v",
... | 40.333333 | 0.019386 |
def _wrap_measure(individual_state_measure_process, state_measure, loaded_processes):
"""
Creates a function on a state_collection, which creates analysis_collections for each state in the collection.
Optionally sorts the collection if the state_measure has a sort_by parameter (see funtool.lib.general... | [
"def",
"_wrap_measure",
"(",
"individual_state_measure_process",
",",
"state_measure",
",",
"loaded_processes",
")",
":",
"def",
"wrapped_measure",
"(",
"state_collection",
",",
"overriding_parameters",
"=",
"None",
",",
"loggers",
"=",
"None",
")",
":",
"if",
"logg... | 68.62069 | 0.019326 |
def bsseval(inargs=None):
"""
Generic cli app for bsseval results. Expects two folder with
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'reference_dir',
type=str
)
parser.add_argument(
'estimates_dir',
type=str
)
parser.add_argument('... | [
"def",
"bsseval",
"(",
"inargs",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'reference_dir'",
",",
"type",
"=",
"str",
")",
"parser",
".",
"add_argument",
"(",
"'estimates_dir'",
... | 20.87037 | 0.000847 |
def _process_interval(self, mod, interval):
'''
Process beacons with intervals
Return True if a beacon should be run on this loop
'''
log.trace('Processing interval %s for beacon mod %s', interval, mod)
loop_interval = self.opts['loop_interval']
if mod in self.int... | [
"def",
"_process_interval",
"(",
"self",
",",
"mod",
",",
"interval",
")",
":",
"log",
".",
"trace",
"(",
"'Processing interval %s for beacon mod %s'",
",",
"interval",
",",
"mod",
")",
"loop_interval",
"=",
"self",
".",
"opts",
"[",
"'loop_interval'",
"]",
"i... | 39.35 | 0.002481 |
def _get_profile(self, profile_id):
'''dict: Return the profile with the received ID as a dict (None if it
doesn't exist).'''
profile_metadata = self._registry.get(profile_id)
if not profile_metadata:
return
path = self._get_absolute_path(profile_metadata.get('schema... | [
"def",
"_get_profile",
"(",
"self",
",",
"profile_id",
")",
":",
"profile_metadata",
"=",
"self",
".",
"_registry",
".",
"get",
"(",
"profile_id",
")",
"if",
"not",
"profile_metadata",
":",
"return",
"path",
"=",
"self",
".",
"_get_absolute_path",
"(",
"prof... | 37 | 0.002026 |
def fit_model(ts, sc=None):
"""
Fits an AR(1) + GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a AR+GARCH model as a Numpy array
Returns an ARGARCH model
"""
assert sc != None, "Missing SparkContext"
... | [
"def",
"fit_model",
"(",
"ts",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing SparkContext\"",
"jvm",
"=",
"sc",
".",
"_jvm",
"jmodel",
"=",
"jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"models",
".",
"ARG... | 29.0625 | 0.014583 |
def all(self, data={}, **kwargs):
""""
Fetch all Settlement entities
Returns:
Dictionary of Settlement data
"""
return super(Settlement, self).all(data, **kwargs) | [
"def",
"all",
"(",
"self",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Settlement",
",",
"self",
")",
".",
"all",
"(",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 26 | 0.009302 |
def get_session(session, baseurl, config):
"""
Try to get a valid session for this baseurl, using login found in config.
This function invoques Firefox if necessary
"""
# Read proxy for firefox
if environ.get("HTTP_PROXY"):
myProxy = environ.get("HTTP_PROXY")
proxy = Proxy({
... | [
"def",
"get_session",
"(",
"session",
",",
"baseurl",
",",
"config",
")",
":",
"# Read proxy for firefox",
"if",
"environ",
".",
"get",
"(",
"\"HTTP_PROXY\"",
")",
":",
"myProxy",
"=",
"environ",
".",
"get",
"(",
"\"HTTP_PROXY\"",
")",
"proxy",
"=",
"Proxy",... | 33.119048 | 0.001397 |
def create_host(factories, value):
"""Use the factories to create a host object.
:param factories: a list of functions that return host objects
(Hostname, IPv4Address, IPv6Address) for valid arguments
:param value: a value to be passed as argument to factories
:returns: an object representing the v... | [
"def",
"create_host",
"(",
"factories",
",",
"value",
")",
":",
"data",
"=",
"[",
"value",
"]",
"for",
"func",
"in",
"factories",
":",
"try",
":",
"return",
"func",
"(",
"value",
")",
"except",
"InvalidHostError",
"as",
"ex",
":",
"data",
".",
"append"... | 33.592593 | 0.001072 |
def scientific_notation_elements(self, value, locale):
""" Returns normalized scientific notation components of a value."""
# Normalize value to only have one lead digit.
exp = value.adjusted()
value = value * get_decimal_quantum(exp)
assert value.adjusted() == 0
# Shift... | [
"def",
"scientific_notation_elements",
"(",
"self",
",",
"value",
",",
"locale",
")",
":",
"# Normalize value to only have one lead digit.",
"exp",
"=",
"value",
".",
"adjusted",
"(",
")",
"value",
"=",
"value",
"*",
"get_decimal_quantum",
"(",
"exp",
")",
"assert... | 38.6 | 0.002022 |
def service_factory(app, host, port,
report_message='service factory port {port}',
provider_cls=HTTPServiceProvider):
"""Create service, start server.
:param app: application to instantiate a service
:param host: interface to bound provider
:param port: port to b... | [
"def",
"service_factory",
"(",
"app",
",",
"host",
",",
"port",
",",
"report_message",
"=",
"'service factory port {port}'",
",",
"provider_cls",
"=",
"HTTPServiceProvider",
")",
":",
"service",
"=",
"Service",
"(",
"app",
")",
"server",
"=",
"provider_cls",
"("... | 34.875 | 0.001745 |
def main(lang="en", output_dir=None, n_iter=25):
"""Create a new model, set up the pipeline and train the tagger. In order to
train the tagger with a custom tag map, we're creating a new Language
instance with a custom vocab.
"""
nlp = spacy.blank(lang)
# add the tagger to the pipeline
# nlp... | [
"def",
"main",
"(",
"lang",
"=",
"\"en\"",
",",
"output_dir",
"=",
"None",
",",
"n_iter",
"=",
"25",
")",
":",
"nlp",
"=",
"spacy",
".",
"blank",
"(",
"lang",
")",
"# add the tagger to the pipeline",
"# nlp.create_pipe works for built-ins that are registered with sp... | 36.930233 | 0.001227 |
def _error_dm(self, m, dm, s):
"""Error function.
Once self.goal has been defined, compute the error
of input using the generalized forward model.
"""
pred = self.fmodel.predict_given_context(np.hstack((m, dm)), s, range(len(s)))
err_v = pred - self.goal
error = ... | [
"def",
"_error_dm",
"(",
"self",
",",
"m",
",",
"dm",
",",
"s",
")",
":",
"pred",
"=",
"self",
".",
"fmodel",
".",
"predict_given_context",
"(",
"np",
".",
"hstack",
"(",
"(",
"m",
",",
"dm",
")",
")",
",",
"s",
",",
"range",
"(",
"len",
"(",
... | 39.555556 | 0.010989 |
def _make_string_formatter(f, offset=None):
""" A closure-izer for string arguments that include a format and possibly an offset. """
format = f
delta = offset
return lambda v: time.strftime(format, (_date(v, delta)).timetuple()) | [
"def",
"_make_string_formatter",
"(",
"f",
",",
"offset",
"=",
"None",
")",
":",
"format",
"=",
"f",
"delta",
"=",
"offset",
"return",
"lambda",
"v",
":",
"time",
".",
"strftime",
"(",
"format",
",",
"(",
"_date",
"(",
"v",
",",
"delta",
")",
")",
... | 46.6 | 0.025316 |
def tprint( text, layers, markup_settings = None ):
''' Formats given text, adding a special ( ANSI-terminal compatible ) markup
to the annotations of given layers, and prints the formatted text to the
screen.
*) layers is a list containing names of the layers to be preformatted in
... | [
"def",
"tprint",
"(",
"text",
",",
"layers",
",",
"markup_settings",
"=",
"None",
")",
":",
"if",
"markup_settings",
"and",
"len",
"(",
"layers",
")",
"!=",
"len",
"(",
"markup_settings",
")",
":",
"raise",
"Exception",
"(",
"' Input arguments layers and marku... | 55.945946 | 0.013295 |
def sortmerna_ref_cluster(seq_path=None,
sortmerna_db=None,
refseqs_fp=None,
result_path=None,
tabular=False,
max_e_value=1,
similarity=0.97,
... | [
"def",
"sortmerna_ref_cluster",
"(",
"seq_path",
"=",
"None",
",",
"sortmerna_db",
"=",
"None",
",",
"refseqs_fp",
"=",
"None",
",",
"result_path",
"=",
"None",
",",
"tabular",
"=",
"False",
",",
"max_e_value",
"=",
"1",
",",
"similarity",
"=",
"0.97",
","... | 32.967213 | 0.000241 |
def wire(self):
"""
Returns (Register, int) tuple where the int is the index of
the wire else None
"""
if self.data_dict['type'] not in ['in', 'out']:
raise QiskitError('The node %s is not an input/output node' % str(self))
return self.data_dict.get('wire') | [
"def",
"wire",
"(",
"self",
")",
":",
"if",
"self",
".",
"data_dict",
"[",
"'type'",
"]",
"not",
"in",
"[",
"'in'",
",",
"'out'",
"]",
":",
"raise",
"QiskitError",
"(",
"'The node %s is not an input/output node'",
"%",
"str",
"(",
"self",
")",
")",
"retu... | 38.75 | 0.009464 |
def query_segdb(cls, flags, *args, **kwargs):
"""Query the inital LIGO segment database for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
... | [
"def",
"query_segdb",
"(",
"cls",
",",
"flags",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"query_segdb is deprecated and will be removed in a \"",
"\"future release\"",
",",
"DeprecationWarning",
")",
"# parse segments",
"q... | 40.522727 | 0.000547 |
def p_const_vector_elem_list_list(p):
""" const_number_list : const_number_list COMMA expr
"""
if p[1] is None or p[3] is None:
return
if not is_static(p[3]):
if isinstance(p[3], symbols.UNARY):
tmp = make_constexpr(p.lineno(2), p[3])
else:
api.errmsg.syn... | [
"def",
"p_const_vector_elem_list_list",
"(",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"is",
"None",
"or",
"p",
"[",
"3",
"]",
"is",
"None",
":",
"return",
"if",
"not",
"is_static",
"(",
"p",
"[",
"3",
"]",
")",
":",
"if",
"isinstance",
"(",
"p",
... | 25.052632 | 0.002024 |
def _is_duplicate_file(db_session, filename, hashes):
"""
Check to see if file already exists, and if it's content matches.
A file is considered to exist if its filename *or* blake2 digest are
present in a file row in the database.
Returns:
- True: This file is a duplicate and all further proce... | [
"def",
"_is_duplicate_file",
"(",
"db_session",
",",
"filename",
",",
"hashes",
")",
":",
"file_",
"=",
"(",
"db_session",
".",
"query",
"(",
"File",
")",
".",
"filter",
"(",
"(",
"File",
".",
"filename",
"==",
"filename",
")",
"|",
"(",
"File",
".",
... | 29.733333 | 0.001086 |
def rdann(record_name, extension, sampfrom=0, sampto=None, shift_samps=False,
pb_dir=None, return_label_elements=['symbol'],
summarize_labels=False):
"""
Read a WFDB annotation file record_name.extension and return an
Annotation object.
Parameters
----------
record_name : st... | [
"def",
"rdann",
"(",
"record_name",
",",
"extension",
",",
"sampfrom",
"=",
"0",
",",
"sampto",
"=",
"None",
",",
"shift_samps",
"=",
"False",
",",
"pb_dir",
"=",
"None",
",",
"return_label_elements",
"=",
"[",
"'symbol'",
"]",
",",
"summarize_labels",
"="... | 39.883333 | 0.000612 |
def cdx_resolve_revisits(cdx_iter):
"""
resolve revisits.
this filter adds three fields to CDX: ``orig.length``, ``orig.offset``,
and ``orig.filename``. for revisit records, these fields have corresponding
field values in previous non-revisit (original) CDX record.
They are all ``"-"`` for non-... | [
"def",
"cdx_resolve_revisits",
"(",
"cdx_iter",
")",
":",
"originals",
"=",
"{",
"}",
"for",
"cdx",
"in",
"cdx_iter",
":",
"is_revisit",
"=",
"cdx",
".",
"is_revisit",
"(",
")",
"digest",
"=",
"cdx",
".",
"get",
"(",
"DIGEST",
")",
"original_cdx",
"=",
... | 31.25 | 0.002327 |
def selection_can_redo(self, name="default"):
"""Can selection name be redone?"""
return (self.selection_history_indices[name] + 1) < len(self.selection_histories[name]) | [
"def",
"selection_can_redo",
"(",
"self",
",",
"name",
"=",
"\"default\"",
")",
":",
"return",
"(",
"self",
".",
"selection_history_indices",
"[",
"name",
"]",
"+",
"1",
")",
"<",
"len",
"(",
"self",
".",
"selection_histories",
"[",
"name",
"]",
")"
] | 61 | 0.016216 |
def update_device_list(self, sessions):
""" Update device list. """
if sessions is None:
_LOGGER.error('Error updating Emby devices.')
return
new_devices = []
active_devices = []
dev_update = False
for device in sessions:
dev_name = '{... | [
"def",
"update_device_list",
"(",
"self",
",",
"sessions",
")",
":",
"if",
"sessions",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"'Error updating Emby devices.'",
")",
"return",
"new_devices",
"=",
"[",
"]",
"active_devices",
"=",
"[",
"]",
"dev_update"... | 42.175439 | 0.000813 |
def cal_gpa(grades):
"""
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考
:param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组
:return: 包含了课程平均绩点和 gpa 的元组
"""
# 课程总数
courses_sum = len(grades)
# 课程绩点和
points_sum = 0
# 学分和
credit_sum = 0
# 课程学分 x 课程绩点之和
gpa_... | [
"def",
"cal_gpa",
"(",
"grades",
")",
":",
"# 课程总数",
"courses_sum",
"=",
"len",
"(",
"grades",
")",
"# 课程绩点和",
"points_sum",
"=",
"0",
"# 学分和",
"credit_sum",
"=",
"0",
"# 课程学分 x 课程绩点之和",
"gpa_points_sum",
"=",
"0",
"for",
"grade",
"in",
"grades",
":",
"poi... | 26.2 | 0.001473 |
def git_url_ssh_to_https(url):
"""Convert a git url
url will look like
https://github.com/ARMmbed/mbed-cloud-sdk-python.git
or
git@github.com:ARMmbed/mbed-cloud-sdk-python.git
we want:
https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git
"""
path = url.split(... | [
"def",
"git_url_ssh_to_https",
"(",
"url",
")",
":",
"path",
"=",
"url",
".",
"split",
"(",
"'github.com'",
",",
"1",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
"new",
"=",
"'https://{GITHUB_TOKEN}@github.com/%s'",
"%",
"path",
"pr... | 35.714286 | 0.001949 |
def get_range(self,
base_key: Key,
start_time: datetime,
end_time: datetime = None,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the store based on the given time range or count.
:param base_k... | [
"def",
"get_range",
"(",
"self",
",",
"base_key",
":",
"Key",
",",
"start_time",
":",
"datetime",
",",
"end_time",
":",
"datetime",
"=",
"None",
",",
"count",
":",
"int",
"=",
"0",
")",
"->",
"List",
"[",
"Tuple",
"[",
"Key",
",",
"Any",
"]",
"]",
... | 48.322581 | 0.008508 |
def start_scan(self, timeout_sec=TIMEOUT_SEC):
"""Start scanning for BLE devices."""
get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)
self._is_scanning = True | [
"def",
"start_scan",
"(",
"self",
",",
"timeout_sec",
"=",
"TIMEOUT_SEC",
")",
":",
"get_provider",
"(",
")",
".",
"_central_manager",
".",
"scanForPeripheralsWithServices_options_",
"(",
"None",
",",
"None",
")",
"self",
".",
"_is_scanning",
"=",
"True"
] | 53.5 | 0.013825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.