text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def main( gpu:Param("GPU to run on", str)=None ):
"""Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch"""
path = Path('/mnt/fe2_disk/')
tot_epochs,size,bs,lr = 60,224,256,3e-1
dirname = 'imagenet'
gpu = setup_distrib(gpu)
if gpu is None: bs *= torch.cud... | [
"def",
"main",
"(",
"gpu",
":",
"Param",
"(",
"\"GPU to run on\"",
",",
"str",
")",
"=",
"None",
")",
":",
"path",
"=",
"Path",
"(",
"'/mnt/fe2_disk/'",
")",
"tot_epochs",
",",
"size",
",",
"bs",
",",
"lr",
"=",
"60",
",",
"224",
",",
"256",
",",
... | 39.230769 | 0.018495 |
def optimize(model,cand,obj):
"""optimize: function for solving the model, updating candidate solutions' list
Parameters:
- model: Gurobi model object
- cand: list of pairs of objective functions (for appending more solutions)
- obj: name of a model's variable to setup as objective
R... | [
"def",
"optimize",
"(",
"model",
",",
"cand",
",",
"obj",
")",
":",
"# model.Params.OutputFlag = 0 # silent mode",
"model",
".",
"setObjective",
"(",
"obj",
",",
"\"minimize\"",
")",
"model",
".",
"optimize",
"(",
")",
"x",
",",
"y",
",",
"C",
",",
"U",
... | 39.130435 | 0.019523 |
def cygpath(x):
"""
This will return the path of input arg for windows
:return: the path in windows
"""
command = ['cygpath', '-wp', x]
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output, _ = p.communicate()
lines = output.split("\n")
return lines[0] | [
"def",
"cygpath",
"(",
"x",
")",
":",
"command",
"=",
"[",
"'cygpath'",
",",
"'-wp'",
",",
"x",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"output",
",",
"_",
"=",
"p",
".",
"com... | 26.9 | 0.02518 |
def _byteify(data):
"""Convert unicode to bytes"""
# Unicode
if isinstance(data, six.text_type):
return data.encode("utf-8")
# Members of lists
if isinstance(data, list):
return [_byteify(item) for item in data]
# Members of dicts
if isinstance(data, dict):
return ... | [
"def",
"_byteify",
"(",
"data",
")",
":",
"# Unicode",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"return",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
"# Members of lists",
"if",
"isinstance",
"(",
"data",
",",
"list",
")... | 23.684211 | 0.002137 |
def extract_pos(positions, cash):
"""
Extract position values from backtest object as returned by
get_backtest() on the Quantopian research platform.
Parameters
----------
positions : pd.DataFrame
timeseries containing one row per symbol (and potentially
duplicate datetime indic... | [
"def",
"extract_pos",
"(",
"positions",
",",
"cash",
")",
":",
"positions",
"=",
"positions",
".",
"copy",
"(",
")",
"positions",
"[",
"'values'",
"]",
"=",
"positions",
".",
"amount",
"*",
"positions",
".",
"last_sale_price",
"cash",
".",
"name",
"=",
"... | 30.380952 | 0.000759 |
def load(filename):
"""Retrieve a pickled object
Parameter
---------
filename : path
Return
------
object
Unpickled object
"""
filename = os.path.normcase(filename)
try:
with open(filename, 'rb') as f:
u = pickle.Unpickler(f)
return u.loa... | [
"def",
"load",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"filename",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"u",
"=",
"pickle",
".",
"Unpickler",
"(",
"f",
")... | 21.052632 | 0.002392 |
def create_actor_polygon(pts, color, **kwargs):
""" Creates a VTK actor for rendering polygons.
:param pts: points
:type pts: vtkFloatArray
:param color: actor color
:type color: list
:return: a VTK actor
:rtype: vtkActor
"""
# Keyword arguments
array_name = kwargs.get('name', "... | [
"def",
"create_actor_polygon",
"(",
"pts",
",",
"color",
",",
"*",
"*",
"kwargs",
")",
":",
"# Keyword arguments",
"array_name",
"=",
"kwargs",
".",
"get",
"(",
"'name'",
",",
"\"\"",
")",
"array_index",
"=",
"kwargs",
".",
"get",
"(",
"'index'",
",",
"0... | 26.673469 | 0.000738 |
def hexdump (bytes, addr=None, preamble=None, printfunc=None, stepsize=16):
"""hexdump(bytes[, addr[, preamble[, printfunc[, stepsize=16]]]])
Outputs bytes in hexdump format lines similar to the following (here
preamble='Bank1', stepsize=8, and len(bytes) == 15)::
Bank1: 0xFD020000: 7f45 4c46 0102 0100 ... | [
"def",
"hexdump",
"(",
"bytes",
",",
"addr",
"=",
"None",
",",
"preamble",
"=",
"None",
",",
"printfunc",
"=",
"None",
",",
"stepsize",
"=",
"16",
")",
":",
"if",
"preamble",
"is",
"None",
":",
"preamble",
"=",
"\"\"",
"bytes",
"=",
"bytearray",
"(",... | 31.457143 | 0.011454 |
def topickle(table, source=None, protocol=-1, write_header=True):
"""
Write the table to a pickle file. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> etl.topickle(table1, 'e... | [
"def",
"topickle",
"(",
"table",
",",
"source",
"=",
"None",
",",
"protocol",
"=",
"-",
"1",
",",
"write_header",
"=",
"True",
")",
":",
"_writepickle",
"(",
"table",
",",
"source",
"=",
"source",
",",
"mode",
"=",
"'wb'",
",",
"protocol",
"=",
"prot... | 28.909091 | 0.002028 |
def complete_features(db):
"""
iterator returning features which are complete (have a 'gene_id' and a
'transcript_id')
"""
for feature in db.all_features():
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id', [None])[0]
... | [
"def",
"complete_features",
"(",
"db",
")",
":",
"for",
"feature",
"in",
"db",
".",
"all_features",
"(",
")",
":",
"gene_id",
"=",
"feature",
".",
"attributes",
".",
"get",
"(",
"'gene_id'",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"transcript_id",
... | 40.9 | 0.002392 |
def handle_http(handler: Resource, args: Tuple, kwargs: Dict, logic: Callable):
"""Handle a Flask HTTP request
:param handler: flask_restful.Resource: An instance of a Flask Restful
resource class.
:param tuple args: Any positional arguments passed to the wrapper method.
:param dict kwargs: Any... | [
"def",
"handle_http",
"(",
"handler",
":",
"Resource",
",",
"args",
":",
"Tuple",
",",
"kwargs",
":",
"Dict",
",",
"logic",
":",
"Callable",
")",
":",
"try",
":",
"# We are checking mimetype here instead of content_type because",
"# mimetype is just the content-type, wh... | 46.473333 | 0.000702 |
def Sato_Riedel(T, M, Tb, Tc):
r'''Calculate the thermal conductivity of a liquid as a function of
temperature using the CSP method of Sato-Riedel [1]_, [2]_, published in
Reid [3]_. Requires temperature, molecular weight, and boiling and critical
temperatures.
.. math::
k = \frac{1.1053}{\... | [
"def",
"Sato_Riedel",
"(",
"T",
",",
"M",
",",
"Tb",
",",
"Tc",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"Tbr",
"=",
"Tb",
"/",
"Tc",
"return",
"1.1053",
"*",
"(",
"3.",
"+",
"20.",
"*",
"(",
"1",
"-",
"Tr",
")",
"**",
"(",
"2",
"/",
"3.",
... | 28.711111 | 0.002246 |
def pipe(*args):
"""
Takes as parameters several dicts, each with the same
parameters passed to popen.
Runs the various processes in a pipeline, connecting
the stdout of every process except the last with the
stdin of the next process.
Adapted from http://www.enricozini.org/2009/debian/pyt... | [
"def",
"pipe",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"pipe needs at least 2 processes\"",
")",
"# Set stdout=PIPE in every subprocess except the last",
"for",
"i",
"in",
"args",
"[",
":",
"-",
"... | 31.275862 | 0.00107 |
def remove_namespaces(self, rpc_reply):
"""remove xmlns attributes from rpc reply"""
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=True)
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser)
self.__transform = etree.XSLT(self... | [
"def",
"remove_namespaces",
"(",
"self",
",",
"rpc_reply",
")",
":",
"self",
".",
"__xslt",
"=",
"self",
".",
"__transform_reply",
"self",
".",
"__parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"self",
".",
"__xslt_doc",... | 56.625 | 0.008696 |
def verifyUniqueWcsname(fname,wcsname):
"""
Report whether or not the specified WCSNAME already exists in the file
"""
uniq = True
numsci,extname = count_sci_extensions(fname)
wnames = altwcs.wcsnames(fname,ext=(extname,1))
if wcsname in wnames.values():
uniq = False
return uni... | [
"def",
"verifyUniqueWcsname",
"(",
"fname",
",",
"wcsname",
")",
":",
"uniq",
"=",
"True",
"numsci",
",",
"extname",
"=",
"count_sci_extensions",
"(",
"fname",
")",
"wnames",
"=",
"altwcs",
".",
"wcsnames",
"(",
"fname",
",",
"ext",
"=",
"(",
"extname",
... | 25.833333 | 0.015576 |
def build_response(self, request, response, from_cache=False):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
if not from_cache and request.method == 'GET':
# apply a... | [
"def",
"build_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"from_cache",
"=",
"False",
")",
":",
"if",
"not",
"from_cache",
"and",
"request",
".",
"method",
"==",
"'GET'",
":",
"# apply any expiration heuristics",
"if",
"response",
".",
"statu... | 38.34375 | 0.000795 |
def is_bool_matrix(l):
r"""Checks if l is a 2D numpy array of bools
"""
if isinstance(l, np.ndarray):
if l.ndim == 2 and (l.dtype == bool):
return True
return False | [
"def",
"is_bool_matrix",
"(",
"l",
")",
":",
"if",
"isinstance",
"(",
"l",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"l",
".",
"ndim",
"==",
"2",
"and",
"(",
"l",
".",
"dtype",
"==",
"bool",
")",
":",
"return",
"True",
"return",
"False"
] | 24.25 | 0.00995 |
async def main_loop(loop, password, user, ip): # pylint: disable=invalid-name
"""Main loop."""
async with aiohttp.ClientSession(loop=loop) as session:
VAR['sma'] = pysma.SMA(session, ip, password=password, group=user)
await VAR['sma'].new_session()
if VAR['sma'].sma_sid is None:
... | [
"async",
"def",
"main_loop",
"(",
"loop",
",",
"password",
",",
"user",
",",
"ip",
")",
":",
"# pylint: disable=invalid-name",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
"loop",
"=",
"loop",
")",
"as",
"session",
":",
"VAR",
"[",
"'sma'",
"]",
... | 32.347826 | 0.001305 |
def table(self, snrthresh=5.5):
"""Represent this `QPlane` as an `EventTable`
Parameters
----------
snrthresh : `float`, optional
lower inclusive threshold on individual tile SNR to keep in the
table, default: 5.5
Returns
-------
out : `~... | [
"def",
"table",
"(",
"self",
",",
"snrthresh",
"=",
"5.5",
")",
":",
"from",
".",
".",
"table",
"import",
"EventTable",
"# get plane properties",
"freqs",
"=",
"self",
".",
"plane",
".",
"frequencies",
"bws",
"=",
"2",
"*",
"(",
"freqs",
"-",
"self",
"... | 37.75 | 0.001291 |
def delete(self, features, make_backup=True, **kwargs):
"""
Delete features from database.
features : str, iterable, FeatureDB instance
If FeatureDB, all features will be used. If string, assume it's the
ID of the feature to remove. Otherwise, assume it's an iterable of
... | [
"def",
"delete",
"(",
"self",
",",
"features",
",",
"make_backup",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"make_backup",
":",
"if",
"isinstance",
"(",
"self",
".",
"dbfn",
",",
"six",
".",
"string_types",
")",
":",
"shutil",
".",
"copy... | 34.8 | 0.001242 |
def QA_util_time_gap(time, gap, methods, type_):
'分钟线回测的时候的gap'
min_len = int(240 / int(str(type_).split('min')[0]))
day_gap = math.ceil(gap / min_len)
if methods in ['>', 'gt']:
data = pd.concat(
[
pd.DataFrame(QA_util_make_min_index(day,
... | [
"def",
"QA_util_time_gap",
"(",
"time",
",",
"gap",
",",
"methods",
",",
"type_",
")",
":",
"min_len",
"=",
"int",
"(",
"240",
"/",
"int",
"(",
"str",
"(",
"type_",
")",
".",
"split",
"(",
"'min'",
")",
"[",
"0",
"]",
")",
")",
"day_gap",
"=",
... | 37.648936 | 0.000275 |
def get(self):
""" Retrieve options set by user."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes} | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"options",
".",
"items",
"(",
")",
")",
"if",
"k",
"in",
"self",
".",
"_allowed_axes",
"}"
] | 47.666667 | 0.034483 |
def recognise(self, string, line_num):
"""
Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string.
"""
symbols = []
unknown = []
for char in string:
if char == SPACE:
continue
try:
name = u... | [
"def",
"recognise",
"(",
"self",
",",
"string",
",",
"line_num",
")",
":",
"symbols",
"=",
"[",
"]",
"unknown",
"=",
"[",
"]",
"for",
"char",
"in",
"string",
":",
"if",
"char",
"==",
"SPACE",
":",
"continue",
"try",
":",
"name",
"=",
"unicodedata",
... | 24.857143 | 0.034578 |
def remove_attr(self, attr_name):
""" Remove cookie attribute. Cookie attribute couldn't be removed if cookie is in read-only mode
(RuntimeError exception is raised).
:param attr_name: name of attribute to remove
:return: None
"""
if self.__ro_flag:
raise RuntimeError('Read-only cookie changing attempt'... | [
"def",
"remove_attr",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"self",
".",
"__ro_flag",
":",
"raise",
"RuntimeError",
"(",
"'Read-only cookie changing attempt'",
")",
"name",
"=",
"self",
".",
"__attr_name",
"(",
"attr_name",
")",
"if",
"name",
"in",
... | 34.333333 | 0.030733 |
def setupQuery(self, query, op, editor):
"""
Sets up the query for this editor.
"""
if editor is not None:
value = editor.currentRecord()
if value is None:
return False
return super(ForeignKeyPlugin, self).setupQuery(query... | [
"def",
"setupQuery",
"(",
"self",
",",
"query",
",",
"op",
",",
"editor",
")",
":",
"if",
"editor",
"is",
"not",
"None",
":",
"value",
"=",
"editor",
".",
"currentRecord",
"(",
")",
"if",
"value",
"is",
"None",
":",
"return",
"False",
"return",
"supe... | 32.4 | 0.009009 |
def draw_nodes(self):
"""
Renders nodes to the figure.
"""
node_r = self.nodeprops["radius"]
lw = self.nodeprops["linewidth"]
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.n... | [
"def",
"draw_nodes",
"(",
"self",
")",
":",
"node_r",
"=",
"self",
".",
"nodeprops",
"[",
"\"radius\"",
"]",
"lw",
"=",
"self",
".",
"nodeprops",
"[",
"\"linewidth\"",
"]",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"self",
".",
"nodes",
")",
"... | 36.381579 | 0.000704 |
def main():
"""Create an organization, print out its attributes and delete it."""
server_config = ServerConfig(
auth=('admin', 'changeme'), # Use these credentials…
url='https://sat1.example.com', # …to talk to this server.
)
org = Organization(server_config, name='junk org').creat... | [
"def",
"main",
"(",
")",
":",
"server_config",
"=",
"ServerConfig",
"(",
"auth",
"=",
"(",
"'admin'",
",",
"'changeme'",
")",
",",
"# Use these credentials…",
"url",
"=",
"'https://sat1.example.com'",
",",
"# …to talk to this server.",
")",
"org",
"=",
"Organizati... | 43.666667 | 0.002494 |
def write_to_file(self, file_path='', date=str(datetime.date.today()),
organization='N/A', members=0, teams=0):
"""
Writes the current organization information to file (csv).
"""
self.checkDir(file_path)
with open(file_path, 'w+') as output:
output.write('date... | [
"def",
"write_to_file",
"(",
"self",
",",
"file_path",
"=",
"''",
",",
"date",
"=",
"str",
"(",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
",",
"organization",
"=",
"'N/A'",
",",
"members",
"=",
"0",
",",
"teams",
"=",
"0",
")",
":",
"... | 58.564103 | 0.009044 |
def default_stream_factory(
total_content_length, filename, content_type, content_length=None
):
"""The stream factory that is used per default."""
max_size = 1024 * 500
if SpooledTemporaryFile is not None:
return SpooledTemporaryFile(max_size=max_size, mode="wb+")
if total_content_length is... | [
"def",
"default_stream_factory",
"(",
"total_content_length",
",",
"filename",
",",
"content_type",
",",
"content_length",
"=",
"None",
")",
":",
"max_size",
"=",
"1024",
"*",
"500",
"if",
"SpooledTemporaryFile",
"is",
"not",
"None",
":",
"return",
"SpooledTempora... | 40.9 | 0.002392 |
def walknset_vars(self, task_class=None, *args, **kwargs):
"""
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:
... | [
"def",
"walknset_vars",
"(",
"self",
",",
"task_class",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"change_task",
"(",
"task",
")",
":",
"if",
"task_class",
"is",
"not",
"None",
"and",
"task",
".",
"__class__",
"is",
"no... | 33.714286 | 0.009269 |
def get_linearoperator(shape, A, timer=None):
"""Enhances aslinearoperator if A is None."""
ret = None
import scipy.sparse.linalg as scipylinalg
if isinstance(A, LinearOperator):
ret = A
elif A is None:
ret = IdentityLinearOperator(shape)
elif isinstance(A, numpy.ndarray) or issp... | [
"def",
"get_linearoperator",
"(",
"shape",
",",
"A",
",",
"timer",
"=",
"None",
")",
":",
"ret",
"=",
"None",
"import",
"scipy",
".",
"sparse",
".",
"linalg",
"as",
"scipylinalg",
"if",
"isinstance",
"(",
"A",
",",
"LinearOperator",
")",
":",
"ret",
"=... | 35.833333 | 0.000906 |
def assignGroup(self, action):
"""
Assigns the group for the given action to the current view.
:param action | <QAction>
"""
grp = unwrapVariant(action.data())
view = self._currentPanel.currentView()
view.setViewingGroup(grp) | [
"def",
"assignGroup",
"(",
"self",
",",
"action",
")",
":",
"grp",
"=",
"unwrapVariant",
"(",
"action",
".",
"data",
"(",
")",
")",
"view",
"=",
"self",
".",
"_currentPanel",
".",
"currentView",
"(",
")",
"view",
".",
"setViewingGroup",
"(",
"grp",
")"... | 32 | 0.013514 |
def executions(self) -> List[Execution]:
"""
List of all executions from this session.
"""
return list(fill.execution for fill in self.wrapper.fills.values()) | [
"def",
"executions",
"(",
"self",
")",
"->",
"List",
"[",
"Execution",
"]",
":",
"return",
"list",
"(",
"fill",
".",
"execution",
"for",
"fill",
"in",
"self",
".",
"wrapper",
".",
"fills",
".",
"values",
"(",
")",
")"
] | 37.2 | 0.010526 |
def _lonlat_from_geos_angle(x, y, geos_area):
"""Get lons and lats from x, y in projection coordinates."""
h = (geos_area.proj_dict['h'] + geos_area.proj_dict['a']) / 1000
b__ = (geos_area.proj_dict['a'] / geos_area.proj_dict['b']) ** 2
sd = np.sqrt((h * np.cos(x) * np.cos(y)) ** 2 -
(... | [
"def",
"_lonlat_from_geos_angle",
"(",
"x",
",",
"y",
",",
"geos_area",
")",
":",
"h",
"=",
"(",
"geos_area",
".",
"proj_dict",
"[",
"'h'",
"]",
"+",
"geos_area",
".",
"proj_dict",
"[",
"'a'",
"]",
")",
"/",
"1000",
"b__",
"=",
"(",
"geos_area",
".",... | 39.15 | 0.001247 |
def handle_tags(repo, **kwargs):
""":return: repo.tags()"""
log.info('tags: %s %s' %(repo, kwargs))
return [str(t) for t in repo.tags(**kwargs)] | [
"def",
"handle_tags",
"(",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"'tags: %s %s'",
"%",
"(",
"repo",
",",
"kwargs",
")",
")",
"return",
"[",
"str",
"(",
"t",
")",
"for",
"t",
"in",
"repo",
".",
"tags",
"(",
"*",
"*"... | 38.25 | 0.012821 |
def _draw_text(self, pos, text, font, **kw):
"""
Remember a single drawable tuple to paint later.
"""
self.drawables.append((pos, text, font, kw)) | [
"def",
"_draw_text",
"(",
"self",
",",
"pos",
",",
"text",
",",
"font",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"drawables",
".",
"append",
"(",
"(",
"pos",
",",
"text",
",",
"font",
",",
"kw",
")",
")"
] | 34.8 | 0.011236 |
def _connect(self):
"""Connects to the manager."""
cls = self._get_manager_class(register_callables=False)
ins = cls(address=self.addr, authkey=self.authkey)
ins.connect()
return ins | [
"def",
"_connect",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"_get_manager_class",
"(",
"register_callables",
"=",
"False",
")",
"ins",
"=",
"cls",
"(",
"address",
"=",
"self",
".",
"addr",
",",
"authkey",
"=",
"self",
".",
"authkey",
")",
"ins",... | 36.166667 | 0.009009 |
def calcDeviationLimits(value, tolerance, mode):
"""Returns the upper and lower deviation limits for a value and a given
tolerance, either as relative or a absolute difference.
:param value: can be a single value or a list of values if a list of values
is given, the minimal value will be used to ca... | [
"def",
"calcDeviationLimits",
"(",
"value",
",",
"tolerance",
",",
"mode",
")",
":",
"values",
"=",
"toList",
"(",
"value",
")",
"if",
"mode",
"==",
"'relative'",
":",
"lowerLimit",
"=",
"min",
"(",
"values",
")",
"*",
"(",
"1",
"-",
"tolerance",
")",
... | 45.809524 | 0.002037 |
def _actionsFreqsAngles(self,*args,**kwargs):
"""
NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,... | [
"def",
"_actionsFreqsAngles",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"5",
":",
"#R,vR.vT, z, vz pragma: no cover",
"raise",
"IOError",
"(",
"\"You need to provide phi when calculating angles\"",
")",
... | 40.309091 | 0.024873 |
def _preprocess_yml(path):
"""Dynamically create PY3 version of the file by re-writing 'unicode' to 'str'."""
with open(path) as f:
tmp_yaml = f.read()
return re.sub(r"unicode", "str", tmp_yaml) | [
"def",
"_preprocess_yml",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"tmp_yaml",
"=",
"f",
".",
"read",
"(",
")",
"return",
"re",
".",
"sub",
"(",
"r\"unicode\"",
",",
"\"str\"",
",",
"tmp_yaml",
")"
] | 42 | 0.009346 |
def element_contains(self, element_id, value):
"""
Assert provided content is contained within an element found by ``id``.
"""
elements = ElementSelector(
world.browser,
str('id("{id}")[contains(., "{value}")]'.format(
id=element_id, value=value)),
filter_displayed=T... | [
"def",
"element_contains",
"(",
"self",
",",
"element_id",
",",
"value",
")",
":",
"elements",
"=",
"ElementSelector",
"(",
"world",
".",
"browser",
",",
"str",
"(",
"'id(\"{id}\")[contains(., \"{value}\")]'",
".",
"format",
"(",
"id",
"=",
"element_id",
",",
... | 30.692308 | 0.002433 |
def runSearchRequest(
self, requestStr, requestClass, responseClass, objectGenerator):
"""
Runs the specified request. The request is a string containing
a JSON representation of an instance of the specified requestClass.
We return a string representation of an instance of th... | [
"def",
"runSearchRequest",
"(",
"self",
",",
"requestStr",
",",
"requestClass",
",",
"responseClass",
",",
"objectGenerator",
")",
":",
"self",
".",
"startProfile",
"(",
")",
"try",
":",
"request",
"=",
"protocol",
".",
"fromJson",
"(",
"requestStr",
",",
"r... | 49.4375 | 0.00124 |
def check_missing_references(client):
"""Find missing references."""
from renku.models.refs import LinkReference
missing = [
ref for ref in LinkReference.iter_items(client)
if not ref.reference.exists()
]
if not missing:
return True
click.secho(
WARNING + 'Ther... | [
"def",
"check_missing_references",
"(",
"client",
")",
":",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"LinkReference",
"missing",
"=",
"[",
"ref",
"for",
"ref",
"in",
"LinkReference",
".",
"iter_items",
"(",
"client",
")",
"if",
"not",
"ref",
... | 28.8 | 0.001681 |
def setup(self, universe):
"""
Setup Security with universe. Speeds up future runs.
Args:
* universe (DataFrame): DataFrame of prices with security's name as
one of the columns.
"""
# if we already have all the prices, we will store them to speed up
... | [
"def",
"setup",
"(",
"self",
",",
"universe",
")",
":",
"# if we already have all the prices, we will store them to speed up",
"# future updates",
"try",
":",
"prices",
"=",
"universe",
"[",
"self",
".",
"name",
"]",
"except",
"KeyError",
":",
"prices",
"=",
"None",... | 32.714286 | 0.001696 |
def unlock():
'''
Unlocks the candidate configuration.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.unlock
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.unlock()
ret['message'] = "Successfully unlocked the config... | [
"def",
"unlock",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"unlock",
"(",
")",
"ret",
"[",
"'message'",
"]",
"="... | 23.363636 | 0.001869 |
def plot(self, label=None, colour='g', style='-'): # pragma: no cover
'''Plot the time series.'''
pylab = LazyImport.pylab()
pylab.plot(self.dates, self.values, '%s%s' % (colour, style), label=label)
if label is not None:
pylab.legend()
pylab.show() | [
"def",
"plot",
"(",
"self",
",",
"label",
"=",
"None",
",",
"colour",
"=",
"'g'",
",",
"style",
"=",
"'-'",
")",
":",
"# pragma: no cover",
"pylab",
"=",
"LazyImport",
".",
"pylab",
"(",
")",
"pylab",
".",
"plot",
"(",
"self",
".",
"dates",
",",
"s... | 42.142857 | 0.013289 |
def compute_implicit_line(nodes):
"""Compute the implicit form of the line connecting curve endpoints.
.. note::
This assumes, but does not check, that the first and last nodes
in ``nodes`` are different.
Computes :math:`a, b` and :math:`c` in the normalized implicit equation
for the li... | [
"def",
"compute_implicit_line",
"(",
"nodes",
")",
":",
"delta",
"=",
"nodes",
"[",
":",
",",
"-",
"1",
"]",
"-",
"nodes",
"[",
":",
",",
"0",
"]",
"length",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"delta",
",",
"ord",
"=",
"2",
")",
"# Nor... | 31.184211 | 0.000818 |
def validate_config_json(pjson):
"""Takes the parsed JSON (output from json.load) from a configuration file
and checks it for common errors."""
# Make sure that the root json is a dict
if type(pjson) is not dict:
raise ParseError("Configuration file should contain a single J... | [
"def",
"validate_config_json",
"(",
"pjson",
")",
":",
"# Make sure that the root json is a dict",
"if",
"type",
"(",
"pjson",
")",
"is",
"not",
"dict",
":",
"raise",
"ParseError",
"(",
"\"Configuration file should contain a single JSON object/dictionary. Instead got a %s.\"",
... | 48.0625 | 0.008286 |
def anneal(self):
"""Minimizes the energy of a system by simulated annealing.
Parameters
state : an initial arrangement of the system
Returns
(state, energy): the best state and energy found.
"""
step = 0
self.start = time.time()
# Precompute fa... | [
"def",
"anneal",
"(",
"self",
")",
":",
"step",
"=",
"0",
"self",
".",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# Precompute factor for exponential cooling from Tmax to Tmin",
"if",
"self",
".",
"Tmin",
"<=",
"0.0",
":",
"raise",
"Exception",
"(",
"'Exp... | 35.828125 | 0.001273 |
def write_networks(folder, network_table, networks):
"""
Writing networkTable, nodes and edges to Perseus readable format.
:param folder: Path to output directory.
:param network_table: Network table.
:param networks: Dictionary with node and edge tables, indexed by network guid.
"""
ma... | [
"def",
"write_networks",
"(",
"folder",
",",
"network_table",
",",
"networks",
")",
":",
"makedirs",
"(",
"folder",
",",
"exist_ok",
"=",
"True",
")",
"network_table",
".",
"to_perseus",
"(",
"path",
".",
"join",
"(",
"folder",
",",
"'networks.txt'",
")",
... | 51.846154 | 0.010204 |
def result_cached(task_id, wait=0, broker=None):
"""
Return the result from the cache backend
"""
if not broker:
broker = get_broker()
start = time()
while True:
r = broker.cache.get('{}:{}'.format(broker.list_key, task_id))
if r:
return SignedPackage.loads(r... | [
"def",
"result_cached",
"(",
"task_id",
",",
"wait",
"=",
"0",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"start",
"=",
"time",
"(",
")",
"while",
"True",
":",
"r",
"=",
"broker",
".",
... | 28.928571 | 0.002392 |
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True,
errors='replace', separator='&', cls=None):
"""
Parse a querystring and return it as :class:`MultiDict`. There is a
difference in key decoding on different Python versions. On Python 3
keys will always be fully de... | [
"def",
"url_decode",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
",",
"decode_keys",
"=",
"False",
",",
"include_empty",
"=",
"True",
",",
"errors",
"=",
"'replace'",
",",
"separator",
"=",
"'&'",
",",
"cls",
"=",
"None",
")",
":",
"if",
"cls",
"is",
"... | 51.208333 | 0.000399 |
def parse_skewer_log(self, f):
""" Go through log file looking for skewer output """
fh = f['f']
regexes = {
'fq1': "Input file:\s+(.+)",
'fq2': "Paired file:\s+(.+)",
'r_processed': "(\d+) read|reads pairs? processed",
'r_short_filtered': "(\d+) \... | [
"def",
"parse_skewer_log",
"(",
"self",
",",
"f",
")",
":",
"fh",
"=",
"f",
"[",
"'f'",
"]",
"regexes",
"=",
"{",
"'fq1'",
":",
"\"Input file:\\s+(.+)\"",
",",
"'fq2'",
":",
"\"Paired file:\\s+(.+)\"",
",",
"'r_processed'",
":",
"\"(\\d+) read|reads pairs? proce... | 41.183673 | 0.021781 |
def save(self, key, data):
""" Save data associated with key.
"""
self._db[key] = json.dumps(data)
self._db.sync() | [
"def",
"save",
"(",
"self",
",",
"key",
",",
"data",
")",
":",
"self",
".",
"_db",
"[",
"key",
"]",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"self",
".",
"_db",
".",
"sync",
"(",
")"
] | 28.4 | 0.013699 |
def get_value(self, source):
"""Apply self.convert to the source. The parameter passed to convert depends on
self.source_name. If source_name is given, self.convert(getattr(source, source_name)) is called,
otherwise self.convert(source) is called.
"""
if self.source_name is None:
present, valu... | [
"def",
"get_value",
"(",
"self",
",",
"source",
")",
":",
"if",
"self",
".",
"source_name",
"is",
"None",
":",
"present",
",",
"value",
"=",
"True",
",",
"self",
".",
"convert",
"(",
"source",
")",
"converted",
"=",
"True",
"else",
":",
"present",
",... | 31.590909 | 0.015363 |
def get(filepath):
"""
Return (width, height) for a given img file content
no requirements
"""
height = -1
width = -1
with open(filepath, 'rb') as fhandle:
head = fhandle.read(24)
size = len(head)
# handle GIFs
if size >= 10 and head[:6] in (b'GIF87a', b'GIF8... | [
"def",
"get",
"(",
"filepath",
")",
":",
"height",
"=",
"-",
"1",
"width",
"=",
"-",
"1",
"with",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"fhandle",
":",
"head",
"=",
"fhandle",
".",
"read",
"(",
"24",
")",
"size",
"=",
"len",
"(",
"he... | 43.783505 | 0.002072 |
def add_gate_option_group(parser):
"""Adds the options needed to apply gates to data.
Parameters
----------
parser : object
ArgumentParser instance.
"""
gate_group = parser.add_argument_group("Options for gating data.")
gate_group.add_argument("--gate", nargs="+", type=str,
... | [
"def",
"add_gate_option_group",
"(",
"parser",
")",
":",
"gate_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Options for gating data.\"",
")",
"gate_group",
".",
"add_argument",
"(",
"\"--gate\"",
",",
"nargs",
"=",
"\"+\"",
",",
"type",
"=",
"str",
... | 49.076923 | 0.000769 |
def rotation(self):
"""Rotation of device
Returns:
int (0-3)
"""
rs = dict(PORTRAIT=0, LANDSCAPE=1, UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT=3)
return rs.get(self.session.orientation, 0) | [
"def",
"rotation",
"(",
"self",
")",
":",
"rs",
"=",
"dict",
"(",
"PORTRAIT",
"=",
"0",
",",
"LANDSCAPE",
"=",
"1",
",",
"UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT",
"=",
"3",
")",
"return",
"rs",
".",
"get",
"(",
"self",
".",
"session",
".",
"orientation",
... | 32.714286 | 0.012766 |
def _syllabifyPhones(phoneList, syllableList):
'''
Given a phone list and a syllable list, syllabify the phones
Typically used by findBestSyllabification which first aligns the phoneList
with a dictionary phoneList and then uses the dictionary syllabification
to syllabify the input phoneList.
... | [
"def",
"_syllabifyPhones",
"(",
"phoneList",
",",
"syllableList",
")",
":",
"numPhoneList",
"=",
"[",
"len",
"(",
"syllable",
")",
"for",
"syllable",
"in",
"syllableList",
"]",
"start",
"=",
"0",
"syllabifiedList",
"=",
"[",
"]",
"for",
"end",
"in",
"numPh... | 28.952381 | 0.011146 |
def sync_allocations(self):
"""
Synchronize vxlan_allocations table with configured tunnel ranges.
"""
# determine current configured allocatable vnis
vxlan_vnis = set()
for tun_min, tun_max in self.tunnel_ranges:
vxlan_vnis |= set(six.moves.range(tun_min, tu... | [
"def",
"sync_allocations",
"(",
"self",
")",
":",
"# determine current configured allocatable vnis",
"vxlan_vnis",
"=",
"set",
"(",
")",
"for",
"tun_min",
",",
"tun_max",
"in",
"self",
".",
"tunnel_ranges",
":",
"vxlan_vnis",
"|=",
"set",
"(",
"six",
".",
"moves... | 50.785714 | 0.00092 |
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return Minion(opts,
timeout,
... | [
"def",
"_create_minion_object",
"(",
"self",
",",
"opts",
",",
"timeout",
",",
"safe",
",",
"io_loop",
"=",
"None",
",",
"loaded_base_name",
"=",
"None",
",",
"jid_queue",
"=",
"None",
")",
":",
"return",
"Minion",
"(",
"opts",
",",
"timeout",
",",
"safe... | 38.833333 | 0.008386 |
def optimize_seq_and_branch_len(self,reuse_branch_len=True, prune_short=True,
marginal_sequences=False, branch_length_mode='joint',
max_iter=5, infer_gtr=False, **kwargs):
"""
Iteratively set branch lengths and reconstruct ancestral... | [
"def",
"optimize_seq_and_branch_len",
"(",
"self",
",",
"reuse_branch_len",
"=",
"True",
",",
"prune_short",
"=",
"True",
",",
"marginal_sequences",
"=",
"False",
",",
"branch_length_mode",
"=",
"'joint'",
",",
"max_iter",
"=",
"5",
",",
"infer_gtr",
"=",
"False... | 48.064935 | 0.009267 |
def loaded_frame(self, tag):
"""Deprecated; use the add method."""
# turn 2.2 into 2.3/2.4 tags
if len(type(tag).__name__) == 3:
tag = type(tag).__base__(tag)
self[tag.HashKey] = tag | [
"def",
"loaded_frame",
"(",
"self",
",",
"tag",
")",
":",
"# turn 2.2 into 2.3/2.4 tags",
"if",
"len",
"(",
"type",
"(",
"tag",
")",
".",
"__name__",
")",
"==",
"3",
":",
"tag",
"=",
"type",
"(",
"tag",
")",
".",
"__base__",
"(",
"tag",
")",
"self",
... | 36.833333 | 0.00885 |
def response(self, payload):
"""
Send a response to the previously received challenge, with the given
`payload`. The payload is encoded using base64 and transmitted to the
server.
Return the next state of the state machine as tuple (see
:class:`SASLStateMachine` for deta... | [
"def",
"response",
"(",
"self",
",",
"payload",
")",
":",
"if",
"self",
".",
"_state",
"==",
"SASLState",
".",
"SUCCESS_SIMULATE_CHALLENGE",
":",
"if",
"payload",
"!=",
"b\"\"",
":",
"# XXX: either our mechanism is buggy or the server",
"# sent SASLState.SUCCESS before ... | 41.26087 | 0.001544 |
def _join(*args):
"""Join S3 bucket args together.
Remove empty entries and strip left-leading ``/``
"""
return delimiter.join(filter(lambda s: s != '', map(lambda s: s.lstrip(delimiter), args))) | [
"def",
"_join",
"(",
"*",
"args",
")",
":",
"return",
"delimiter",
".",
"join",
"(",
"filter",
"(",
"lambda",
"s",
":",
"s",
"!=",
"''",
",",
"map",
"(",
"lambda",
"s",
":",
"s",
".",
"lstrip",
"(",
"delimiter",
")",
",",
"args",
")",
")",
")"
... | 34.5 | 0.009434 |
def jpegtran(ext_args):
"""Create argument list for jpegtran."""
args = copy.copy(_JPEGTRAN_ARGS)
if Settings.destroy_metadata:
args += ["-copy", "none"]
else:
args += ["-copy", "all"]
if Settings.jpegtran_prog:
args += ["-progressive"]
args += ['-outfile']
args += [e... | [
"def",
"jpegtran",
"(",
"ext_args",
")",
":",
"args",
"=",
"copy",
".",
"copy",
"(",
"_JPEGTRAN_ARGS",
")",
"if",
"Settings",
".",
"destroy_metadata",
":",
"args",
"+=",
"[",
"\"-copy\"",
",",
"\"none\"",
"]",
"else",
":",
"args",
"+=",
"[",
"\"-copy\"",... | 30.846154 | 0.002421 |
def _filter_meta_data(self, source, soup, data, url=None):
"""This method filters the web page content for meta tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['meta']``
:type source: string
:param soup: BeautifulSoup ... | [
"def",
"_filter_meta_data",
"(",
"self",
",",
"source",
",",
"soup",
",",
"data",
",",
"url",
"=",
"None",
")",
":",
"meta",
"=",
"FILTER_MAPS",
"[",
"'meta'",
"]",
"[",
"source",
"]",
"meta_map",
"=",
"meta",
"[",
"'map'",
"]",
"html",
"=",
"soup",
... | 38.887097 | 0.002427 |
def update_beliefs(self, corpus_id):
"""Return updated belief scores for a given corpus.
Parameters
----------
corpus_id : str
The ID of the corpus for which beliefs are to be updated.
Returns
-------
dict
A dictionary of belief scores wi... | [
"def",
"update_beliefs",
"(",
"self",
",",
"corpus_id",
")",
":",
"corpus",
"=",
"self",
".",
"get_corpus",
"(",
"corpus_id",
")",
"be",
"=",
"BeliefEngine",
"(",
"self",
".",
"scorer",
")",
"stmts",
"=",
"list",
"(",
"corpus",
".",
"statements",
".",
... | 35.333333 | 0.002041 |
def query(self, collection, query, request_handler='select', **kwargs):
"""
:param str collection: The name of the collection for the request
:param str request_handler: Request handler, default is 'select'
:param dict query: Python dictonary of Solr query parameters.
Sends a qu... | [
"def",
"query",
"(",
"self",
",",
"collection",
",",
"query",
",",
"request_handler",
"=",
"'select'",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"field",
"in",
"[",
"'facet.pivot'",
"]",
":",
"if",
"field",
"in",
"query",
".",
"keys",
"(",
")",
":",
... | 43.210526 | 0.001787 |
def get_description(self, lang=None):
""" Get the DC description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal
"""
return self.metadata.get_single(key=RDF_NAMESPACES.CTS.description, lang=lang) | [
"def",
"get_description",
"(",
"self",
",",
"lang",
"=",
"None",
")",
":",
"return",
"self",
".",
"metadata",
".",
"get_single",
"(",
"key",
"=",
"RDF_NAMESPACES",
".",
"CTS",
".",
"description",
",",
"lang",
"=",
"lang",
")"
] | 36.5 | 0.010033 |
def commands(self):
"""
Returns a list of commands that are supported by the motor
controller. Possible values are `run-forever`, `run-to-abs-pos`, `run-to-rel-pos`,
`run-timed`, `run-direct`, `stop` and `reset`. Not all commands may be supported.
- `run-forever` will cause the ... | [
"def",
"commands",
"(",
"self",
")",
":",
"(",
"self",
".",
"_commands",
",",
"value",
")",
"=",
"self",
".",
"get_cached_attr_set",
"(",
"self",
".",
"_commands",
",",
"'commands'",
")",
"return",
"value"
] | 64.5 | 0.009548 |
def addAction(self, action):
""" Register Custom Action """
self.ACTIONS.append(action)
return "ACTION#{}".format(len(self.ACTIONS) - 1) | [
"def",
"addAction",
"(",
"self",
",",
"action",
")",
":",
"self",
".",
"ACTIONS",
".",
"append",
"(",
"action",
")",
"return",
"\"ACTION#{}\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"ACTIONS",
")",
"-",
"1",
")"
] | 39.25 | 0.0125 |
def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
... | [
"def",
"parse_substitution_from_list",
"(",
"list_rep",
")",
":",
"# We are expecting [pattern, replacement [, is_multiline]]",
"if",
"type",
"(",
"list_rep",
")",
"is",
"not",
"list",
":",
"raise",
"SyntaxError",
"(",
"'Substitution must be a list'",
")",
"if",
"len",
... | 34.363636 | 0.001287 |
def read_dataset(ctx, dataset, output):
"""Read the attributes of a dataset.
Prints a JSON object containing the attributes
of a dataset. The attributes: owner (a Mapbox account),
id (dataset id), created (Unix timestamp), modified
(timestamp), name (string), and description (string).
$ ma... | [
"def",
"read_dataset",
"(",
"ctx",
",",
"dataset",
",",
"output",
")",
":",
"stdout",
"=",
"click",
".",
"open_file",
"(",
"output",
",",
"'w'",
")",
"service",
"=",
"ctx",
".",
"obj",
".",
"get",
"(",
"'service'",
")",
"res",
"=",
"service",
".",
... | 32.863636 | 0.001344 |
def diff(var, key):
'''calculate differences between values'''
global last_diff
ret = 0
if not key in last_diff:
last_diff[key] = var
return 0
ret = var - last_diff[key]
last_diff[key] = var
return ret | [
"def",
"diff",
"(",
"var",
",",
"key",
")",
":",
"global",
"last_diff",
"ret",
"=",
"0",
"if",
"not",
"key",
"in",
"last_diff",
":",
"last_diff",
"[",
"key",
"]",
"=",
"var",
"return",
"0",
"ret",
"=",
"var",
"-",
"last_diff",
"[",
"key",
"]",
"l... | 23.6 | 0.008163 |
def lookupRecords(self, record):
"""
Lookups records based on the inputed record. This will use the
tableLookupIndex property to determine the Orb Index method to
use to look up records. That index method should take the inputed
record as an argument, and return a list of... | [
"def",
"lookupRecords",
"(",
"self",
",",
"record",
")",
":",
"table_type",
"=",
"self",
".",
"tableType",
"(",
")",
"if",
"not",
"table_type",
":",
"return",
"index",
"=",
"getattr",
"(",
"table_type",
",",
"self",
".",
"tableLookupIndex",
"(",
")",
","... | 35.277778 | 0.009202 |
def _from_python(self, value):
"""
Converts python values to a form suitable for insertion into the xml
we send to solr.
"""
if hasattr(value, 'strftime'):
if hasattr(value, 'hour'):
offset = value.utcoffset()
if offset:
... | [
"def",
"_from_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'strftime'",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'hour'",
")",
":",
"offset",
"=",
"value",
".",
"utcoffset",
"(",
")",
"if",
"offset",
":",
... | 33.322581 | 0.001881 |
def unlike(self):
""" Unlike a clip.
"""
r = requests.delete(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header)
return (r.json()) | [
"def",
"unlike",
"(",
"self",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"\"https://kippt.com/api/clips/%s/likes\"",
"%",
"(",
"self",
".",
"id",
")",
",",
"headers",
"=",
"self",
".",
"kippt",
".",
"header",
")",
"return",
"(",
"r",
".",
"jso... | 26 | 0.009302 |
def spitOutLines(lines, file, expand=False):
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler)."""
file = _normalizeToFile(file, mode="w", expand=expand)
try: file.writelines(lines)
finally: file.close() | [
"def",
"spitOutLines",
"(",
"lines",
",",
"file",
",",
"expand",
"=",
"False",
")",
":",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"mode",
"=",
"\"w\"",
",",
"expand",
"=",
"expand",
")",
"try",
":",
"file",
".",
"writelines",
"(",
"lines",
... | 43.5 | 0.011278 |
def add_namespace(self, ns_prefix, ns_uri):
'''
preferred method is to instantiate with repository under 'context',
but prefixes / namespaces can be added for a Resource instance
adds to self.rdf.prefixes which will endure through create/update/refresh,
and get added back to parsed graph namespaces
Args:... | [
"def",
"add_namespace",
"(",
"self",
",",
"ns_prefix",
",",
"ns_uri",
")",
":",
"# add to prefixes",
"setattr",
"(",
"self",
".",
"rdf",
".",
"prefixes",
",",
"ns_prefix",
",",
"rdflib",
".",
"Namespace",
"(",
"ns_uri",
")",
")",
"# bind to graph",
"self",
... | 35.954545 | 0.023399 |
def __prepare(self):
"""Update database with existing devices"""
self.log.debug("prepare")
if self.__phase > 0:
raise RuntimeError("Internal error: Can only prepare in phase 0")
server_instance = self.server_instance
db = Database()
# get list of server dev... | [
"def",
"__prepare",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"prepare\"",
")",
"if",
"self",
".",
"__phase",
">",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Internal error: Can only prepare in phase 0\"",
")",
"server_instance",
"=",
"se... | 35.76 | 0.001451 |
def set_managing_editor(self):
"""Parses managing editor and set value"""
try:
self.managing_editor = self.soup.find('managingeditor').string
except AttributeError:
self.managing_editor = None | [
"def",
"set_managing_editor",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"managing_editor",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'managingeditor'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"managing_editor",
"=",
"None"
... | 39.166667 | 0.008333 |
def allow_create(function):
"""
Decorate the `form_valid` method in a Create/Update class to create new
values if necessary.
.. warning::
Make sure that this decorator **only** decorates the ``form_valid()``
method and **only** this one.
"""
@wraps(function)
def _wrapped_f... | [
"def",
"allow_create",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"args",
"[",
"0",
"]",
"# If this argument is not a form, there are a lot of chances... | 36.967742 | 0.00085 |
def _flux_engine_data(engine):
""" Return rTorrent data set for pushing to InfluxDB.
"""
data = stats.engine_data(engine)
# Make it flat
data["up_rate"] = data["upload"][0]
data["up_limit"] = data["upload"][1]
data["down_rate"] = data["download"][0]
data["down_limit"] = data["download"]... | [
"def",
"_flux_engine_data",
"(",
"engine",
")",
":",
"data",
"=",
"stats",
".",
"engine_data",
"(",
"engine",
")",
"# Make it flat",
"data",
"[",
"\"up_rate\"",
"]",
"=",
"data",
"[",
"\"upload\"",
"]",
"[",
"0",
"]",
"data",
"[",
"\"up_limit\"",
"]",
"=... | 25.947368 | 0.001957 |
def __get_dtype(typespec):
'''Get the dtype associated with a jsonschema type definition
Parameters
----------
typespec : dict
The schema definition
Returns
-------
dtype : numpy.dtype
The associated dtype
'''
if 'type' in typespec:
return __TYPE_MAP__.get(... | [
"def",
"__get_dtype",
"(",
"typespec",
")",
":",
"if",
"'type'",
"in",
"typespec",
":",
"return",
"__TYPE_MAP__",
".",
"get",
"(",
"typespec",
"[",
"'type'",
"]",
",",
"np",
".",
"object_",
")",
"elif",
"'enum'",
"in",
"typespec",
":",
"# Enums map to obje... | 22.2 | 0.001439 |
def modify_placeholder(request, page_id):
"""Modify the content of a page."""
content_type = request.GET.get('content_type')
language_id = request.GET.get('language_id')
page = get_object_or_404(Page, pk=page_id)
perm = request.user.has_perm('pages.change_page')
if perm and request.method == 'PO... | [
"def",
"modify_placeholder",
"(",
"request",
",",
"page_id",
")",
":",
"content_type",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'content_type'",
")",
"language_id",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'language_id'",
")",
"page",
"=",
"get_o... | 39.461538 | 0.000634 |
def mask(args):
"""
%prog mask agpfile bedfile
Mask given ranges in components to gaps. When the bedfile contains a single
base pair, this position can be a point of split and no base is lost
(--splitsingle).
"""
p = OptionParser(mask.__doc__)
p.add_option("--splitobject", default=False... | [
"def",
"mask",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mask",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--splitobject\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Create new names fo... | 34.888889 | 0.000664 |
def to_timedelta(value):
"""Converts a string to a timedelta."""
if value is None:
return None
if isinstance(value, (six.integer_types, float)):
return timedelta(microseconds=(float(value) / 10))
match = _TIMESPAN_PATTERN.match(value)
if match:
if match.group(1) == "-":
... | [
"def",
"to_timedelta",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"six",
".",
"integer_types",
",",
"float",
")",
")",
":",
"return",
"timedelta",
"(",
"microseconds",
"=",
"(... | 33.25 | 0.001462 |
def file_copy(name, dest=None, **kwargs):
'''
Copies the file from the local device to the junos device.
.. code-block:: yaml
/home/m2/info.txt:
junos:
- file_copy
- dest: info_copy.txt
Parameters:
Required
* src:
The s... | [
"def",
"file_copy",
"(",
"name",
",",
"dest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"... | 27.428571 | 0.001678 |
def add(self, data_source, module, package=None):
"""
Add data_source to model. Tries to import module, then looks for data
source class definition.
:param data_source: Name of data source to add.
:type data_source: str
:param module: Module in which data source resides.... | [
"def",
"add",
"(",
"self",
",",
"data_source",
",",
"module",
",",
"package",
"=",
"None",
")",
":",
"super",
"(",
"Data",
",",
"self",
")",
".",
"add",
"(",
"data_source",
",",
"module",
",",
"package",
")",
"# only update layer info if it is missing!",
"... | 43.217391 | 0.001969 |
def get_environment_paths(config, env):
"""
Get environment paths from given environment variable.
"""
if env is None:
return config.get(Config.DEFAULTS, 'environment')
# Config option takes precedence over environment key.
if config.has_option(Config.ENVIRONMENTS, env):
... | [
"def",
"get_environment_paths",
"(",
"config",
",",
"env",
")",
":",
"if",
"env",
"is",
"None",
":",
"return",
"config",
".",
"get",
"(",
"Config",
".",
"DEFAULTS",
",",
"'environment'",
")",
"# Config option takes precedence over environment key.\r",
"if",
"confi... | 34.066667 | 0.001905 |
def update(context, id, etag, name, component_types,
label, next_topic_id, active, product_id, data):
"""update(context, id, etag, name, label, next_topic_id, active,
product_id, data)
Update a Topic.
>>> dcictl topic-update [OPTIONS]
:param string id: ID of the Topic [requir... | [
"def",
"update",
"(",
"context",
",",
"id",
",",
"etag",
",",
"name",
",",
"component_types",
",",
"label",
",",
"next_topic_id",
",",
"active",
",",
"product_id",
",",
"data",
")",
":",
"if",
"component_types",
":",
"component_types",
"=",
"component_types"... | 42.62069 | 0.000791 |
def records(self):
"""
Return a new raw REST interface to record resources
:rtype: :py:class:`ns1.rest.records.Records`
"""
import ns1.rest.records
return ns1.rest.records.Records(self.config) | [
"def",
"records",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"records",
"return",
"ns1",
".",
"rest",
".",
"records",
".",
"Records",
"(",
"self",
".",
"config",
")"
] | 29.25 | 0.008299 |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist, not empty (issue #871) and plugin not disabled
if not self.stats or (self.stats == []) or self.is_disable():... | [
"def",
"msg_curse",
"(",
"self",
",",
"args",
"=",
"None",
",",
"max_width",
"=",
"None",
")",
":",
"# Init the return message",
"ret",
"=",
"[",
"]",
"# Only process if stats exist, not empty (issue #871) and plugin not disabled",
"if",
"not",
"self",
".",
"stats",
... | 39.583333 | 0.001467 |
def get_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None):
"""
Return the expr_def_id for the row in the table whose
values match the givens.
If a matching row is not found, returns None.
@search_group: string representing the search group (e.g., cbc)
... | [
"def",
"get_expr_id",
"(",
"self",
",",
"search_group",
",",
"search",
",",
"lars_id",
",",
"instruments",
",",
"gps_start_time",
",",
"gps_end_time",
",",
"comments",
"=",
"None",
")",
":",
"# create string from instrument set",
"instruments",
"=",
"ifos_from_instr... | 43.5 | 0.025305 |
def done_waiting(self):
"""
Show running progress bar (only has an effect if we are in waiting state).
"""
if self.waiting:
self.waiting = False
self.progress_bar.show_running() | [
"def",
"done_waiting",
"(",
"self",
")",
":",
"if",
"self",
".",
"waiting",
":",
"self",
".",
"waiting",
"=",
"False",
"self",
".",
"progress_bar",
".",
"show_running",
"(",
")"
] | 32.428571 | 0.012876 |
def _get_stddevs(self, imt, mag, n_sites, stddev_types):
"""
The standard error (assumed equivalent to total standard deviation)
is defined as a function of magnitude and period (equation 4,
page 1168). For magnitudes lower than 5.0 the standard deviation is
equal to that for the... | [
"def",
"_get_stddevs",
"(",
"self",
",",
"imt",
",",
"mag",
",",
"n_sites",
",",
"stddev_types",
")",
":",
"if",
"mag",
"<",
"5.0",
":",
"stddev_mag",
"=",
"5.0",
"else",
":",
"stddev_mag",
"=",
"mag",
"if",
"imt",
".",
"name",
"==",
"\"PGA\"",
"or",... | 45.928571 | 0.001523 |
def createmeta(accountable, project_key, issue_type=None):
"""
Create new issue.
"""
metadata = accountable.create_meta(project_key, issue_type)
headers = [
'project_key', 'issuetype_name', 'field_key', 'field_name', 'required'
]
rows = [headers]
for project in metadata:
... | [
"def",
"createmeta",
"(",
"accountable",
",",
"project_key",
",",
"issue_type",
"=",
"None",
")",
":",
"metadata",
"=",
"accountable",
".",
"create_meta",
"(",
"project_key",
",",
"issue_type",
")",
"headers",
"=",
"[",
"'project_key'",
",",
"'issuetype_name'",
... | 35.095238 | 0.001321 |
def fromenv() -> 'VaultAuth12Factor':
"""
:return: Load configuration from the environment and return a configured instance
"""
i = None # type: VaultAuth12Factor
if os.getenv("VAULT_TOKEN", None):
i = VaultAuth12Factor.token(os.getenv("VAULT_TOKEN"))
elif os... | [
"def",
"fromenv",
"(",
")",
"->",
"'VaultAuth12Factor'",
":",
"i",
"=",
"None",
"# type: VaultAuth12Factor",
"if",
"os",
".",
"getenv",
"(",
"\"VAULT_TOKEN\"",
",",
"None",
")",
":",
"i",
"=",
"VaultAuth12Factor",
".",
"token",
"(",
"os",
".",
"getenv",
"(... | 53.333333 | 0.008772 |
def validate(self, signature, timestamp, nonce):
"""Validate request signature.
:param signature: A string signature parameter sent by weixin.
:param timestamp: A int timestamp parameter sent by weixin.
:param nonce: A int nonce parameter sent by weixin.
"""
if not self.... | [
"def",
"validate",
"(",
"self",
",",
"signature",
",",
"timestamp",
",",
"nonce",
")",
":",
"if",
"not",
"self",
".",
"token",
":",
"raise",
"RuntimeError",
"(",
"'WEIXIN_TOKEN is missing'",
")",
"if",
"self",
".",
"expires_in",
":",
"try",
":",
"timestamp... | 32.8 | 0.001974 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.