text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _make_request(self, method, endpoint, **kwargs):
"""
Do the actual request with supplied HTTP method
:param method: HTTP method
:param endpoint: DHIS2 API endpoint
:param kwargs: keyword args
:return: response if ok, RequestException if not
"""
if isin... | [
"def",
"_make_request",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"kwargs",
".",
"get",
"(",
"'file_type'",
")",
",",
"string_types",
")",
":",
"file_type",
"=",
"kwargs",
"[",
"'file_type'",... | 35.25641 | 19.769231 |
def register_new_suffix_tree(case_insensitive=False):
"""Factory method, returns new suffix tree object.
"""
assert isinstance(case_insensitive, bool)
root_node = register_new_node()
suffix_tree_id = uuid4()
event = SuffixTree.Created(
originator_id=suffix_tree_id,
root_node_id=... | [
"def",
"register_new_suffix_tree",
"(",
"case_insensitive",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"case_insensitive",
",",
"bool",
")",
"root_node",
"=",
"register_new_node",
"(",
")",
"suffix_tree_id",
"=",
"uuid4",
"(",
")",
"event",
"=",
"Suffi... | 25.333333 | 16.238095 |
def top(self, **kwargs):
"""
Display the running processes of the container.
Args:
ps_args (str): An optional arguments passed to ps (e.g. ``aux``)
Returns:
(str): The output of the top
Raises:
:py:class:`docker.errors.APIError`
... | [
"def",
"top",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"api",
".",
"top",
"(",
"self",
".",
"id",
",",
"*",
"*",
"kwargs",
")"
] | 27.133333 | 19.266667 |
def show_xys(self, xs, ys)->None:
"Show the `xs` (inputs) and `ys` (targets)."
from IPython.display import display, HTML
items,names = [], xs[0].names + ['target']
for i, (x,y) in enumerate(zip(xs,ys)):
res = []
cats = x.cats if len(x.cats.size()) > 0 else []
... | [
"def",
"show_xys",
"(",
"self",
",",
"xs",
",",
"ys",
")",
"->",
"None",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
",",
"HTML",
"items",
",",
"names",
"=",
"[",
"]",
",",
"xs",
"[",
"0",
"]",
".",
"names",
"+",
"[",
"'target'",... | 48.375 | 14.25 |
def readShiftFile(self, filename):
"""
Reads a shift file from disk and populates a dictionary.
"""
order = []
fshift = open(filename,'r')
flines = fshift.readlines()
fshift.close()
common = [f.strip('#').strip() for f in flines if f.startswith('#')]
... | [
"def",
"readShiftFile",
"(",
"self",
",",
"filename",
")",
":",
"order",
"=",
"[",
"]",
"fshift",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"flines",
"=",
"fshift",
".",
"readlines",
"(",
")",
"fshift",
".",
"close",
"(",
")",
"common",
"=",
"... | 39.716667 | 22.016667 |
def query(name, use_kerberos=None, debug=False):
"""Query the Channel Information System for details on the given
channel name
Parameters
----------
name : `~gwpy.detector.Channel`, or `str`
Name of the channel of interest
Returns
-------
channel : `~gwpy.detector.Channel`
... | [
"def",
"query",
"(",
"name",
",",
"use_kerberos",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"url",
"=",
"'%s/?q=%s'",
"%",
"(",
"CIS_API_URL",
",",
"name",
")",
"more",
"=",
"True",
"out",
"=",
"ChannelList",
"(",
")",
"while",
"more",
":",
... | 28.181818 | 18.030303 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
deploy
/deployments/<id>/deploy
``super`` is called otherwise.
"""
if which == 'deploy':
return '{0}... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"==",
"'deploy'",
":",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"super",
"(",
"RHCIDeployment",
",",
"self",
")",
".",
"path",
"(",
"which",
"=",
"'self'",
")",
",",
... | 27.764706 | 19.823529 |
def autoscroll(self, autoscroll):
"""Autoscroll will 'right justify' text from the cursor if set True,
otherwise it will 'left justify' the text.
"""
if autoscroll:
self.displaymode |= LCD_ENTRYSHIFTINCREMENT
else:
self.displaymode &= ~LCD_ENTRYSHIFTINCREM... | [
"def",
"autoscroll",
"(",
"self",
",",
"autoscroll",
")",
":",
"if",
"autoscroll",
":",
"self",
".",
"displaymode",
"|=",
"LCD_ENTRYSHIFTINCREMENT",
"else",
":",
"self",
".",
"displaymode",
"&=",
"~",
"LCD_ENTRYSHIFTINCREMENT",
"self",
".",
"write8",
"(",
"LCD... | 41.333333 | 12.111111 |
def explain_prediction_linear_classifier(clf, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets... | [
"def",
"explain_prediction_linear_classifier",
"(",
"clf",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",... | 38.939024 | 19.573171 |
def emit(self, value):
"""Emits a value to output writer.
Args:
value: a value of type expected by the output writer.
"""
if not self._tstate.output_writer:
logging.error("emit is called, but no output writer is set.")
return
self._tstate.output_writer.write(value) | [
"def",
"emit",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_tstate",
".",
"output_writer",
":",
"logging",
".",
"error",
"(",
"\"emit is called, but no output writer is set.\"",
")",
"return",
"self",
".",
"_tstate",
".",
"output_writer",
"... | 29.5 | 16.8 |
def _build_generator_list(network):
"""Builds DataFrames with all generators in MV and LV grids
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to MV generators
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and refere... | [
"def",
"_build_generator_list",
"(",
"network",
")",
":",
"genos_mv",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"(",
"'id'",
",",
"'obj'",
")",
")",
"genos_lv",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"(",
"'id'",
",",
"'obj'",
")",
... | 38.272727 | 18.212121 |
def mousePressEvent(self, event):
"""Override Qt method
Add/remove breakpoints by single click.
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
shift = event.modifiers() & Qt.ShiftModifier
self.editor.debugger.toogle_breakpoint(line_number,
... | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"line_number",
"=",
"self",
".",
"editor",
".",
"get_linenumber_from_mouse_event",
"(",
"event",
")",
"shift",
"=",
"event",
".",
"modifiers",
"(",
")",
"&",
"Qt",
".",
"ShiftModifier",
"self",
... | 41.222222 | 16.111111 |
def structure(cls):
# type: () -> Text
"""Get the part structure, as a DNA regex pattern.
The structure of most parts can be obtained automatically from the
part signature and the restriction enzyme used in the Golden Gate
assembly.
Warning:
If overloading t... | [
"def",
"structure",
"(",
"cls",
")",
":",
"# type: () -> Text",
"if",
"cls",
".",
"signature",
"is",
"NotImplemented",
":",
"raise",
"NotImplementedError",
"(",
"\"no signature defined\"",
")",
"up",
"=",
"cls",
".",
"cutter",
".",
"elucidate",
"(",
")",
"down... | 34.039216 | 20.72549 |
def parse_rawprofile_blocks(text):
"""
Split the file into blocks along delimters and and put delimeters back in
the list
"""
# The total time reported in the raw output is from pystone not kernprof
# The pystone total time is actually the average time spent in the function
delim = 'Total ti... | [
"def",
"parse_rawprofile_blocks",
"(",
"text",
")",
":",
"# The total time reported in the raw output is from pystone not kernprof",
"# The pystone total time is actually the average time spent in the function",
"delim",
"=",
"'Total time: '",
"delim2",
"=",
"'Pystone time: '",
"#delim =... | 40.5 | 17.928571 |
def apply(self, word, ctx=None):
""" ignore ctx information right now """
flag,reason = Sequential.in_sequence(word,AdjacentConsonants.mei_letters,AdjacentConsonants.reason,self.freq_threshold)
if flag:
flag,reason = Sequential.in_sequence(word,AdjacentConsonants.agaram_letters,Adjac... | [
"def",
"apply",
"(",
"self",
",",
"word",
",",
"ctx",
"=",
"None",
")",
":",
"flag",
",",
"reason",
"=",
"Sequential",
".",
"in_sequence",
"(",
"word",
",",
"AdjacentConsonants",
".",
"mei_letters",
",",
"AdjacentConsonants",
".",
"reason",
",",
"self",
... | 63.833333 | 37.833333 |
def setDisabledBorderColor( self ):
"""
Returns the base color for this node.
:return <QColor>
"""
color = QColor(color)
if self._palette is None:
self._palette = XNodePalette(self._scenePalette)
self._palette.setColor(self._palet... | [
"def",
"setDisabledBorderColor",
"(",
"self",
")",
":",
"color",
"=",
"QColor",
"(",
"color",
")",
"if",
"self",
".",
"_palette",
"is",
"None",
":",
"self",
".",
"_palette",
"=",
"XNodePalette",
"(",
"self",
".",
"_scenePalette",
")",
"self",
".",
"_pale... | 31.285714 | 12.428571 |
def water(target, temperature='pore.temperature', salinity='pore.salinity'):
r"""
Calculates density of pure water or seawater at atmospheric pressure
using Eq. (8) given by Sharqawy et. al [1]. Values at temperature higher
than the normal boiling temperature are calculated at the saturation
pressur... | [
"def",
"water",
"(",
"target",
",",
"temperature",
"=",
"'pore.temperature'",
",",
"salinity",
"=",
"'pore.salinity'",
")",
":",
"T",
"=",
"target",
"[",
"temperature",
"]",
"if",
"salinity",
"in",
"target",
".",
"keys",
"(",
")",
":",
"S",
"=",
"target"... | 30.016393 | 23.704918 |
def clone(self, source_id, backup_id, size,
volume_id=None, source_host=None):
"""
create a volume then clone the contents of
the backup into the new volume
"""
volume_id = volume_id or str(uuid.uuid4())
return self.http_put('/volumes/%s' % volume_id,
... | [
"def",
"clone",
"(",
"self",
",",
"source_id",
",",
"backup_id",
",",
"size",
",",
"volume_id",
"=",
"None",
",",
"source_host",
"=",
"None",
")",
":",
"volume_id",
"=",
"volume_id",
"or",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"return",
"s... | 43.642857 | 9.214286 |
def move_to(self, element, x=0, y=0):
"""Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
element(WebElement): WebElement Object.
x(float): X of... | [
"def",
"move_to",
"(",
"self",
",",
"element",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"_execute",
"(",
"Command",
".",
"MOVE_TO",
",",
"{",
"'element'",
":",
"element",
".",
"element_id",
",",
"'x'",
":",
"x",
",",
"'y'",
... | 31.454545 | 18.363636 |
def force_run(self, hosts, function, attempts=1):
"""
Like priority_run(), but starts the task immediately even if that
max_threads is exceeded.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function:... | [
"def",
"force_run",
"(",
"self",
",",
"hosts",
",",
"function",
",",
"attempts",
"=",
"1",
")",
":",
"return",
"self",
".",
"_run",
"(",
"hosts",
",",
"function",
",",
"self",
".",
"workqueue",
".",
"priority_enqueue",
",",
"True",
",",
"attempts",
")"... | 38.263158 | 13.421053 |
def scale(self, xfactor, yfactor=None):
"""Returns a new envelope rescaled from center by the given factor(s).
Arguments:
xfactor -- int or float X scaling factor
yfactor -- int or float Y scaling factor
"""
yfactor = xfactor if yfactor is None else yfactor
x, y ... | [
"def",
"scale",
"(",
"self",
",",
"xfactor",
",",
"yfactor",
"=",
"None",
")",
":",
"yfactor",
"=",
"xfactor",
"if",
"yfactor",
"is",
"None",
"else",
"yfactor",
"x",
",",
"y",
"=",
"self",
".",
"centroid",
"xshift",
"=",
"self",
".",
"width",
"*",
... | 40.416667 | 12.166667 |
def strip_lastharaka(text):
"""Strip the last Haraka from arabic word except Shadda.
The striped marks are :
- FATHA, DAMMA, KASRA
- SUKUN
- FATHATAN, DAMMATAN, KASRATAN
@param text: arabic text.
@type text: unicode.
@return: return a striped text.
@rtype: unicode.
... | [
"def",
"strip_lastharaka",
"(",
"text",
")",
":",
"if",
"text",
":",
"if",
"is_vocalized",
"(",
"text",
")",
":",
"return",
"re",
".",
"sub",
"(",
"LASTHARAKA_PATTERN",
",",
"u''",
",",
"text",
")",
"return",
"text"
] | 26.75 | 14.4375 |
def _deserialize(
self, data, fields_dict, error_store, many=False, partial=False,
unknown=RAISE, dict_class=dict, index_errors=True, index=None,
):
"""Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict... | [
"def",
"_deserialize",
"(",
"self",
",",
"data",
",",
"fields_dict",
",",
"error_store",
",",
"many",
"=",
"False",
",",
"partial",
"=",
"False",
",",
"unknown",
"=",
"RAISE",
",",
"dict_class",
"=",
"dict",
",",
"index_errors",
"=",
"True",
",",
"index"... | 45.932692 | 16.548077 |
def _check_self_to_empty(self, stateid):
"""
Because of the optimization, the rule for empty states is missing
A check takes place live
Args:
stateid (int): The state identifier
Returns:
bool: A true or false response
"""
x_term = stateid.r... | [
"def",
"_check_self_to_empty",
"(",
"self",
",",
"stateid",
")",
":",
"x_term",
"=",
"stateid",
".",
"rfind",
"(",
"'@'",
")",
"y_term",
"=",
"stateid",
".",
"rfind",
"(",
"'A'",
")",
"if",
"y_term",
">",
"x_term",
":",
"x_term",
"=",
"y_term",
"ids",
... | 29.6 | 12.2 |
def render_to_string(template, object, params=None):
"""
``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml
will be transformed using ``template``.
The result is a unicode string containing the transformed xml.
:param template: an xslt template name.
:pa... | [
"def",
"render_to_string",
"(",
"template",
",",
"object",
",",
"params",
"=",
"None",
")",
":",
"xsl_path",
"=",
"find_template_path",
"(",
"template",
")",
"xml",
"=",
"xmltree",
".",
"xml",
"(",
"object",
")",
"result",
"=",
"transform",
"(",
"xml",
"... | 43.588235 | 21.470588 |
def calc_trades(current_contracts, desired_holdings, trade_weights, prices,
multipliers, **kwargs):
"""
Calculate the number of tradeable contracts for rebalancing from a set
of current contract holdings to a set of desired generic notional holdings
based on prevailing prices and mapping... | [
"def",
"calc_trades",
"(",
"current_contracts",
",",
"desired_holdings",
",",
"trade_weights",
",",
"prices",
",",
"multipliers",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"trade_weights",
",",
"dict",
")",
":",
"trade_weights",
"=",
... | 45.989362 | 22.840426 |
def pre_serialize(self, raw, pkt, i):
'''
Set length of the header based on
'''
self.length = len(raw) + OpenflowHeader._MINLEN | [
"def",
"pre_serialize",
"(",
"self",
",",
"raw",
",",
"pkt",
",",
"i",
")",
":",
"self",
".",
"length",
"=",
"len",
"(",
"raw",
")",
"+",
"OpenflowHeader",
".",
"_MINLEN"
] | 31 | 15.4 |
def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | [
"def",
"score_file",
"(",
"filename",
")",
":",
"# Prepare model.",
"hparams",
"=",
"create_hparams",
"(",
")",
"encoders",
"=",
"registry",
".",
"problem",
"(",
"FLAGS",
".",
"problem",
")",
".",
"feature_encoders",
"(",
"FLAGS",
".",
"data_dir",
")",
"has_... | 36.413793 | 17.655172 |
def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):
"""
Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str
"""
if service_type == ServiceTypes.ASSET_ACCESS:
name = 'access_sla_template.json'
elif service_type == Se... | [
"def",
"get_sla_template_path",
"(",
"service_type",
"=",
"ServiceTypes",
".",
"ASSET_ACCESS",
")",
":",
"if",
"service_type",
"==",
"ServiceTypes",
".",
"ASSET_ACCESS",
":",
"name",
"=",
"'access_sla_template.json'",
"elif",
"service_type",
"==",
"ServiceTypes",
".",... | 39.235294 | 16.882353 |
def delete_user(self, id):
"""
Delete user with given id.
"""
self.assert_has_permission('scim.write')
uri = self.uri + '/Users/%s' % id
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
resp... | [
"def",
"delete_user",
"(",
"self",
",",
"id",
")",
":",
"self",
".",
"assert_has_permission",
"(",
"'scim.write'",
")",
"uri",
"=",
"self",
".",
"uri",
"+",
"'/Users/%s'",
"%",
"id",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
")",
"logging",
".",
... | 30.368421 | 12.894737 |
def keys(self):
"""
Access the keys
:returns: twilio.rest.api.v2010.account.key.KeyList
:rtype: twilio.rest.api.v2010.account.key.KeyList
"""
if self._keys is None:
self._keys = KeyList(self._version, account_sid=self._solution['sid'], )
return self._... | [
"def",
"keys",
"(",
"self",
")",
":",
"if",
"self",
".",
"_keys",
"is",
"None",
":",
"self",
".",
"_keys",
"=",
"KeyList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"return",
"self... | 31.5 | 18.7 |
def sse(mean, estimator):
"""
Description:
Calculates the Sum of Squared Errors (SSE) of
an estimation on flat numpy ndarrays.
Parameters:
mean: actual value (numpy ndarray)
estimator: estimated value of the mean (numpy ndarray)
"""
return np.sum((np.asa... | [
"def",
"sse",
"(",
"mean",
",",
"estimator",
")",
":",
"return",
"np",
".",
"sum",
"(",
"(",
"np",
".",
"asarray",
"(",
"estimator",
")",
"-",
"np",
".",
"asarray",
"(",
"mean",
")",
")",
"**",
"2",
",",
"axis",
"=",
"0",
")"
] | 36 | 14.6 |
def _validate_empty_attributes(self, attributes):
"""Check that required attributes are not empty."""
attrs_to_check = set(self._required) & set(attributes)
for attr in attrs_to_check:
value = getattr(self, attr) # We should always have a value here
if value is None or v... | [
"def",
"_validate_empty_attributes",
"(",
"self",
",",
"attributes",
")",
":",
"attrs_to_check",
"=",
"set",
"(",
"self",
".",
"_required",
")",
"&",
"set",
"(",
"attributes",
")",
"for",
"attr",
"in",
"attrs_to_check",
":",
"value",
"=",
"getattr",
"(",
"... | 52.555556 | 18.222222 |
def _meet(intervals_hier, labels_hier, frame_size):
'''Compute the (sparse) least-common-ancestor (LCA) matrix for a
hierarchical segmentation.
For any pair of frames ``(s, t)``, the LCA is the deepest level in
the hierarchy such that ``(s, t)`` are contained within a single
segment at that level.
... | [
"def",
"_meet",
"(",
"intervals_hier",
",",
"labels_hier",
",",
"frame_size",
")",
":",
"frame_size",
"=",
"float",
"(",
"frame_size",
")",
"# Figure out how many frames we need",
"n_start",
",",
"n_end",
"=",
"_hierarchy_bounds",
"(",
"intervals_hier",
")",
"n",
... | 34.245902 | 22.540984 |
async def writelines(self, lines, eof = False, buffering = True):
"""
Write lines to current output stream
"""
for l in lines:
await self.write(l, False, buffering)
if eof:
await self.write(b'', eof, buffering) | [
"async",
"def",
"writelines",
"(",
"self",
",",
"lines",
",",
"eof",
"=",
"False",
",",
"buffering",
"=",
"True",
")",
":",
"for",
"l",
"in",
"lines",
":",
"await",
"self",
".",
"write",
"(",
"l",
",",
"False",
",",
"buffering",
")",
"if",
"eof",
... | 33.375 | 11.125 |
def get_word_vectors(vocab):
""" Create a word2vec embedding matrix for all the words in the vocab """
wv = get_data('word2vec')
vectors = np.array(len(vocab), len(wv['the']))
for i, tok in enumerate(vocab):
word = tok[0]
variations = (word, word.lower(), word.lower()[:-1])
for w... | [
"def",
"get_word_vectors",
"(",
"vocab",
")",
":",
"wv",
"=",
"get_data",
"(",
"'word2vec'",
")",
"vectors",
"=",
"np",
".",
"array",
"(",
"len",
"(",
"vocab",
")",
",",
"len",
"(",
"wv",
"[",
"'the'",
"]",
")",
")",
"for",
"i",
",",
"tok",
"in",... | 41.461538 | 14.153846 |
def _check_property(self, rest=None, require_indexed=True):
"""Internal helper to check this property for specific requirements.
Called by Model._check_properties().
Args:
rest: Optional subproperty to check, of the form 'name1.name2...nameN'.
Raises:
InvalidPropertyError if this property... | [
"def",
"_check_property",
"(",
"self",
",",
"rest",
"=",
"None",
",",
"require_indexed",
"=",
"True",
")",
":",
"if",
"require_indexed",
"and",
"not",
"self",
".",
"_indexed",
":",
"raise",
"InvalidPropertyError",
"(",
"'Property is unindexed %s'",
"%",
"self",
... | 42.052632 | 24 |
def _create_hexdump(src, start_offset=0, length=16):
"""
Prepares an hexadecimal dump string
:param src: A string containing binary data
:param start_offset: The start offset of the source
:param length: Length of a dump line
:return: A dump string
"""
FI... | [
"def",
"_create_hexdump",
"(",
"src",
",",
"start_offset",
"=",
"0",
",",
"length",
"=",
"16",
")",
":",
"FILTER",
"=",
"\"\"",
".",
"join",
"(",
"(",
"len",
"(",
"repr",
"(",
"chr",
"(",
"x",
")",
")",
")",
"==",
"3",
")",
"and",
"chr",
"(",
... | 37.565217 | 18.347826 |
def _on_connection_failed(self, connection_id, adapter_id, success, failure_reason):
"""Callback function called when a connection has failed.
It is executed in the baBLE working thread: should not be blocking.
Args:
connection_id (int): A unique identifier for this connection on th... | [
"def",
"_on_connection_failed",
"(",
"self",
",",
"connection_id",
",",
"adapter_id",
",",
"success",
",",
"failure_reason",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"_on_connection_failed connection_id=%d, reason=%s\"",
",",
"connection_id",
",",
"failur... | 45.666667 | 28.055556 |
def dropDataProducts(self, *pathnames):
"""Drops (that is, deletes) new (i.e. non-archived) DP items matching the given pathnames."""
trash = QTreeWidget(None)
updated = False
for path in pathnames:
item = self.dpitems.get(path)
if item and not item._dp.archived:
... | [
"def",
"dropDataProducts",
"(",
"self",
",",
"*",
"pathnames",
")",
":",
"trash",
"=",
"QTreeWidget",
"(",
"None",
")",
"updated",
"=",
"False",
"for",
"path",
"in",
"pathnames",
":",
"item",
"=",
"self",
".",
"dpitems",
".",
"get",
"(",
"path",
")",
... | 42.461538 | 8.230769 |
def read_structs(fstream):
"""
Read all structs from likwid's file stream.
Args:
fstream: Likwid's output file stream.
Returns:
A generator that can be used to iterate over all structs in the
fstream.
"""
struct = read_struct(fstream)
while struct is not None:
... | [
"def",
"read_structs",
"(",
"fstream",
")",
":",
"struct",
"=",
"read_struct",
"(",
"fstream",
")",
"while",
"struct",
"is",
"not",
"None",
":",
"yield",
"struct",
"struct",
"=",
"read_struct",
"(",
"fstream",
")"
] | 23.933333 | 17.4 |
def move_to_collection(self, request, *args, **kwargs):
"""Move samples from source to destination collection."""
ids = self.get_ids(request.data)
src_collection_id = self.get_id(request.data, 'source_collection')
dst_collection_id = self.get_id(request.data, 'destination_collection')
... | [
"def",
"move_to_collection",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ids",
"=",
"self",
".",
"get_ids",
"(",
"request",
".",
"data",
")",
"src_collection_id",
"=",
"self",
".",
"get_id",
"(",
"request",
".",
... | 49 | 27.846154 |
def get_mean(self, C, rup, sites, dists):
"""
Returns the mean ground motion in terms of log10 m/s/s, implementing
equation 2 (page 502)
"""
# W2 needs to be a 1 by 5 matrix (not a vector
w_2 = np.array([
[C["W_21"], C["W_22"], C["W_23"], C["W_24"], C["W_25"]]... | [
"def",
"get_mean",
"(",
"self",
",",
"C",
",",
"rup",
",",
"sites",
",",
"dists",
")",
":",
"# W2 needs to be a 1 by 5 matrix (not a vector",
"w_2",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"C",
"[",
"\"W_21\"",
"]",
",",
"C",
"[",
"\"W_22\"",
"]",
",",... | 47.5 | 16.166667 |
def _choose_host(self):
"""
This method randomly chooses a server from the server list given as
a parameter to the parent PythonSDK
:return: The selected host to which the Sender will attempt to
connect
"""
# If a host hasn't been chosen yet or there is o... | [
"def",
"_choose_host",
"(",
"self",
")",
":",
"# If a host hasn't been chosen yet or there is only one host",
"if",
"len",
"(",
"self",
".",
"_hosts",
")",
"==",
"1",
"or",
"self",
".",
"_http_host",
"is",
"None",
":",
"self",
".",
"_http_host",
"=",
"self",
"... | 51.6 | 19.066667 |
def listTagged(self, *args, **kwargs):
"""
List builds tagged with a tag.
Calls "listTagged" XML-RPC.
:returns: deferred that when fired returns a list of Build objects.
"""
data = yield self.call('listTagged', *args, **kwargs)
builds = []
for bdata in d... | [
"def",
"listTagged",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"yield",
"self",
".",
"call",
"(",
"'listTagged'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"builds",
"=",
"[",
"]",
"for",
"bdata",
"in",
... | 30.333333 | 13.4 |
def pockettopo2compass(txtfilename, exclude_splays=False, calculate_lrud=False):
"""Main function which converts a PocketTopo .TXT file to a Compass .DAT file"""
print 'Converting PocketTopo data file %s ...' % txtfilename
# Read our PocketTopo .TXT file, averaging triple-shots in the process
infile = ... | [
"def",
"pockettopo2compass",
"(",
"txtfilename",
",",
"exclude_splays",
"=",
"False",
",",
"calculate_lrud",
"=",
"False",
")",
":",
"print",
"'Converting PocketTopo data file %s ...'",
"%",
"txtfilename",
"# Read our PocketTopo .TXT file, averaging triple-shots in the process",
... | 43.131579 | 26.394737 |
def load_pa11y_results(stdout, spider, url):
"""
Load output from pa11y, filtering out the ignored messages.
The `stdout` parameter is a bytestring, not a unicode string.
"""
if not stdout:
return []
results = json.loads(stdout.decode('utf8'))
ignore_rules = ignore_rules_for_url(sp... | [
"def",
"load_pa11y_results",
"(",
"stdout",
",",
"spider",
",",
"url",
")",
":",
"if",
"not",
"stdout",
":",
"return",
"[",
"]",
"results",
"=",
"json",
".",
"loads",
"(",
"stdout",
".",
"decode",
"(",
"'utf8'",
")",
")",
"ignore_rules",
"=",
"ignore_r... | 29.058824 | 17.647059 |
def _accept_header(self):
"""
Method for determining correct `Accept` header.
Different resources and different GoCD version servers prefer
a diverse headers. In order to manage all of them, this method
tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided,
if wou... | [
"def",
"_accept_header",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"VERSION_TO_ACCEPT_HEADER",
":",
"return",
"self",
".",
"ACCEPT_HEADER",
"return",
"YagocdUtil",
".",
"choose_option",
"(",
"version_to_options",
"=",
"self",
".",
"VERSION_TO_ACCEPT_HEADER",
... | 41.96 | 20.04 |
def pot_to_rpole_aligned(pot, sma, q, F, d, component=1):
"""
Transforms surface potential to polar radius
"""
q = q_for_component(q, component=component)
Phi = pot_for_component(pot, q, component=component)
logger.debug("libphobe.roche_pole(q={}, F={}, d={}, Omega={})".format(q, F, d, pot))
... | [
"def",
"pot_to_rpole_aligned",
"(",
"pot",
",",
"sma",
",",
"q",
",",
"F",
",",
"d",
",",
"component",
"=",
"1",
")",
":",
"q",
"=",
"q_for_component",
"(",
"q",
",",
"component",
"=",
"component",
")",
"Phi",
"=",
"pot_for_component",
"(",
"pot",
",... | 45.125 | 13.375 |
def brackets_insanity_check(p_string):
"""
This function performs a check for different number of '(' and ')'
characters, which indicates that some forks are poorly constructed.
Parameters
----------
p_string: str
String with the definition of the pipeline, e.g.::
'process... | [
"def",
"brackets_insanity_check",
"(",
"p_string",
")",
":",
"if",
"p_string",
".",
"count",
"(",
"FORK_TOKEN",
")",
"!=",
"p_string",
".",
"count",
"(",
"CLOSE_TOKEN",
")",
":",
"# get the number of each type of bracket and state the one that has a",
"# higher value",
... | 36.642857 | 23.571429 |
def get_feature_layers(self, input_layer=None, trainable=False, use_weighted_sum=False):
"""Get layers that output the Bi-LM feature.
:param input_layer: Use existing input layer.
:param trainable: Whether the layers are still trainable.
:param use_weighted_sum: Whether to use weighted ... | [
"def",
"get_feature_layers",
"(",
"self",
",",
"input_layer",
"=",
"None",
",",
"trainable",
"=",
"False",
",",
"use_weighted_sum",
"=",
"False",
")",
":",
"model",
"=",
"keras",
".",
"models",
".",
"clone_model",
"(",
"self",
".",
"model",
",",
"input_lay... | 49 | 21.243243 |
def build_pwm():
""" Builds source with Python 2.7 and 3.2, and tests import """
with cd("/tmp/source/c_pwm"):
test = "import _PWM; print(_PWM.VERSION)"
run("make py2.7")
run('sudo python2.7 -c "%s"' % test)
run("cp _PWM.so ../RPIO/PWM/")
run("mv _PWM.so ../RPIO/PWM/_PWM2... | [
"def",
"build_pwm",
"(",
")",
":",
"with",
"cd",
"(",
"\"/tmp/source/c_pwm\"",
")",
":",
"test",
"=",
"\"import _PWM; print(_PWM.VERSION)\"",
"run",
"(",
"\"make py2.7\"",
")",
"run",
"(",
"'sudo python2.7 -c \"%s\"'",
"%",
"test",
")",
"run",
"(",
"\"cp _PWM.so .... | 39.090909 | 8.272727 |
def show_raslog_output_show_all_raslog_raslog_entries_switch_or_chassis_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_a... | [
"def",
"show_raslog_output_show_all_raslog_raslog_entries_switch_or_chassis_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_raslog",
"=",
"ET",
".",
"Element",
"(",
"\"show_raslog\"",
")",
"... | 49.142857 | 21.071429 |
def academic_degree(self) -> str:
"""Get a random academic degree.
:return: Degree.
:Example:
Bachelor.
"""
degrees = self._data['academic_degree']
return self.random.choice(degrees) | [
"def",
"academic_degree",
"(",
"self",
")",
"->",
"str",
":",
"degrees",
"=",
"self",
".",
"_data",
"[",
"'academic_degree'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"degrees",
")"
] | 23.5 | 15.4 |
def dataframe(self, measure, p_dim, s_dim=None, filters={}, df_class=None):
"""
Return a dataframe with a sumse of the columns of the partition, including a measure and one
or two dimensions. FOr dimensions that have labels, the labels are included
The returned dataframe will have extra... | [
"def",
"dataframe",
"(",
"self",
",",
"measure",
",",
"p_dim",
",",
"s_dim",
"=",
"None",
",",
"filters",
"=",
"{",
"}",
",",
"df_class",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"measure",
"=",
"self",
".",
"measure",
"(",
"measure",
... | 31.337748 | 26.768212 |
def size(self):
"""Total number of grid points."""
# Since np.prod(()) == 1.0 we need to handle that by ourselves
return (0 if self.shape == () else
int(np.prod(self.shape, dtype='int64'))) | [
"def",
"size",
"(",
"self",
")",
":",
"# Since np.prod(()) == 1.0 we need to handle that by ourselves",
"return",
"(",
"0",
"if",
"self",
".",
"shape",
"==",
"(",
")",
"else",
"int",
"(",
"np",
".",
"prod",
"(",
"self",
".",
"shape",
",",
"dtype",
"=",
"'i... | 45 | 14.6 |
def _fmt_fields(fld_vals, fld2fmt):
"""Optional user-formatting of specific fields, eg, pval: '{:8.2e}'."""
vals = []
for fld, val in fld_vals:
if fld in fld2fmt:
val = fld2fmt[fld].format(val)
vals.append(val)
return vals | [
"def",
"_fmt_fields",
"(",
"fld_vals",
",",
"fld2fmt",
")",
":",
"vals",
"=",
"[",
"]",
"for",
"fld",
",",
"val",
"in",
"fld_vals",
":",
"if",
"fld",
"in",
"fld2fmt",
":",
"val",
"=",
"fld2fmt",
"[",
"fld",
"]",
".",
"format",
"(",
"val",
")",
"v... | 32.375 | 12.5 |
def create_output(stdout=None, true_color=False, ansi_colors_only=None):
"""
Return an :class:`~prompt_toolkit.output.Output` instance for the command
line.
:param true_color: When True, use 24bit colors instead of 256 colors.
(`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.)
:para... | [
"def",
"create_output",
"(",
"stdout",
"=",
"None",
",",
"true_color",
"=",
"False",
",",
"ansi_colors_only",
"=",
"None",
")",
":",
"stdout",
"=",
"stdout",
"or",
"sys",
".",
"__stdout__",
"true_color",
"=",
"to_simple_filter",
"(",
"true_color",
")",
"if",... | 34.961538 | 18.730769 |
def _env_filenames(filenames, env):
"""
Extend filenames with ennv indication of environments.
:param list filenames: list of strings indicating filenames
:param str env: environment indicator
:returns: list of filenames extended with environment version
:rtype: list
"""
env_filenames ... | [
"def",
"_env_filenames",
"(",
"filenames",
",",
"env",
")",
":",
"env_filenames",
"=",
"[",
"]",
"for",
"filename",
"in",
"filenames",
":",
"filename_parts",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"filename_parts",
".",
"insert",
"(",
"1",
",",
... | 30.294118 | 17.235294 |
def add_position_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as the position (horizontal) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
"""
if not hparams.positio... | [
"def",
"add_position_timing_signal",
"(",
"x",
",",
"step",
",",
"hparams",
")",
":",
"if",
"not",
"hparams",
".",
"position_start_index",
":",
"index",
"=",
"0",
"elif",
"hparams",
".",
"position_start_index",
"==",
"\"random\"",
":",
"# Shift all positions rando... | 31.4375 | 19.125 |
def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate mouse right click at point x, y.
x: int.
y: int.
waitTime: float.
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absol... | [
"def",
"RightClick",
"(",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"waitTime",
":",
"float",
"=",
"OPERATION_WAIT_TIME",
")",
"->",
"None",
":",
"SetCursorPos",
"(",
"x",
",",
"y",
")",
"screenWidth",
",",
"screenHeight",
"=",
"GetScreenSize",
"(",
... | 41.692308 | 27.076923 |
def verify(password, hash):
"""
Verify a password against a passed hash
"""
_, algorithm, cost, salt, password_hash = hash.split("$")
password = pbkdf2.pbkdf2_hex(password, salt, int(cost) * 500)
return _safe_str_cmp(password, password_hash) | [
"def",
"verify",
"(",
"password",
",",
"hash",
")",
":",
"_",
",",
"algorithm",
",",
"cost",
",",
"salt",
",",
"password_hash",
"=",
"hash",
".",
"split",
"(",
"\"$\"",
")",
"password",
"=",
"pbkdf2",
".",
"pbkdf2_hex",
"(",
"password",
",",
"salt",
... | 28.777778 | 16.777778 |
def validate(self, corpus):
"""
Perform validation on the given corpus.
Args:
corpus (Corpus): The corpus to test/validate.
"""
passed = True
results = {}
for validator in self.validators:
sub_result = validator.validate(corpus)
... | [
"def",
"validate",
"(",
"self",
",",
"corpus",
")",
":",
"passed",
"=",
"True",
"results",
"=",
"{",
"}",
"for",
"validator",
"in",
"self",
".",
"validators",
":",
"sub_result",
"=",
"validator",
".",
"validate",
"(",
"corpus",
")",
"results",
"[",
"va... | 24.842105 | 18.631579 |
def _delete_objects_not_in_list(self, cont, object_prefix=""):
"""
Finds all the objects in the specified container that are not present
in the self._local_files list, and deletes them.
"""
objnames = set(cont.get_object_names(prefix=object_prefix,
full_listing=Tr... | [
"def",
"_delete_objects_not_in_list",
"(",
"self",
",",
"cont",
",",
"object_prefix",
"=",
"\"\"",
")",
":",
"objnames",
"=",
"set",
"(",
"cont",
".",
"get_object_names",
"(",
"prefix",
"=",
"object_prefix",
",",
"full_listing",
"=",
"True",
")",
")",
"local... | 51.846154 | 17.076923 |
def _clean_accents(self, text):
"""Remove most accent marks.
Note that the circumflexes over alphas and iotas in the text since
they determine vocalic quantity.
:param text: raw text
:return: clean text with minimum accent marks
:rtype : string
"""
accent... | [
"def",
"_clean_accents",
"(",
"self",
",",
"text",
")",
":",
"accents",
"=",
"{",
"'ὲέἐἑἒἓἕἔ': 'ε',",
"",
"",
"",
"'ὺύὑὐὒὓὔὕ': 'υ',",
"",
"",
"",
"'ὸόὀὁὂὃὄὅ': 'ο',",
"",
"",
"",
"'ὶίἰἱἲἳἵἴ': 'ι',",
"",
"",
"",
"'ὰάἁἀἂἃἅἄᾳᾂᾃ': 'α',",
"",
"",
"",
"'ὴήἠἡἢἣἥ... | 30.37931 | 13.448276 |
def serialize(self, keep_readonly=False):
"""Return the JSON that would be sent to azure from this model.
This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
:param bool keep_readonly: If you want to serialize the readonly attributes
:returns: A dict JSON ... | [
"def",
"serialize",
"(",
"self",
",",
"keep_readonly",
"=",
"False",
")",
":",
"serializer",
"=",
"Serializer",
"(",
"self",
".",
"_infer_class_models",
"(",
")",
")",
"return",
"serializer",
".",
"_serialize",
"(",
"self",
",",
"keep_readonly",
"=",
"keep_r... | 44.727273 | 22.727273 |
def _is_compound_mfr_temperature_tuple(self, value):
"""Determines whether value is a tuple of the format
(compound(str), mfr(float), temperature(float)).
:param value: The value to be tested.
:returns: True or False"""
if not type(value) is tuple:
return False
... | [
"def",
"_is_compound_mfr_temperature_tuple",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"type",
"(",
"value",
")",
"is",
"tuple",
":",
"return",
"False",
"elif",
"not",
"len",
"(",
"value",
")",
"==",
"3",
":",
"return",
"False",
"elif",
"not",
... | 34.208333 | 14.958333 |
def add(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).add(**kwargs)
) | [
"def",
"add",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"from_datetime",
"(",
"pendulum",
".",
"instance",
"(",
"self",
".",
"datetime",
"(",
")",
")",
".",
"add",
"(",
"*",
"*",
"kwargs",
")",
")"
] | 38.4 | 14.6 |
def repo(self):
"""Get repository data"""
path = urijoin(self.base_url, 'repos', self.owner, self.repository)
r = self.fetch(path)
repo = r.text
return repo | [
"def",
"repo",
"(",
"self",
")",
":",
"path",
"=",
"urijoin",
"(",
"self",
".",
"base_url",
",",
"'repos'",
",",
"self",
".",
"owner",
",",
"self",
".",
"repository",
")",
"r",
"=",
"self",
".",
"fetch",
"(",
"path",
")",
"repo",
"=",
"r",
".",
... | 21.222222 | 25.777778 |
def _populate_profile_from_group_memberships(self, profile):
"""
Populate the given profile object from AUTH_LDAP_PROFILE_FLAGS_BY_GROUP.
Returns True if the profile was modified.
"""
save_profile = False
for field, group_dns in self.settings.PROFILE_FLAGS_BY_GROUP.items... | [
"def",
"_populate_profile_from_group_memberships",
"(",
"self",
",",
"profile",
")",
":",
"save_profile",
"=",
"False",
"for",
"field",
",",
"group_dns",
"in",
"self",
".",
"settings",
".",
"PROFILE_FLAGS_BY_GROUP",
".",
"items",
"(",
")",
":",
"if",
"isinstance... | 39.333333 | 18.533333 |
def create_arc(self, mace_type, name):
'''
Creates the story arc and initial tree for that arc
for the current outline. Returns the resulting Arc
instance.
'''
arc = Arc(mace_type=mace_type, outline=self, name=name)
arc.save()
milestone_count = arc.generat... | [
"def",
"create_arc",
"(",
"self",
",",
"mace_type",
",",
"name",
")",
":",
"arc",
"=",
"Arc",
"(",
"mace_type",
"=",
"mace_type",
",",
"outline",
"=",
"self",
",",
"name",
"=",
"name",
")",
"arc",
".",
"save",
"(",
")",
"milestone_count",
"=",
"arc",... | 38.785714 | 21.214286 |
def show(commands,
raw_text=True,
**kwargs):
'''
Execute one or more show (non-configuration) commands.
commands
The commands to be executed.
raw_text: ``True``
Whether to return raw text or structured data.
transport: ``https``
Specifies the type of conn... | [
"def",
"show",
"(",
"commands",
",",
"raw_text",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"raw_text",
":",
"method",
"=",
"'cli_ascii'",
"key",
"=",
"'msg'",
"else",
":",
"method",
"=",
"'cli'",
"key",
"=",
"'body... | 32.275862 | 27.793103 |
def _parseline(self, line):
"""
Results log file line Parser. The parse method in
InstrumentCSVResultsFileParser calls this method for each line
in the results file that is to be parsed.
:param line: a to parse
:returns: the number of rows to jump and parse the next data ... | [
"def",
"_parseline",
"(",
"self",
",",
"line",
")",
":",
"split_line",
"=",
"line",
".",
"split",
"(",
"self",
".",
"_separator",
")",
"if",
"self",
".",
"_is_header",
":",
"self",
".",
"_is_header",
"=",
"False",
"self",
".",
"_current_section",
"=",
... | 50.25 | 21.45 |
def calculate_expiration(self, token):
"""
Calculate token expiration
return expiration if the token need to set expiration or refresh,
otherwise return None.
Args:
token (dict): a decoded token
"""
if not token:
return None
now =... | [
"def",
"calculate_expiration",
"(",
"self",
",",
"token",
")",
":",
"if",
"not",
"token",
":",
"return",
"None",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"time_to_live",
"=",
"self",
".",
"config",
"[",
"\"expiration\"",
"]",
"if",
"\"exp\"",
"no... | 33.590909 | 14.863636 |
def item_before(self, item):
"""The item before an item
:param item: The item to get the previous item relative to
"""
prev_iter = self._prev_iter_for(item)
if prev_iter is not None:
return self._object_at_iter(prev_iter) | [
"def",
"item_before",
"(",
"self",
",",
"item",
")",
":",
"prev_iter",
"=",
"self",
".",
"_prev_iter_for",
"(",
"item",
")",
"if",
"prev_iter",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_object_at_iter",
"(",
"prev_iter",
")"
] | 33.375 | 12.5 |
def get_headers_in_order(self):
"""Gets the headers in the order they want to be displayed.
Returns a list of triplets: (idx, key, header_info)
"""
res = list()
#Scan through self.headers_in_order and just bolt on the actual header info
for bucket in sorted(self.header... | [
"def",
"get_headers_in_order",
"(",
"self",
")",
":",
"res",
"=",
"list",
"(",
")",
"#Scan through self.headers_in_order and just bolt on the actual header info",
"for",
"bucket",
"in",
"sorted",
"(",
"self",
".",
"headers_in_order",
")",
":",
"for",
"idx",
",",
"k"... | 46 | 16.4 |
def _load_config():
"""Searches for config files, reads them and returns a dictionary
Looks for a ``check-manifest`` section in ``pyproject.toml``,
``setup.cfg``, and ``tox.ini``, in that order. The first file
that exists and has that section will be loaded and returned as a
dictionary.
"""
... | [
"def",
"_load_config",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"\"pyproject.toml\"",
")",
":",
"config",
"=",
"toml",
".",
"load",
"(",
"\"pyproject.toml\"",
")",
"if",
"CFG_SECTION_CHECK_MANIFEST",
"in",
"config",
".",
"get",
"(",
"\"t... | 37.261905 | 22.309524 |
def pdf_Rosin_Rammler(d, k, m):
r'''Calculates the probability density of a particle
distribution following the Rosin-Rammler (RR) model given a
particle diameter `d`, and the two parameters `k` and `m`.
.. math::
q(d) = k m d^{(m-1)} \exp(- k d^{m})
Parameters
----------
... | [
"def",
"pdf_Rosin_Rammler",
"(",
"d",
",",
"k",
",",
"m",
")",
":",
"return",
"d",
"**",
"(",
"m",
"-",
"1.0",
")",
"*",
"k",
"*",
"m",
"*",
"exp",
"(",
"-",
"d",
"**",
"m",
"*",
"k",
")"
] | 27.461538 | 23.974359 |
def assert_string_list(dist, attr, value):
"""Verify that value is a string list or None"""
try:
assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError):
raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
... | [
"def",
"assert_string_list",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"assert",
"''",
".",
"join",
"(",
"value",
")",
"!=",
"value",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"AttributeError",
",",
"AssertionError",
")",
":... | 39.625 | 15.875 |
def set_fluxinfo(self):
""" Uses list of known flux calibrators (with models in CASA) to find full name given in scan.
"""
knowncals = ['3C286', '3C48', '3C147', '3C138']
# find scans with knowncals in the name
sourcenames = [self.sources[source]['source'] for source in self.so... | [
"def",
"set_fluxinfo",
"(",
"self",
")",
":",
"knowncals",
"=",
"[",
"'3C286'",
",",
"'3C48'",
",",
"'3C147'",
",",
"'3C138'",
"]",
"# find scans with knowncals in the name",
"sourcenames",
"=",
"[",
"self",
".",
"sources",
"[",
"source",
"]",
"[",
"'source'",... | 45.391304 | 22.304348 |
def isBetween(self, a, b, axes='xyz'):
'''
:a: Point or point equivalent
:b: Point or point equivalent
:axis: optional string
:return: float
Checks the coordinates specified in 'axes' of 'self' to
determine if they are bounded by 'a' and 'b'. The range
is... | [
"def",
"isBetween",
"(",
"self",
",",
"a",
",",
"b",
",",
"axes",
"=",
"'xyz'",
")",
":",
"a",
"=",
"self",
".",
"__class__",
".",
"_convert",
"(",
"a",
")",
"b",
"=",
"self",
".",
"__class__",
".",
"_convert",
"(",
"b",
")",
"fn",
"=",
"lambda... | 29.4 | 17.4 |
def install_python_module(name):
""" instals a python module using pip """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
run('pip --quiet install %s' % name) | [
"def",
"install_python_module",
"(",
"name",
")",
":",
"with",
"settings",
"(",
"hide",
"(",
"'warnings'",
",",
"'running'",
",",
"'stdout'",
",",
"'stderr'",
")",
",",
"warn_only",
"=",
"False",
",",
"capture",
"=",
"True",
")",
":",
"run",
"(",
"'pip -... | 39.333333 | 14.5 |
def sortframe(frame):
'''
sorts particles for a frame
'''
d = frame['data'];
sortedargs = np.lexsort([d['xi'],d['yi'],d['zi']])
d = d[sortedargs];
frame['data']=d;
return frame; | [
"def",
"sortframe",
"(",
"frame",
")",
":",
"d",
"=",
"frame",
"[",
"'data'",
"]",
"sortedargs",
"=",
"np",
".",
"lexsort",
"(",
"[",
"d",
"[",
"'xi'",
"]",
",",
"d",
"[",
"'yi'",
"]",
",",
"d",
"[",
"'zi'",
"]",
"]",
")",
"d",
"=",
"d",
"[... | 22.333333 | 20.777778 |
def destroy(self):
""" Cleanup the activty lifecycle listener """
if self.widget:
self.set_active(False)
super(AndroidBarcodeView, self).destroy() | [
"def",
"destroy",
"(",
"self",
")",
":",
"if",
"self",
".",
"widget",
":",
"self",
".",
"set_active",
"(",
"False",
")",
"super",
"(",
"AndroidBarcodeView",
",",
"self",
")",
".",
"destroy",
"(",
")"
] | 35.6 | 10.8 |
def from_string(cls, width, height, rgba_string):
"""Returns a Form with 32-bit RGBA pixels
Accepts string containing raw RGBA color values
"""
# Convert RGBA string to ARGB
raw = ""
for i in range(0, len(rgba_string), 4):
raw += rgba_string[i+3] # alpha
... | [
"def",
"from_string",
"(",
"cls",
",",
"width",
",",
"height",
",",
"rgba_string",
")",
":",
"# Convert RGBA string to ARGB",
"raw",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"rgba_string",
")",
",",
"4",
")",
":",
"raw",
"+=",... | 30.111111 | 14.555556 |
def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_input, Iterable):
layer_input = list(map(lambda x: node_to_id[x], layer_input))
else:
... | [
"def",
"layer_description_extractor",
"(",
"layer",
",",
"node_to_id",
")",
":",
"layer_input",
"=",
"layer",
".",
"input",
"layer_output",
"=",
"layer",
".",
"output",
"if",
"layer_input",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"layer_input",
",",... | 30.163265 | 17.469388 |
def visit_dictcomp(self, node):
"""return an astroid.DictComp node as string"""
return "{%s: %s %s}" % (
node.key.accept(self),
node.value.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | [
"def",
"visit_dictcomp",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"{%s: %s %s}\"",
"%",
"(",
"node",
".",
"key",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
",",
"\" \"",
".",
"join",
"(",
"n"... | 37 | 11.428571 |
def _remote_space_available_unix(self, search_pattern=""):
"""Return space available on *nix system (BSD/Linux)."""
self.ssh_ctl_chan._enter_shell()
remote_cmd = "/bin/df -k {}".format(self.file_system)
remote_output = self.ssh_ctl_chan.send_command(
remote_cmd, expect_string... | [
"def",
"_remote_space_available_unix",
"(",
"self",
",",
"search_pattern",
"=",
"\"\"",
")",
":",
"self",
".",
"ssh_ctl_chan",
".",
"_enter_shell",
"(",
")",
"remote_cmd",
"=",
"\"/bin/df -k {}\"",
".",
"format",
"(",
"self",
".",
"file_system",
")",
"remote_out... | 41.5 | 18.617647 |
def handle_notification(self, msgtype, method, args, kwargs):
"""Handle a notification."""
self.dispatch.call(method, args, kwargs) | [
"def",
"handle_notification",
"(",
"self",
",",
"msgtype",
",",
"method",
",",
"args",
",",
"kwargs",
")",
":",
"self",
".",
"dispatch",
".",
"call",
"(",
"method",
",",
"args",
",",
"kwargs",
")"
] | 48.333333 | 9.666667 |
def config_name_from_full_name(full_name):
"""Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like... | [
"def",
"config_name_from_full_name",
"(",
"full_name",
")",
":",
"projects",
",",
"_",
",",
"configs",
",",
"result",
"=",
"full_name",
".",
"split",
"(",
"\"/\"",
")",
"if",
"projects",
"!=",
"\"projects\"",
"or",
"configs",
"!=",
"\"configs\"",
":",
"raise... | 39.84 | 23.68 |
def as_flat_array(iterables):
'''Given a sequence of sequences, return a flat numpy array.
Parameters
----------
iterables : sequence of sequence of number
A sequence of tuples or lists containing numbers. Typically these come
from something that represents each joint in a skeleton, lik... | [
"def",
"as_flat_array",
"(",
"iterables",
")",
":",
"arr",
"=",
"[",
"]",
"for",
"x",
"in",
"iterables",
":",
"arr",
".",
"extend",
"(",
"x",
")",
"return",
"np",
".",
"array",
"(",
"arr",
")"
] | 28.444444 | 26.333333 |
def _kwargs(self):
"""Keyword arguments for recreating the Shape from the vertices.
"""
return dict(color=self.color, velocity=self.velocity, colors=self.colors) | [
"def",
"_kwargs",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"color",
"=",
"self",
".",
"color",
",",
"velocity",
"=",
"self",
".",
"velocity",
",",
"colors",
"=",
"self",
".",
"colors",
")"
] | 36.4 | 20.6 |
def _wait_for_js(self):
"""
Class method added by the decorators to allow
decorated classes to manually re-check JavaScript
dependencies.
Expect that `self` is a class that:
1) Has been decorated with either `js_defined` or `requirejs`
2) Has a `browser` property
If either (1) or (2) i... | [
"def",
"_wait_for_js",
"(",
"self",
")",
":",
"# No Selenium browser available, so return without doing anything",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'browser'",
")",
":",
"return",
"# pylint: disable=protected-access",
"# Wait for JavaScript variables to be defined",
"... | 35.75 | 21.5 |
def locked_coroutine(f):
"""
Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time
"""
@asyncio.coroutine
def new_function(*args, **kwargs):
# In the instance of the class we will st... | [
"def",
"locked_coroutine",
"(",
"f",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# In the instance of the class we will store",
"# a lock has an attribute.",
"lock_var_name",
"=",
"\"__\"",... | 33.473684 | 16.315789 |
def replace_close(x, xhat, rtol=default_rtol, atol=default_atol, copy=True):
'''
replace_close(x, xhat) yields x if x is not close to xhat and xhat otherwise. Closeness is
determined by numpy's isclose(), and the atol and rtol options are passed along.
The x and xhat arguments may be lists/arrays.
... | [
"def",
"replace_close",
"(",
"x",
",",
"xhat",
",",
"rtol",
"=",
"default_rtol",
",",
"atol",
"=",
"default_atol",
",",
"copy",
"=",
"True",
")",
":",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"default_rtol",
"if",
"atol",
"is",
"None",
":",
"ato... | 40.733333 | 25.266667 |
def doFindAny(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params):
"""This function will perform the command -findany."""
self._preFind(WHAT, SORT, SKIP, MAX, LOP)
for key in params:
self._addDBParam(key, params[key])
return self._doAction('-findany') | [
"def",
"doFindAny",
"(",
"self",
",",
"WHAT",
"=",
"{",
"}",
",",
"SORT",
"=",
"[",
"]",
",",
"SKIP",
"=",
"None",
",",
"MAX",
"=",
"None",
",",
"LOP",
"=",
"'AND'",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"_preFind",
"(",
"WHAT",
","... | 30.111111 | 21.222222 |
def parse_slab_stats(slab_stats):
"""Convert output from memcached's `stats slabs` into a Python dict.
Newlines are returned by memcached along with carriage returns
(i.e. '\r\n').
>>> parse_slab_stats(
"STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT "
"active_sla... | [
"def",
"parse_slab_stats",
"(",
"slab_stats",
")",
":",
"stats_dict",
"=",
"{",
"'slabs'",
":",
"defaultdict",
"(",
"lambda",
":",
"{",
"}",
")",
"}",
"for",
"line",
"in",
"slab_stats",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
"==",
"'END'",
":"... | 28.657895 | 18 |
def track_pageview(self, name, url, duration=0, properties=None, measurements=None):
"""Send information about the page viewed in the application (a web page for instance).
Args:
name (str). the name of the page that was viewed.\n
url (str). the URL of the page that was viewed.\... | [
"def",
"track_pageview",
"(",
"self",
",",
"name",
",",
"url",
",",
"duration",
"=",
"0",
",",
"properties",
"=",
"None",
",",
"measurements",
"=",
"None",
")",
":",
"data",
"=",
"channel",
".",
"contracts",
".",
"PageViewData",
"(",
")",
"data",
".",
... | 49.65 | 25.15 |
def connected_sites( self, site_labels=None ):
"""
Searches the lattice to find sets of sites that are contiguously neighbouring.
Mutually exclusive sets of contiguous sites are returned as Cluster objects.
Args:
site_labels (:obj:(List(Str)|Set(Str)|Str), optional): Labels ... | [
"def",
"connected_sites",
"(",
"self",
",",
"site_labels",
"=",
"None",
")",
":",
"if",
"site_labels",
":",
"selected_sites",
"=",
"self",
".",
"select_sites",
"(",
"site_labels",
")",
"else",
":",
"selected_sites",
"=",
"self",
".",
"sites",
"initial_clusters... | 38.658537 | 23.682927 |
def guess_python_env():
"""Guess the default python env to use."""
version, major, minor = get_version_info()
if 'PyPy' in version:
return 'pypy3' if major == 3 else 'pypy'
return 'py{major}{minor}'.format(major=major, minor=minor) | [
"def",
"guess_python_env",
"(",
")",
":",
"version",
",",
"major",
",",
"minor",
"=",
"get_version_info",
"(",
")",
"if",
"'PyPy'",
"in",
"version",
":",
"return",
"'pypy3'",
"if",
"major",
"==",
"3",
"else",
"'pypy'",
"return",
"'py{major}{minor}'",
".",
... | 41.666667 | 11.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.