text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def success(self):
"""Return boolean indicating whether a solution was found."""
self._check_valid()
if self._ret_val != 0:
return False
return swiglpk.glp_get_status(self._problem._p) == swiglpk.GLP_OPT | [
"def",
"success",
"(",
"self",
")",
":",
"self",
".",
"_check_valid",
"(",
")",
"if",
"self",
".",
"_ret_val",
"!=",
"0",
":",
"return",
"False",
"return",
"swiglpk",
".",
"glp_get_status",
"(",
"self",
".",
"_problem",
".",
"_p",
")",
"==",
"swiglpk",... | 40.333333 | 15.833333 |
def rollsingle(self, func, window=20, name=None, fallback=False,
align='right', **kwargs):
'''Efficient rolling window calculation for min, max type functions
'''
rname = 'roll_{0}'.format(func)
if fallback:
rfunc = getattr(lib.fallback, rname)
else:
rfunc = getattr(li... | [
"def",
"rollsingle",
"(",
"self",
",",
"func",
",",
"window",
"=",
"20",
",",
"name",
"=",
"None",
",",
"fallback",
"=",
"False",
",",
"align",
"=",
"'right'",
",",
"*",
"*",
"kwargs",
")",
":",
"rname",
"=",
"'roll_{0}'",
".",
"format",
"(",
"func... | 38 | 16.1 |
def diffusion(diffusion_constant=0.2, exposure_time=0.05, samples=200):
"""
See `diffusion_correlated` for information related to units, etc
"""
radius = 5
psfsize = np.array([2.0, 1.0, 3.0])
# create a base image of one particle
s0 = init.create_single_particle_state(imsize=4*radius,
... | [
"def",
"diffusion",
"(",
"diffusion_constant",
"=",
"0.2",
",",
"exposure_time",
"=",
"0.05",
",",
"samples",
"=",
"200",
")",
":",
"radius",
"=",
"5",
"psfsize",
"=",
"np",
".",
"array",
"(",
"[",
"2.0",
",",
"1.0",
",",
"3.0",
"]",
")",
"# create a... | 33.727273 | 20.69697 |
def BuildFilterFindSpecs(
self, artifact_definitions_path, custom_artifacts_path,
knowledge_base_object, artifact_filter_names=None, filter_file_path=None):
"""Builds find specifications from artifacts or filter file if available.
Args:
artifact_definitions_path (str): path to artifact defini... | [
"def",
"BuildFilterFindSpecs",
"(",
"self",
",",
"artifact_definitions_path",
",",
"custom_artifacts_path",
",",
"knowledge_base_object",
",",
"artifact_filter_names",
"=",
"None",
",",
"filter_file_path",
"=",
"None",
")",
":",
"environment_variables",
"=",
"knowledge_ba... | 40.65625 | 23.875 |
def features_tags_parse_str_to_dict(obj):
"""
Parse tag strings of all features in the collection into a Python
dictionary, if possible.
"""
features = obj['features']
for i in tqdm(range(len(features))):
tags = features[i]['properties'].get('tags')
if tags is not None:
... | [
"def",
"features_tags_parse_str_to_dict",
"(",
"obj",
")",
":",
"features",
"=",
"obj",
"[",
"'features'",
"]",
"for",
"i",
"in",
"tqdm",
"(",
"range",
"(",
"len",
"(",
"features",
")",
")",
")",
":",
"tags",
"=",
"features",
"[",
"i",
"]",
"[",
"'pr... | 37.190476 | 15.666667 |
def _VarintBytes(value):
"""Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast."""
pieces = []
_EncodeVarint(pieces.append, value)
return b"".join(pieces) | [
"def",
"_VarintBytes",
"(",
"value",
")",
":",
"pieces",
"=",
"[",
"]",
"_EncodeVarint",
"(",
"pieces",
".",
"append",
",",
"value",
")",
"return",
"b\"\"",
".",
"join",
"(",
"pieces",
")"
] | 33.428571 | 14.428571 |
def GetReportDownloadHeaders(self, **kwargs):
"""Returns a dictionary of headers for a report download request.
Note that the given keyword arguments will override any settings configured
from the googleads.yaml file.
Args:
**kwargs: Optional keyword arguments.
Keyword Arguments:
clie... | [
"def",
"GetReportDownloadHeaders",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"self",
".",
"_adwords_client",
".",
"oauth2_client",
".",
"CreateHttpHeader",
"(",
")",
"headers",
".",
"update",
"(",
"{",
"'Content-type'",
":",
"self",
"."... | 41.948276 | 24.155172 |
def levels(self):
"""Returns a histogram for each RGBA channel.
Returns a 4-tuple of lists, r, g, b, and a.
Each list has 255 items, a count for each pixel value.
"""
h = self.img.histogram()
r = h[0:255]
g = h[256:511]
... | [
"def",
"levels",
"(",
"self",
")",
":",
"h",
"=",
"self",
".",
"img",
".",
"histogram",
"(",
")",
"r",
"=",
"h",
"[",
"0",
":",
"255",
"]",
"g",
"=",
"h",
"[",
"256",
":",
"511",
"]",
"b",
"=",
"h",
"[",
"512",
":",
"767",
"]",
"a",
"="... | 24.125 | 19 |
def input_loop():
'''wait for user input'''
while mpstate.status.exit != True:
try:
if mpstate.status.exit != True:
line = input(mpstate.rl.prompt)
except EOFError:
mpstate.status.exit = True
sys.exit(1)
mpstate.input_queue.put(line) | [
"def",
"input_loop",
"(",
")",
":",
"while",
"mpstate",
".",
"status",
".",
"exit",
"!=",
"True",
":",
"try",
":",
"if",
"mpstate",
".",
"status",
".",
"exit",
"!=",
"True",
":",
"line",
"=",
"input",
"(",
"mpstate",
".",
"rl",
".",
"prompt",
")",
... | 30.8 | 11.2 |
def is_path(path):
"""Checks if the passed in path is a valid Path within the portal
:param path: The path to check
:type uid: string
:return: True if the path is a valid path within the portal
:rtype: bool
"""
if not isinstance(path, basestring):
return False
portal_path = get_... | [
"def",
"is_path",
"(",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"return",
"False",
"portal_path",
"=",
"get_path",
"(",
"get_portal",
"(",
")",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"portal_path",... | 28 | 14.470588 |
def nsamples_to_hourmin(x, pos):
'''Convert axes labels to experiment duration in hours/minutes
Notes
-----
Matplotlib FuncFormatter function
https://matplotlib.org/examples/pylab_examples/custom_ticker1.html
'''
h, m, s = hourminsec(x/16.0)
return '{:.0f}h {:2.0f}′'.format(h, m+round(... | [
"def",
"nsamples_to_hourmin",
"(",
"x",
",",
"pos",
")",
":",
"h",
",",
"m",
",",
"s",
"=",
"hourminsec",
"(",
"x",
"/",
"16.0",
")",
"return",
"'{:.0f}h {:2.0f}′'.f",
"o",
"rmat(h",
",",
" ",
"m",
"r",
"o",
"und(s",
")",
")",
"",
""
] | 28.454545 | 23.727273 |
def reference_doi(self, index):
"""Return the reference DOI."""
return self.reference_data(index).get("DOI", self.reference_extra_field("DOI", index)) | [
"def",
"reference_doi",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"reference_data",
"(",
"index",
")",
".",
"get",
"(",
"\"DOI\"",
",",
"self",
".",
"reference_extra_field",
"(",
"\"DOI\"",
",",
"index",
")",
")"
] | 54.666667 | 21 |
def _calc_all_possible_moves(self, input_color):
"""
Returns list of all possible moves
:type: input_color: Color
:rtype: list
"""
for piece in self:
# Tests if square on the board is not empty
if piece is not None and piece.color == input_color:... | [
"def",
"_calc_all_possible_moves",
"(",
"self",
",",
"input_color",
")",
":",
"for",
"piece",
"in",
"self",
":",
"# Tests if square on the board is not empty",
"if",
"piece",
"is",
"not",
"None",
"and",
"piece",
".",
"color",
"==",
"input_color",
":",
"for",
"mo... | 38.694444 | 21.75 |
def getPlayer(name):
"""obtain a specific PlayerRecord settings file"""
if isinstance(name, PlayerRecord): return name
try: return getKnownPlayers()[name.lower()]
except KeyError:
raise ValueError("given player name '%s' is not a known player definition"%(name)) | [
"def",
"getPlayer",
"(",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"PlayerRecord",
")",
":",
"return",
"name",
"try",
":",
"return",
"getKnownPlayers",
"(",
")",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"raise"... | 47.333333 | 18.333333 |
def prox_zero(X, step):
"""Proximal operator to project onto zero
"""
return np.zeros(X.shape, dtype=X.dtype) | [
"def",
"prox_zero",
"(",
"X",
",",
"step",
")",
":",
"return",
"np",
".",
"zeros",
"(",
"X",
".",
"shape",
",",
"dtype",
"=",
"X",
".",
"dtype",
")"
] | 29.5 | 5 |
def lcs(self, stringIdxs=-1):
"""Returns the Largest Common Substring of Strings provided in stringIdxs.
If stringIdxs is not provided, the LCS of all strings is returned.
::param stringIdxs: Optional: List of indexes of strings.
"""
if stringIdxs == -1 or not isinstance(stringI... | [
"def",
"lcs",
"(",
"self",
",",
"stringIdxs",
"=",
"-",
"1",
")",
":",
"if",
"stringIdxs",
"==",
"-",
"1",
"or",
"not",
"isinstance",
"(",
"stringIdxs",
",",
"list",
")",
":",
"stringIdxs",
"=",
"set",
"(",
"range",
"(",
"len",
"(",
"self",
".",
... | 40.666667 | 17.4 |
def on_add_cols(self, event):
"""
Show simple dialog that allows user to add a new column name
"""
col_labels = self.grid.col_labels
dia = pw.ChooseOne(self, yes="Add single columns", no="Add groups")
result1 = dia.ShowModal()
if result1 == wx.ID_CANCEL:
... | [
"def",
"on_add_cols",
"(",
"self",
",",
"event",
")",
":",
"col_labels",
"=",
"self",
".",
"grid",
".",
"col_labels",
"dia",
"=",
"pw",
".",
"ChooseOne",
"(",
"self",
",",
"yes",
"=",
"\"Add single columns\"",
",",
"no",
"=",
"\"Add groups\"",
")",
"resu... | 40.204082 | 16.653061 |
def _render_line(self, line, settings):
"""
Render single box line.
"""
s = self._es(settings, self.SETTING_WIDTH, self.SETTING_FLAG_BORDER, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT)
width_content = self.calculate_width_widget_int(**s)
s =... | [
"def",
"_render_line",
"(",
"self",
",",
"line",
",",
"settings",
")",
":",
"s",
"=",
"self",
".",
"_es",
"(",
"settings",
",",
"self",
".",
"SETTING_WIDTH",
",",
"self",
".",
"SETTING_FLAG_BORDER",
",",
"self",
".",
"SETTING_MARGIN",
",",
"self",
".",
... | 37.583333 | 19.75 |
def ws_db004(self, value=None):
""" Corresponds to IDD Field `ws_db004`
Mean wind speed coincident with 0.4% dry-bulb temperature
Args:
value (float): value for IDD Field `ws_db004`
Unit: m/s
if `value` is None it will not be checked against the
... | [
"def",
"ws_db004",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float... | 35 | 20.285714 |
def sky2pix_vec(self, pos, r, pa):
"""
Convert a vector from sky to pixel coords.
The vector has a magnitude, angle, and an origin on the sky.
Parameters
----------
pos : (float, float)
The (ra, dec) of the origin of the vector (degrees).
r : float
... | [
"def",
"sky2pix_vec",
"(",
"self",
",",
"pos",
",",
"r",
",",
"pa",
")",
":",
"ra",
",",
"dec",
"=",
"pos",
"x",
",",
"y",
"=",
"self",
".",
"sky2pix",
"(",
"pos",
")",
"a",
"=",
"translate",
"(",
"ra",
",",
"dec",
",",
"r",
",",
"pa",
")",... | 29.65625 | 19.40625 |
def get_font_path(self):
"""Return the current font path as a list of strings."""
r = request.GetFontPath(display = self.display)
return r.paths | [
"def",
"get_font_path",
"(",
"self",
")",
":",
"r",
"=",
"request",
".",
"GetFontPath",
"(",
"display",
"=",
"self",
".",
"display",
")",
"return",
"r",
".",
"paths"
] | 41.25 | 12.25 |
def compile_create(self, blueprint, command, _):
"""
Compile a create table command.
"""
columns = ', '.join(self._get_columns(blueprint))
sql = 'CREATE TABLE %s (%s' % (self.wrap_table(blueprint), columns)
sql += self._add_foreign_keys(blueprint)
sql += self._... | [
"def",
"compile_create",
"(",
"self",
",",
"blueprint",
",",
"command",
",",
"_",
")",
":",
"columns",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"_get_columns",
"(",
"blueprint",
")",
")",
"sql",
"=",
"'CREATE TABLE %s (%s'",
"%",
"(",
"self",
".",
"... | 27.769231 | 19.461538 |
def Import(context, request):
""" Beckman Coulter Access 2 analysis results
"""
infile = request.form['rochecobas_taqman_model48_file']
fileformat = request.form['rochecobas_taqman_model48_format']
artoapply = request.form['rochecobas_taqman_model48_artoapply']
override = request.form['rochecoba... | [
"def",
"Import",
"(",
"context",
",",
"request",
")",
":",
"infile",
"=",
"request",
".",
"form",
"[",
"'rochecobas_taqman_model48_file'",
"]",
"fileformat",
"=",
"request",
".",
"form",
"[",
"'rochecobas_taqman_model48_format'",
"]",
"artoapply",
"=",
"request",
... | 36.716667 | 18.983333 |
def register_editor(self, editor, parent, ensure_uniqueness=False):
"""
Registers given :class:`umbra.components.factory.script_editor.editor.Editor` class editor in the Model.
:param editor: Editor to register.
:type editor: Editor
:param parent: EditorNode parent.
:typ... | [
"def",
"register_editor",
"(",
"self",
",",
"editor",
",",
"parent",
",",
"ensure_uniqueness",
"=",
"False",
")",
":",
"if",
"ensure_uniqueness",
":",
"if",
"self",
".",
"get_editor_nodes",
"(",
"editor",
")",
":",
"raise",
"foundations",
".",
"exceptions",
... | 36.9 | 20.5 |
def fluence(
power_mW,
color,
beam_radius,
reprate_Hz,
pulse_width,
color_units="wn",
beam_radius_units="mm",
pulse_width_units="fs_t",
area_type="even",
) -> tuple:
"""Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated p... | [
"def",
"fluence",
"(",
"power_mW",
",",
"color",
",",
"beam_radius",
",",
"reprate_Hz",
",",
"pulse_width",
",",
"color_units",
"=",
"\"wn\"",
",",
"beam_radius_units",
"=",
"\"mm\"",
",",
"pulse_width_units",
"=",
"\"fs_t\"",
",",
"area_type",
"=",
"\"even\"",
... | 32.536232 | 17.463768 |
def _load_int(self):
"""Load internal data from file and return it."""
values = numpy.fromfile(self.filepath_int)
if self.NDIM > 0:
values = values.reshape(self.seriesshape)
return values | [
"def",
"_load_int",
"(",
"self",
")",
":",
"values",
"=",
"numpy",
".",
"fromfile",
"(",
"self",
".",
"filepath_int",
")",
"if",
"self",
".",
"NDIM",
">",
"0",
":",
"values",
"=",
"values",
".",
"reshape",
"(",
"self",
".",
"seriesshape",
")",
"retur... | 37.666667 | 12.833333 |
def fine_tune_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
fine_tune_model_from_file_paths(model_archive_path=args.model_archive,
config_file=args.config_file,
... | [
"def",
"fine_tune_model_from_args",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
":",
"fine_tune_model_from_file_paths",
"(",
"model_archive_path",
"=",
"args",
".",
"model_archive",
",",
"config_file",
"=",
"args",
".",
"config_file",
",",
"serialization_dir"... | 61.583333 | 27.083333 |
def t_NAMESPACE(self, t):
r"([0-9a-zA-Z_])+(?=::)"
t.endlexpos = t.lexpos + len(t.value)
return t | [
"def",
"t_NAMESPACE",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"endlexpos",
"=",
"t",
".",
"lexpos",
"+",
"len",
"(",
"t",
".",
"value",
")",
"return",
"t"
] | 29.5 | 13 |
def calc_prob_mom(returns, other_returns):
"""
`Probabilistic momentum <http://cssanalytics.wordpress.com/2014/01/28/are-simple-momentum-strategies-too-dumb-introducing-probabilistic-momentum/>`_ (see `momentum investing <https://www.investopedia.com/terms/m/momentum_investing.asp>`_)
Basically the "probab... | [
"def",
"calc_prob_mom",
"(",
"returns",
",",
"other_returns",
")",
":",
"return",
"t",
".",
"cdf",
"(",
"returns",
".",
"calc_information_ratio",
"(",
"other_returns",
")",
",",
"len",
"(",
"returns",
")",
"-",
"1",
")"
] | 53.166667 | 38.166667 |
def fetch(self):
"""
Download a package
@returns: 0 = success or 1 if failed download
"""
#Default type to download
source = True
directory = "."
if self.options.file_type == "svn":
version = "dev"
svn_uri = get_download_uri(self... | [
"def",
"fetch",
"(",
"self",
")",
":",
"#Default type to download",
"source",
"=",
"True",
"directory",
"=",
"\".\"",
"if",
"self",
".",
"options",
".",
"file_type",
"==",
"\"svn\"",
":",
"version",
"=",
"\"dev\"",
"svn_uri",
"=",
"get_download_uri",
"(",
"s... | 31.914286 | 17.914286 |
def read_unsigned_var_int(file_obj):
"""Read a value using the unsigned, variable int encoding."""
result = 0
shift = 0
while True:
byte = struct.unpack(b"<B", file_obj.read(1))[0]
result |= ((byte & 0x7F) << shift)
if (byte & 0x80) == 0:
break
shift += 7
... | [
"def",
"read_unsigned_var_int",
"(",
"file_obj",
")",
":",
"result",
"=",
"0",
"shift",
"=",
"0",
"while",
"True",
":",
"byte",
"=",
"struct",
".",
"unpack",
"(",
"b\"<B\"",
",",
"file_obj",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"result",
... | 29.363636 | 16.181818 |
def visit_Boolean(self, node):
"""Visitor for `Boolean` AST node."""
if node.value == 'true':
return Bool(True)
elif node.value == 'false':
return Bool(False) | [
"def",
"visit_Boolean",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"value",
"==",
"'true'",
":",
"return",
"Bool",
"(",
"True",
")",
"elif",
"node",
".",
"value",
"==",
"'false'",
":",
"return",
"Bool",
"(",
"False",
")"
] | 33.5 | 7.333333 |
def spectral_entropy(X, Band, Fs, Power_Ratio=None):
"""Compute spectral entropy of a time series from either two cases below:
1. X, the time series (default)
2. Power_Ratio, a list of normalized signal power in a set of frequency
bins defined in Band (if Power_Ratio is provided, recommended to speed up... | [
"def",
"spectral_entropy",
"(",
"X",
",",
"Band",
",",
"Fs",
",",
"Power_Ratio",
"=",
"None",
")",
":",
"if",
"Power_Ratio",
"is",
"None",
":",
"Power",
",",
"Power_Ratio",
"=",
"bin_power",
"(",
"X",
",",
"Band",
",",
"Fs",
")",
"Spectral_Entropy",
"=... | 28.389831 | 26.898305 |
def entry_point(items=tuple()):
"""
External entry point which calls main() and
if Stop is raised, calls sys.exit()
"""
try:
if not items:
from .example import ExampleCommand
from .version import Version
items = [(ExampleCommand.NAME, ExampleCommand),
... | [
"def",
"entry_point",
"(",
"items",
"=",
"tuple",
"(",
")",
")",
":",
"try",
":",
"if",
"not",
"items",
":",
"from",
".",
"example",
"import",
"ExampleCommand",
"from",
".",
"version",
"import",
"Version",
"items",
"=",
"[",
"(",
"ExampleCommand",
".",
... | 27.521739 | 12.913043 |
def sample(self, nsims=1000):
""" Samples from the posterior predictive distribution
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
Returns
----------
- np.ndarray of draws from the data
... | [
"def",
"sample",
"(",
"self",
",",
"nsims",
"=",
"1000",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimation_method",
"not",
"in",
"[",
"'BBVI'",
",",
"'M-H'",
"]",
":",
"raise",
"Exception",
"(",
"\"No latent variables estimated!\"",
")",
"els... | 44.35 | 26.85 |
def remove_unnecessary_whitespace(css):
"""Remove unnecessary whitespace characters."""
def pseudoclasscolon(css):
"""
Prevents 'p :link' from becoming 'p:link'.
Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is
translated back again later.
"""
... | [
"def",
"remove_unnecessary_whitespace",
"(",
"css",
")",
":",
"def",
"pseudoclasscolon",
"(",
"css",
")",
":",
"\"\"\"\n Prevents 'p :link' from becoming 'p:link'.\n\n Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is\n translated back again later.\n ... | 31.707317 | 19.243902 |
def insert_penalty_model(cur, penalty_model):
"""Insert a penalty model into the database.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
penalty_model (:class:`penaltymodel.PenaltyModel`): A penalty
... | [
"def",
"insert_penalty_model",
"(",
"cur",
",",
"penalty_model",
")",
":",
"encoded_data",
"=",
"{",
"}",
"linear",
",",
"quadratic",
",",
"offset",
"=",
"penalty_model",
".",
"model",
".",
"to_ising",
"(",
")",
"nodelist",
"=",
"sorted",
"(",
"linear",
")... | 41.838235 | 21.352941 |
def _get_user(self, username, attrs=ALL_ATTRS):
"""Get a user from the ldap"""
username = ldap.filter.escape_filter_chars(username)
user_filter = self.user_filter_tmpl % {
'username': self._uni(username)
}
r = self._search(self._byte_p2(user_filter), attrs, self.user... | [
"def",
"_get_user",
"(",
"self",
",",
"username",
",",
"attrs",
"=",
"ALL_ATTRS",
")",
":",
"username",
"=",
"ldap",
".",
"filter",
".",
"escape_filter_chars",
"(",
"username",
")",
"user_filter",
"=",
"self",
".",
"user_filter_tmpl",
"%",
"{",
"'username'",... | 30.736842 | 18.631579 |
def scroll_to_bottom(self):
"""
Scoll to the very bottom of the page
TODO: add increment & delay options to scoll slowly down the whole page to let each section load in
"""
if self.driver.selenium is not None:
try:
self.driver.selenium.execute_script("... | [
"def",
"scroll_to_bottom",
"(",
"self",
")",
":",
"if",
"self",
".",
"driver",
".",
"selenium",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"driver",
".",
"selenium",
".",
"execute_script",
"(",
"\"window.scrollTo(0, document.body.scrollHeight);\"",
")",
... | 47.833333 | 21 |
def Version():
"""Gets the version of gdb as a 3-tuple.
The gdb devs seem to think it's a good idea to make --version
output multiple lines of welcome text instead of just the actual version,
so we ignore everything it outputs after the first line.
Returns:
The installed version of gdb in the... | [
"def",
"Version",
"(",
")",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'gdb'",
",",
"'--version'",
"]",
")",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
"# Example output (Arch linux):",
"# GNU gdb (GDB) 7.7",
"# Example output (Debian... | 36.522727 | 18.272727 |
def find_project_config_file(project_root: str) -> str:
"""Return absolute path to project-specific config file, if it exists.
:param project_root: Absolute path to project root directory.
A project config file is a file named `YCONFIG_FILE` found at the top
level of the project root dir.
Return ... | [
"def",
"find_project_config_file",
"(",
"project_root",
":",
"str",
")",
"->",
"str",
":",
"if",
"project_root",
":",
"project_config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"project_root",
",",
"YCONFIG_FILE",
")",
"if",
"os",
".",
"path",
".",
"... | 38 | 18.733333 |
def update_virtual_meta(self):
"""Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame."""
import astropy.units
try:
path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml")
... | [
"def",
"update_virtual_meta",
"(",
"self",
")",
":",
"import",
"astropy",
".",
"units",
"try",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"get_private_dir",
"(",
"create",
"=",
"False",
")",
",",
"\"virtual_meta.yaml\"",
")",
"if... | 55.058824 | 19.823529 |
def _getScaledValue(self, inpt):
"""
Convert the input, which is in normal space, into log space
"""
if inpt == SENTINEL_VALUE_FOR_MISSING_DATA:
return None
else:
val = inpt
if val < self.minval:
val = self.minval
elif val > self.maxval:
val = self.maxval
... | [
"def",
"_getScaledValue",
"(",
"self",
",",
"inpt",
")",
":",
"if",
"inpt",
"==",
"SENTINEL_VALUE_FOR_MISSING_DATA",
":",
"return",
"None",
"else",
":",
"val",
"=",
"inpt",
"if",
"val",
"<",
"self",
".",
"minval",
":",
"val",
"=",
"self",
".",
"minval",
... | 23.933333 | 15.666667 |
def image1(d, u, v, w, dmind, dtind, beamnum, irange):
""" Parallelizable function for imaging a chunk of data for a single dm.
Assumes data is dedispersed and resampled, so this just images each integration.
Simple one-stage imaging that returns dict of params.
returns dictionary with keys of cand loca... | [
"def",
"image1",
"(",
"d",
",",
"u",
",",
"v",
",",
"w",
",",
"dmind",
",",
"dtind",
",",
"beamnum",
",",
"irange",
")",
":",
"i0",
",",
"i1",
"=",
"irange",
"data_resamp",
"=",
"numpyview",
"(",
"data_resamp_mem",
",",
"'complex64'",
",",
"datashape... | 49.474359 | 23.666667 |
def _get_next_parent_node(self, parent):
""" Used by _get_next_child_node, this method is called to find next possible parent.
For example if timeperiod 2011010200 has all children processed, but is not yet processed itself
then it makes sense to look in 2011010300 for hourly nodes """
... | [
"def",
"_get_next_parent_node",
"(",
"self",
",",
"parent",
")",
":",
"grandparent",
"=",
"parent",
".",
"parent",
"if",
"grandparent",
"is",
"None",
":",
"# here, we work at yearly/linear level",
"return",
"None",
"parent_siblings",
"=",
"list",
"(",
"grandparent",... | 46.4375 | 15.375 |
def hsv_to_rgb(hsv):
"""
Vectorized HSV to RGB conversion, adapted from:
http://stackoverflow.com/questions/24852345/hsv-to-rgb-color-conversion
"""
h, s, v = (hsv[..., i] for i in range(3))
shape = h.shape
i = np.int_(h*6.)
f = h*6.-i
q = f
t = 1.-f
i = np.ravel(i)
f = ... | [
"def",
"hsv_to_rgb",
"(",
"hsv",
")",
":",
"h",
",",
"s",
",",
"v",
"=",
"(",
"hsv",
"[",
"...",
",",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
")",
"shape",
"=",
"h",
".",
"shape",
"i",
"=",
"np",
".",
"int_",
"(",
"h",
"*",
... | 23.428571 | 23.571429 |
def _normalize(self, key, value):
"""
Use normalize_<key> methods to normalize user input. Any user
input will be normalized at the moment it is used as filter,
or entered as a value of Task attribute.
"""
# None value should not be converted by normalizer
if val... | [
"def",
"_normalize",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# None value should not be converted by normalizer",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"normalize_func",
"=",
"getattr",
"(",
"self",
",",
"'normalize_{0}'",
".",
"format",
... | 32.933333 | 18.533333 |
def json_encode_default(obj):
'''
Convert datetime.datetime to timestamp
:param obj: value to (possibly) convert
'''
if isinstance(obj, (datetime, date)):
result = dt2ts(obj)
else:
result = json_encoder.default(obj)
return to_encoding(result) | [
"def",
"json_encode_default",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"datetime",
",",
"date",
")",
")",
":",
"result",
"=",
"dt2ts",
"(",
"obj",
")",
"else",
":",
"result",
"=",
"json_encoder",
".",
"default",
"(",
"obj",
")"... | 25.181818 | 16.272727 |
def PrivateKeyFromNEP2(nep2_key, passphrase):
"""
Gets the private key from a NEP-2 encrypted private key
Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
... | [
"def",
"PrivateKeyFromNEP2",
"(",
"nep2_key",
",",
"passphrase",
")",
":",
"if",
"not",
"nep2_key",
"or",
"len",
"(",
"nep2_key",
")",
"!=",
"58",
":",
"raise",
"ValueError",
"(",
"'Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'",
".",
"format",
"... | 40.22449 | 23.489796 |
def remove_line_interval(input_file: str, delete_line_from: int,
delete_line_to: int, output_file: str):
r"""Remove a line interval.
:parameter input_file: the file that needs to be read.
:parameter delete_line_from: the line number from which start deleting.
:parameter delete_... | [
"def",
"remove_line_interval",
"(",
"input_file",
":",
"str",
",",
"delete_line_from",
":",
"int",
",",
"delete_line_to",
":",
"int",
",",
"output_file",
":",
"str",
")",
":",
"assert",
"delete_line_from",
">=",
"1",
"assert",
"delete_line_to",
">=",
"1",
"wit... | 36.382979 | 20 |
def clipPolygons(self, polygons):
"""
Recursively remove all polygons in `polygons` that are inside this BSP
tree.
"""
if not self.plane:
return polygons[:]
front = []
back = []
for poly in polygons:
self.plane.splitPolygon(poly,... | [
"def",
"clipPolygons",
"(",
"self",
",",
"polygons",
")",
":",
"if",
"not",
"self",
".",
"plane",
":",
"return",
"polygons",
"[",
":",
"]",
"front",
"=",
"[",
"]",
"back",
"=",
"[",
"]",
"for",
"poly",
"in",
"polygons",
":",
"self",
".",
"plane",
... | 24.217391 | 20.434783 |
def write_to_cache(self, data, filename=''):
''' Writes data to file as JSON. Returns True. '''
if not filename:
filename = self.cache_path_cache
json_data = json.dumps(data)
with open(filename, 'w') as cache:
cache.write(json_data)
return True | [
"def",
"write_to_cache",
"(",
"self",
",",
"data",
",",
"filename",
"=",
"''",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"self",
".",
"cache_path_cache",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"with",
"open",
"(",
"fil... | 37.75 | 9.5 |
def absolute_abundance(coverage, total_bases):
"""
absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100
"""
absolute = {}
for genome in coverage:
absolute[genome] = []
index = 0
for calc in coverage[genome]:
bases = calc[0]
total = total_bases[index]
absolu... | [
"def",
"absolute_abundance",
"(",
"coverage",
",",
"total_bases",
")",
":",
"absolute",
"=",
"{",
"}",
"for",
"genome",
"in",
"coverage",
":",
"absolute",
"[",
"genome",
"]",
"=",
"[",
"]",
"index",
"=",
"0",
"for",
"calc",
"in",
"coverage",
"[",
"geno... | 28.857143 | 18.095238 |
def build_node_key_search(query, key) -> NodePredicate:
"""Build a node filter for nodes whose values for the given key are superstrings of the query string(s).
:param query: The query string or strings to check if they're in the node name
:type query: str or iter[str]
:param str key: The key for the n... | [
"def",
"build_node_key_search",
"(",
"query",
",",
"key",
")",
"->",
"NodePredicate",
":",
"if",
"isinstance",
"(",
"query",
",",
"str",
")",
":",
"return",
"build_node_data_search",
"(",
"key",
",",
"lambda",
"s",
":",
"query",
".",
"lower",
"(",
")",
"... | 49 | 26.785714 |
def get_interface_detail_output_interface_ifHCOutBroadcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "o... | [
"def",
"get_interface_detail_output_interface_ifHCOutBroadcastPkts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",... | 51.647059 | 20.411765 |
def _print_level(level, msg):
"""Print the information in Unicode safe manner."""
for l in str(msg.rstrip()).split("\n"):
print("{0:<9s}{1}".format(level, str(l))) | [
"def",
"_print_level",
"(",
"level",
",",
"msg",
")",
":",
"for",
"l",
"in",
"str",
"(",
"msg",
".",
"rstrip",
"(",
")",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"print",
"(",
"\"{0:<9s}{1}\"",
".",
"format",
"(",
"level",
",",
"str",
"(",
"l... | 44 | 5.75 |
def hmac(key, message, tag=None, alg=hashlib.sha256):
"""
Generates a hashed message authentication code (HMAC) by prepending the
specified @tag string to a @message, then hashing with to HMAC
using a cryptographic @key and hashing @alg -orithm.
"""
return HMAC.new(str(key), str(tag) + str(mess... | [
"def",
"hmac",
"(",
"key",
",",
"message",
",",
"tag",
"=",
"None",
",",
"alg",
"=",
"hashlib",
".",
"sha256",
")",
":",
"return",
"HMAC",
".",
"new",
"(",
"str",
"(",
"key",
")",
",",
"str",
"(",
"tag",
")",
"+",
"str",
"(",
"message",
")",
... | 49 | 18.428571 |
def send_and_wait(self, message, params=None, timeout=10, raises=False):
"""Send service method request and wait for response
:param message:
proto message instance (use :meth:`SteamUnifiedMessages.get`)
or method name (e.g. ``Player.GetGameBadgeLevels#1``)
:type message... | [
"def",
"send_and_wait",
"(",
"self",
",",
"message",
",",
"params",
"=",
"None",
",",
"timeout",
"=",
"10",
",",
"raises",
"=",
"False",
")",
":",
"job_id",
"=",
"self",
".",
"send",
"(",
"message",
",",
"params",
")",
"resp",
"=",
"self",
".",
"wa... | 49.3 | 16.95 |
def lookup(self, name: str):
'''lookup a symbol by fully qualified name.'''
# <module>
if name in self._moduleMap:
return self._moduleMap[name]
# <module>.<Symbol>
(module_name, type_name, fragment_name) = self.split_typename(name)
if not module_name and type_... | [
"def",
"lookup",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"# <module>",
"if",
"name",
"in",
"self",
".",
"_moduleMap",
":",
"return",
"self",
".",
"_moduleMap",
"[",
"name",
"]",
"# <module>.<Symbol>",
"(",
"module_name",
",",
"type_name",
",",
"f... | 43.333333 | 14.833333 |
def transitions_for(self, roles=None, actor=None, anchors=[]):
"""
For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes:
returns currently available transitions for the specified
roles or actor as a dictionary of name: :class:`StateTransitionWrapper`.
"""
prox... | [
"def",
"transitions_for",
"(",
"self",
",",
"roles",
"=",
"None",
",",
"actor",
"=",
"None",
",",
"anchors",
"=",
"[",
"]",
")",
":",
"proxy",
"=",
"self",
".",
"obj",
".",
"access_for",
"(",
"roles",
",",
"actor",
",",
"anchors",
")",
"return",
"{... | 53.888889 | 22.777778 |
def check_who_am_i(self):
"""
This method checks verifies the device ID.
@return: True if valid, False if not
"""
register = self.MMA8452Q_Register['WHO_AM_I']
self.board.i2c_read_request(self.address, register, 1,
Constants.I2C_READ |... | [
"def",
"check_who_am_i",
"(",
"self",
")",
":",
"register",
"=",
"self",
".",
"MMA8452Q_Register",
"[",
"'WHO_AM_I'",
"]",
"self",
".",
"board",
".",
"i2c_read_request",
"(",
"self",
".",
"address",
",",
"register",
",",
"1",
",",
"Constants",
".",
"I2C_RE... | 31 | 21 |
def _install_interrupt_handler():
"""Suppress KeyboardInterrupt traceback display in specific situations
If not running in dev mode, and if executed from the command line, then
we raise SystemExit instead of KeyboardInterrupt. This provides a clean
exit.
:returns: None if no action is taken, orig... | [
"def",
"_install_interrupt_handler",
"(",
")",
":",
"# These would clutter the quilt.x namespace, so they're imported here instead.",
"import",
"os",
"import",
"sys",
"import",
"signal",
"import",
"pkg_resources",
"from",
".",
"tools",
"import",
"const",
"# Check to see what en... | 44.724138 | 24.844828 |
def get_record(self, fileName, ref_extract_callback=None):
"""
Gets the Marc xml of the files in xaml_jp directory
:param fileName: the name of the file to parse.
:type fileName: string
:param refextract_callback: callback to be used to extract
... | [
"def",
"get_record",
"(",
"self",
",",
"fileName",
",",
"ref_extract_callback",
"=",
"None",
")",
":",
"self",
".",
"document",
"=",
"parse",
"(",
"fileName",
")",
"article_type",
"=",
"self",
".",
"_get_article_type",
"(",
")",
"if",
"article_type",
"not",
... | 44.81982 | 17.162162 |
def get_wireframe(viewer, x, y, z, **kwargs):
"""Produce a compound object of paths implementing a wireframe.
x, y, z are expected to be 2D arrays of points making up the mesh.
"""
# TODO: something like this would make a great utility function
# for ginga
n, m = x.shape
objs = []
for i ... | [
"def",
"get_wireframe",
"(",
"viewer",
",",
"x",
",",
"y",
",",
"z",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: something like this would make a great utility function",
"# for ginga",
"n",
",",
"m",
"=",
"x",
".",
"shape",
"objs",
"=",
"[",
"]",
"for",
"... | 36 | 16.315789 |
def m2o_to_x2m(cr, model, table, field, source_field):
"""
Transform many2one relations into one2many or many2many.
Use rename_columns in your pre-migrate script to retain the column's old
value, then call m2o_to_x2m in your post-migrate script.
WARNING: If converting to one2many, there can be data... | [
"def",
"m2o_to_x2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")",
":",
"columns",
"=",
"getattr",
"(",
"model",
",",
"'_columns'",
",",
"False",
")",
"or",
"getattr",
"(",
"model",
",",
"'_fields'",
")",
"if",
"not",
... | 39.338028 | 17.746479 |
def taf(trans: TafLineTrans) -> str:
"""
Condense the translation strings into a single forecast summary string
"""
summary = []
if trans.wind:
summary.append('Winds ' + trans.wind)
if trans.visibility:
summary.append('Vis ' + trans.visibility[:trans.visibility.find(' (')].lower(... | [
"def",
"taf",
"(",
"trans",
":",
"TafLineTrans",
")",
"->",
"str",
":",
"summary",
"=",
"[",
"]",
"if",
"trans",
".",
"wind",
":",
"summary",
".",
"append",
"(",
"'Winds '",
"+",
"trans",
".",
"wind",
")",
"if",
"trans",
".",
"visibility",
":",
"su... | 34.818182 | 15.818182 |
def repost(self, token):
"""
Repost the job if it has timed out
(:py:data:`cloudsight.STATUS_TIMEOUT`).
:param token: Job token as returned from
:py:meth:`cloudsight.API.image_request` or
:py:meth:`cloudsight.API.remote_image_request`
... | [
"def",
"repost",
"(",
"self",
",",
"token",
")",
":",
"url",
"=",
"'%s/%s/repost'",
"%",
"(",
"REQUESTS_URL",
",",
"token",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"{",
"'Authorization'",
":",
"self",
".",
"auth"... | 33 | 16.263158 |
def set_ylim_cb(self, redraw=True):
"""Set plot limit based on user values."""
try:
ymin = float(self.w.y_lo.get_text())
except Exception:
set_min = True
else:
set_min = False
try:
ymax = float(self.w.y_hi.get_text())
excep... | [
"def",
"set_ylim_cb",
"(",
"self",
",",
"redraw",
"=",
"True",
")",
":",
"try",
":",
"ymin",
"=",
"float",
"(",
"self",
".",
"w",
".",
"y_lo",
".",
"get_text",
"(",
")",
")",
"except",
"Exception",
":",
"set_min",
"=",
"True",
"else",
":",
"set_min... | 27.625 | 17.375 |
def get_subgraphs_by_annotation(graph, annotation, sentinel=None):
"""Stratify the given graph into sub-graphs based on the values for edges' annotations.
:param pybel.BELGraph graph: A BEL graph
:param str annotation: The annotation to group by
:param Optional[str] sentinel: The value to stick unannot... | [
"def",
"get_subgraphs_by_annotation",
"(",
"graph",
",",
"annotation",
",",
"sentinel",
"=",
"None",
")",
":",
"if",
"sentinel",
"is",
"not",
"None",
":",
"subgraphs",
"=",
"_get_subgraphs_by_annotation_keep_undefined",
"(",
"graph",
",",
"annotation",
",",
"senti... | 42.0625 | 25.6875 |
def create_api_environment(self):
"""Get an instance of Api Environment services facade."""
return ApiEnvironment(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_api_environment",
"(",
"self",
")",
":",
"return",
"ApiEnvironment",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 33.571429 | 10 |
def get_n_tail(tmax, tail_temps):
"""determines number of included tail checks in best fit segment"""
#print "tail_temps: {0}, tmax: {0}".format(tail_temps, tmax)
t_index = 0
adj_tmax = 0
if tmax < tail_temps[0]:
return 0
try:
t_index = list(tail_temps).index(tmax)
except: # ... | [
"def",
"get_n_tail",
"(",
"tmax",
",",
"tail_temps",
")",
":",
"#print \"tail_temps: {0}, tmax: {0}\".format(tail_temps, tmax)",
"t_index",
"=",
"0",
"adj_tmax",
"=",
"0",
"if",
"tmax",
"<",
"tail_temps",
"[",
"0",
"]",
":",
"return",
"0",
"try",
":",
"t_index",... | 37.5 | 16.5625 |
def setLedN(self, led_number=0):
"""Set the 'current LED' value for writePatternLine
:param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB
"""
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('l'), led_number, 0,0,0,0,0,0]
self.write(buf) | [
"def",
"setLedN",
"(",
"self",
",",
"led_number",
"=",
"0",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"buf",
"=",
"[",
"REPORT_ID",
",",
"ord",
"(",
"'l'",
")",
",",
"led_number",
",",
"0",
",",
"0",
",",
... | 41.428571 | 10 |
def Session(access_token=None, env=None):
"""Create an HTTP session.
Parameters
----------
access_token : str
Mapbox access token string (optional).
env : dict, optional
A dict that subsitutes for os.environ.
Returns
-------
requests.Session
"""
if env is None:
... | [
"def",
"Session",
"(",
"access_token",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"access_token",
"=",
"(",
"access_token",
"or",
"env",
".",
"get",
"(",
... | 27.038462 | 16 |
def compute(self):
"""Computes the tendencies for all state variables given current state
and specified input.
The function first computes all diagnostic processes. They don't produce
any tendencies directly but they may affect the other processes (such as
change in solar distri... | [
"def",
"compute",
"(",
"self",
")",
":",
"# First reset tendencies to zero -- recomputing them is the point of this method",
"for",
"varname",
"in",
"self",
".",
"tendencies",
":",
"self",
".",
"tendencies",
"[",
"varname",
"]",
"*=",
"0.",
"if",
"not",
"self",
"."... | 52.414634 | 23.987805 |
def _sbd(x, y):
"""
>>> _sbd([1,1,1], [1,1,1])
(-2.2204460492503131e-16, array([1, 1, 1]))
>>> _sbd([0,1,2], [1,2,3])
(0.043817112532485103, array([1, 2, 3]))
>>> _sbd([1,2,3], [0,1,2])
(0.043817112532485103, array([0, 1, 2]))
"""
ncc = _ncc_c(x, y)
idx = ncc.argmax()
dist = ... | [
"def",
"_sbd",
"(",
"x",
",",
"y",
")",
":",
"ncc",
"=",
"_ncc_c",
"(",
"x",
",",
"y",
")",
"idx",
"=",
"ncc",
".",
"argmax",
"(",
")",
"dist",
"=",
"1",
"-",
"ncc",
"[",
"idx",
"]",
"yshift",
"=",
"roll_zeropad",
"(",
"y",
",",
"(",
"idx",... | 27 | 13.4 |
def generate_raml_docs(module, fields, shared_types, user=None, title="My API", version="v1", api_root="api", base_uri="http://mysite.com/{version}"):
"""Return a RAML file of a Pale module's documentation as a string.
The user argument is optional. If included, it expects the user to be an object with an "is_... | [
"def",
"generate_raml_docs",
"(",
"module",
",",
"fields",
",",
"shared_types",
",",
"user",
"=",
"None",
",",
"title",
"=",
"\"My API\"",
",",
"version",
"=",
"\"v1\"",
",",
"api_root",
"=",
"\"api\"",
",",
"base_uri",
"=",
"\"http://mysite.com/{version}\"",
... | 37.206349 | 24.650794 |
def activation_shell_code(self, shell=None):
"""Get shell code that should be run to activate this suite."""
from rez.shells import create_shell
from rez.rex import RexExecutor
executor = RexExecutor(interpreter=create_shell(shell),
parent_variables=["PATH... | [
"def",
"activation_shell_code",
"(",
"self",
",",
"shell",
"=",
"None",
")",
":",
"from",
"rez",
".",
"shells",
"import",
"create_shell",
"from",
"rez",
".",
"rex",
"import",
"RexExecutor",
"executor",
"=",
"RexExecutor",
"(",
"interpreter",
"=",
"create_shell... | 45.5 | 10.6 |
def generate(env):
"""Add Builders and construction variables for dvips to an Environment."""
global PSAction
if PSAction is None:
PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR')
global DVIPSAction
if DVIPSAction is None:
DVIPSAction = SCons.Action.Action(DviPsFunction, strfun... | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"PSAction",
"if",
"PSAction",
"is",
"None",
":",
"PSAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$PSCOM'",
",",
"'$PSCOMSTR'",
")",
"global",
"DVIPSAction",
"if",
"DVIPSAction",
"is",
"None"... | 43.214286 | 24.642857 |
def get_parallel_raw_data(self, other):
""" Get the raw data that is similar to the specified other segment
"""
start, end = other.byte_bounds_offset()
r = self.rawdata[start:end]
if other.rawdata.is_indexed:
r = r.get_indexed[other.order]
return r | [
"def",
"get_parallel_raw_data",
"(",
"self",
",",
"other",
")",
":",
"start",
",",
"end",
"=",
"other",
".",
"byte_bounds_offset",
"(",
")",
"r",
"=",
"self",
".",
"rawdata",
"[",
"start",
":",
"end",
"]",
"if",
"other",
".",
"rawdata",
".",
"is_indexe... | 37.625 | 5.375 |
def load_text(self, text, tokenizer=None):
""" Load text from which to generate a word frequency list
Args:
text (str): The text to be loaded
tokenizer (function): The function to use to tokenize a string
"""
if tokenizer:
words = [x.lower... | [
"def",
"load_text",
"(",
"self",
",",
"text",
",",
"tokenizer",
"=",
"None",
")",
":",
"if",
"tokenizer",
":",
"words",
"=",
"[",
"x",
".",
"lower",
"(",
")",
"for",
"x",
"in",
"tokenizer",
"(",
"text",
")",
"]",
"else",
":",
"words",
"=",
"self"... | 33.071429 | 16 |
def _enforce_instance(model_or_class):
"""
It's a common mistake to not initialize a
schematics class. We should handle that by just
calling the default constructor.
"""
if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType):
return model_or_class()
return model... | [
"def",
"_enforce_instance",
"(",
"model_or_class",
")",
":",
"if",
"isinstance",
"(",
"model_or_class",
",",
"type",
")",
"and",
"issubclass",
"(",
"model_or_class",
",",
"BaseType",
")",
":",
"return",
"model_or_class",
"(",
")",
"return",
"model_or_class"
] | 35.666667 | 9.666667 |
def handle_stream_features(self, stream, features):
"""Process incoming <stream:features/> element.
[initiating entity only]
The received features element is available in `features`.
"""
logger.debug(u"Handling stream features: {0}".format(
... | [
"def",
"handle_stream_features",
"(",
"self",
",",
"stream",
",",
"features",
")",
":",
"logger",
".",
"debug",
"(",
"u\"Handling stream features: {0}\"",
".",
"format",
"(",
"element_to_unicode",
"(",
"features",
")",
")",
")",
"element",
"=",
"features",
".",
... | 40.25 | 16.5 |
def aggregate_periods(self, periods):
"""Returns list of ndarrays averaged to a given number of periods.
Arguments:
periods -- desired number of periods as int
"""
try:
fieldname = self.raster_field.name
except TypeError:
raise exceptions.FieldDoe... | [
"def",
"aggregate_periods",
"(",
"self",
",",
"periods",
")",
":",
"try",
":",
"fieldname",
"=",
"self",
".",
"raster_field",
".",
"name",
"except",
"TypeError",
":",
"raise",
"exceptions",
".",
"FieldDoesNotExist",
"(",
"'Raster field not found'",
")",
"arrays"... | 37.615385 | 16.269231 |
def recover(
data: bytes,
signature: Signature,
hasher: Callable[[bytes], bytes] = eth_sign_sha3,
) -> Address:
""" eth_recover address from data hash and signature """
_hash = hasher(data)
# ecdsa_recover accepts only standard [0,1] v's so we add support also for [27,28] here
#... | [
"def",
"recover",
"(",
"data",
":",
"bytes",
",",
"signature",
":",
"Signature",
",",
"hasher",
":",
"Callable",
"[",
"[",
"bytes",
"]",
",",
"bytes",
"]",
"=",
"eth_sign_sha3",
",",
")",
"->",
"Address",
":",
"_hash",
"=",
"hasher",
"(",
"data",
")"... | 38.421053 | 21.368421 |
def members(name, members_list, root=None):
'''
Replaces members of the group with a provided list.
CLI Example:
salt '*' group.members foo 'user1,user2,user3,...'
Replaces a membership list for a local group 'foo'.
foo:x:1234:user1,user2,user3,...
'''
cmd = 'chgrpmem -m = {0}... | [
"def",
"members",
"(",
"name",
",",
"members_list",
",",
"root",
"=",
"None",
")",
":",
"cmd",
"=",
"'chgrpmem -m = {0} {1}'",
".",
"format",
"(",
"members_list",
",",
"name",
")",
"retcode",
"=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"... | 28.333333 | 24.066667 |
def validate_metadata(self, handler):
""" validate that kind=category does not change the categories """
if self.meta == 'category':
new_metadata = self.metadata
cur_metadata = handler.read_metadata(self.cname)
if (new_metadata is not None and cur_metadata is not None... | [
"def",
"validate_metadata",
"(",
"self",
",",
"handler",
")",
":",
"if",
"self",
".",
"meta",
"==",
"'category'",
":",
"new_metadata",
"=",
"self",
".",
"metadata",
"cur_metadata",
"=",
"handler",
".",
"read_metadata",
"(",
"self",
".",
"cname",
")",
"if",... | 58.777778 | 16.777778 |
def ascwl(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
basedir=None,
):
"""Return the ``attrs`` attribute values of *inst* as a dict.
Support ``jsonldPredicate`` in a field metadata for generating
mappings from lists.
Adapted from ``attr._... | [
"def",
"ascwl",
"(",
"inst",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"None",
",",
"dict_factory",
"=",
"dict",
",",
"retain_collection_types",
"=",
"False",
",",
"basedir",
"=",
"None",
",",
")",
":",
"attrs",
"=",
"fields",
"(",
"inst",
".",
... | 30.091954 | 15.54023 |
def get(self, request, *args, **kwargs):
"""
Return a :class:`.django.http.JsonResponse`.
Example::
{
'results': [
{
'text': "foo",
'id': 123
}
],
... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"widget",
"=",
"self",
".",
"get_widget_or_404",
"(",
")",
"self",
".",
"term",
"=",
"kwargs",
".",
"get",
"(",
"'term'",
",",
"request",
... | 27.612903 | 16.709677 |
def evaluate(dataset, predictions, output_folder, **kwargs):
"""evaluate dataset using different methods based on dataset type.
Args:
dataset: Dataset object
predictions(list[BoxList]): each item in the list represents the
prediction results for one image.
output_folder: outp... | [
"def",
"evaluate",
"(",
"dataset",
",",
"predictions",
",",
"output_folder",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"dict",
"(",
"dataset",
"=",
"dataset",
",",
"predictions",
"=",
"predictions",
",",
"output_folder",
"=",
"output_folder",
",",
"*... | 41.238095 | 19.380952 |
def save_animation(filename, pianoroll, window, hop=1, fps=None, is_drum=False,
beat_resolution=None, downbeats=None, preset='default',
cmap='Blues', xtick='auto', ytick='octave', xticklabel=True,
yticklabel='auto', tick_loc=None, tick_direction='in',
... | [
"def",
"save_animation",
"(",
"filename",
",",
"pianoroll",
",",
"window",
",",
"hop",
"=",
"1",
",",
"fps",
"=",
"None",
",",
"is_drum",
"=",
"False",
",",
"beat_resolution",
"=",
"None",
",",
"downbeats",
"=",
"None",
",",
"preset",
"=",
"'default'",
... | 44.315789 | 22.763158 |
def index_of(self, name):
"""
Returns the index of the actor with the given name.
:param name: the name of the Actor to find
:type name: str
:return: the index, -1 if not found
:rtype: int
"""
result = -1
for index, actor in enumerate(self.actors)... | [
"def",
"index_of",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"-",
"1",
"for",
"index",
",",
"actor",
"in",
"enumerate",
"(",
"self",
".",
"actors",
")",
":",
"if",
"actor",
".",
"name",
"==",
"name",
":",
"result",
"=",
"index",
"break",
... | 27.8 | 14.066667 |
def reduce_fn(x):
"""
Aggregation function to get the first non-zero value.
"""
values = x.values if pd and isinstance(x, pd.Series) else x
for v in values:
if not is_nan(v):
return v
return np.NaN | [
"def",
"reduce_fn",
"(",
"x",
")",
":",
"values",
"=",
"x",
".",
"values",
"if",
"pd",
"and",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Series",
")",
"else",
"x",
"for",
"v",
"in",
"values",
":",
"if",
"not",
"is_nan",
"(",
"v",
")",
":",
"retur... | 25.888889 | 15.666667 |
def main(global_config, **settings):
"""
Get a PyShop WSGI application configured with settings.
"""
if sys.version_info[0] < 3:
reload(sys)
sys.setdefaultencoding('utf-8')
settings = dict(settings)
# Scoping sessions for Pyramid ensure session are commit/rollback
# after th... | [
"def",
"main",
"(",
"global_config",
",",
"*",
"*",
"settings",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"reload",
"(",
"sys",
")",
"sys",
".",
"setdefaultencoding",
"(",
"'utf-8'",
")",
"settings",
"=",
"dict",
"(",
... | 36.333333 | 17.074074 |
def addTags(self, tags):
"""Adds the list of tags to current tags. (flickr.photos.addtags)
"""
method = 'flickr.photos.addTags'
if isinstance(tags, list):
tags = uniq(tags)
_dopost(method, auth=True, photo_id=self.id, tags=tags)
#load properties again
... | [
"def",
"addTags",
"(",
"self",
",",
"tags",
")",
":",
"method",
"=",
"'flickr.photos.addTags'",
"if",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"tags",
"=",
"uniq",
"(",
"tags",
")",
"_dopost",
"(",
"method",
",",
"auth",
"=",
"True",
",",
"p... | 33.5 | 11.5 |
def _MakeRanges(pairs):
"""Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]."""
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
... | [
"def",
"_MakeRanges",
"(",
"pairs",
")",
":",
"ranges",
"=",
"[",
"]",
"last",
"=",
"-",
"100",
"def",
"evenodd",
"(",
"last",
",",
"a",
",",
"b",
",",
"r",
")",
":",
"if",
"a",
"!=",
"last",
"+",
"1",
"or",
"b",
"!=",
"_AddDelta",
"(",
"a",
... | 20.947368 | 20.921053 |
def get_calendar_events(self, **kwargs):
"""
List calendar events.
:calls: `GET /api/v1/calendar_events \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:cla... | [
"def",
"get_calendar_events",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"calendar_event",
"import",
"CalendarEvent",
"return",
"PaginatedList",
"(",
"CalendarEvent",
",",
"self",
".",
"__requester",
",",
"'GET'",
",",
"'calendar_e... | 32.052632 | 19.315789 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return TaggerId(key)
if key not in TaggerId._member_map_:
extend_enum(TaggerId, key, default)
return TaggerId[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"TaggerId",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"TaggerId",
".",
"_member_map_",
":",
"extend_enum",
"(",
"Tag... | 36.857143 | 7.714286 |
def get_tasks(self, task_id=None, state='completed', json_file=None):
"""Load all project Tasks."""
if self.project is None:
raise ProjectError
loader = create_tasks_loader(self.project.id, task_id,
state, json_file, self.all)
self.tasks ... | [
"def",
"get_tasks",
"(",
"self",
",",
"task_id",
"=",
"None",
",",
"state",
"=",
"'completed'",
",",
"json_file",
"=",
"None",
")",
":",
"if",
"self",
".",
"project",
"is",
"None",
":",
"raise",
"ProjectError",
"loader",
"=",
"create_tasks_loader",
"(",
... | 39.181818 | 18.545455 |
def _initialize(g=globals()):
"Set up global resource manager (deliberately not state-saved)"
manager = ResourceManager()
g['_manager'] = manager
for name in dir(manager):
if not name.startswith('_'):
g[name] = getattr(manager, name) | [
"def",
"_initialize",
"(",
"g",
"=",
"globals",
"(",
")",
")",
":",
"manager",
"=",
"ResourceManager",
"(",
")",
"g",
"[",
"'_manager'",
"]",
"=",
"manager",
"for",
"name",
"in",
"dir",
"(",
"manager",
")",
":",
"if",
"not",
"name",
".",
"startswith"... | 37.571429 | 11.285714 |
def erase_text(self, locator, click=True, clear=False, backspace=0, params=None):
"""
Various ways to erase text from web element.
:param locator: locator tuple or WebElement instance
:param click: clicks the input field
:param clear: clears the input field
:param backsp... | [
"def",
"erase_text",
"(",
"self",
",",
"locator",
",",
"click",
"=",
"True",
",",
"clear",
"=",
"False",
",",
"backspace",
"=",
"0",
",",
"params",
"=",
"None",
")",
":",
"element",
"=",
"locator",
"if",
"not",
"isinstance",
"(",
"element",
",",
"Web... | 32.307692 | 17.153846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.