text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def note_and_log(cls):
"""
This will be used as a decorator on class to activate
logging and store messages in the variable cls._notes
This will allow quick access to events in the web app.
A note can be added to cls._notes without logging if passing
the argument log=false to function note()
... | [
"def",
"note_and_log",
"(",
"cls",
")",
":",
"if",
"hasattr",
"(",
"cls",
",",
"\"DEBUG_LEVEL\"",
")",
":",
"if",
"cls",
".",
"DEBUG_LEVEL",
"==",
"\"debug\"",
":",
"file_level",
"=",
"logging",
".",
"DEBUG",
"console_level",
"=",
"logging",
".",
"DEBUG",
... | 31.161765 | 0.000686 |
def process_params(self, params):
'''
Populates the launch data from a dictionary. Only cares about keys in
the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or
'ext_'.
'''
for key, val in params.items():
if key in LAUNCH_DATA_PARAMETERS and val !=... | [
"def",
"process_params",
"(",
"self",
",",
"params",
")",
":",
"for",
"key",
",",
"val",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"LAUNCH_DATA_PARAMETERS",
"and",
"val",
"!=",
"'None'",
":",
"if",
"key",
"==",
"'roles'",
":",
"... | 42.285714 | 0.002203 |
def getMultiSeriesRegistrations(self,q_filter=Q(),name_series=False,**kwargs):
'''
Use the getSeriesRegistered method above to get a list of each series the
person has registered for. The return only indicates whether they are
registered more than once for the same series (e.g. for keep... | [
"def",
"getMultiSeriesRegistrations",
"(",
"self",
",",
"q_filter",
"=",
"Q",
"(",
")",
",",
"name_series",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"series_registered",
"=",
"self",
".",
"getSeriesRegistered",
"(",
"q_filter",
",",
"distinct",
"=",
... | 56.333333 | 0.012609 |
def process_item(self, item):
"""Calculate new maximum value for each group,
for "new" items only.
"""
group, value = item['group'], item['value']
if group in self._groups:
cur_val = self._groups[group]
self._groups[group] = max(cur_val, value)
els... | [
"def",
"process_item",
"(",
"self",
",",
"item",
")",
":",
"group",
",",
"value",
"=",
"item",
"[",
"'group'",
"]",
",",
"item",
"[",
"'value'",
"]",
"if",
"group",
"in",
"self",
".",
"_groups",
":",
"cur_val",
"=",
"self",
".",
"_groups",
"[",
"gr... | 44.7 | 0.002191 |
def isel_variable_and_index(
name: Hashable,
variable: Variable,
index: pd.Index,
indexers: Mapping[Any, Union[slice, Variable]],
) -> Tuple[Variable, Optional[pd.Index]]:
"""Index a Variable and pandas.Index together."""
if not indexers:
# nothing to index
return variable.copy(d... | [
"def",
"isel_variable_and_index",
"(",
"name",
":",
"Hashable",
",",
"variable",
":",
"Variable",
",",
"index",
":",
"pd",
".",
"Index",
",",
"indexers",
":",
"Mapping",
"[",
"Any",
",",
"Union",
"[",
"slice",
",",
"Variable",
"]",
"]",
",",
")",
"->",... | 30.482759 | 0.001096 |
def _interpret_result(self, task):
"""
Interpret the result of a ping.
:param task: The pinger task.
The result or exception of the `task` is interpreted as follows:
* :data:`None` result: *positive*
* :class:`aioxmpp.errors.XMPPError`, ``service-unavailable``:
... | [
"def",
"_interpret_result",
"(",
"self",
",",
"task",
")",
":",
"if",
"task",
".",
"exception",
"(",
")",
"is",
"None",
":",
"self",
".",
"_on_fresh",
"(",
")",
"return",
"exc",
"=",
"task",
".",
"exception",
"(",
")",
"if",
"isinstance",
"(",
"exc",... | 34.882353 | 0.001641 |
def htmljoin(ol,sp,**kwargs):
'''
ol = [1,2,3,4]
htmljoin(ol,"option",outer="select")
'''
if('outer' in kwargs):
outer = kwargs['outer']
else:
outer = ""
if(outer):
head = "<" + outer + ">"
tail = "</" + outer + ">"
else:
head = ""... | [
"def",
"htmljoin",
"(",
"ol",
",",
"sp",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'outer'",
"in",
"kwargs",
")",
":",
"outer",
"=",
"kwargs",
"[",
"'outer'",
"]",
"else",
":",
"outer",
"=",
"\"\"",
"if",
"(",
"outer",
")",
":",
"head",
"=... | 21.958333 | 0.009091 |
def configure_output(verbosity=0, output_levels=None, quiet=False):
"""
Configure verbosity level through Fabric's output managers.
Provides a default mapping from verbosity levels to output types.
:param verbosity: an integral verbosity level
:param output_levels: an optional mapping from Fabric ... | [
"def",
"configure_output",
"(",
"verbosity",
"=",
"0",
",",
"output_levels",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"verbosity",
"=",
"verbosity",
"if",
"not",
"quiet",
"else",
"-",
"1",
"output_levels",
"=",
"output_levels",
"or",
"{",
"\"stat... | 32.675 | 0.002229 |
def setAlternateColor(self, color):
"""
Sets the alternate color for this node.
:param color <QColor>
"""
color = QColor(color)
if self._palette is None:
self._palette = XNodePalette(self._scenePalette)
self._palette.setCol... | [
"def",
"setAlternateColor",
"(",
"self",
",",
"color",
")",
":",
"color",
"=",
"QColor",
"(",
"color",
")",
"if",
"self",
".",
"_palette",
"is",
"None",
":",
"self",
".",
"_palette",
"=",
"XNodePalette",
"(",
"self",
".",
"_scenePalette",
")",
"self",
... | 31.75 | 0.010204 |
def _setup_observers(self):
"""
Setup the default observers
1: pass through to parent, if present
"""
if self.has_parent():
self.add_observer(self._parent_, self._parent_._pass_through_notify_observers, -np.inf) | [
"def",
"_setup_observers",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_parent",
"(",
")",
":",
"self",
".",
"add_observer",
"(",
"self",
".",
"_parent_",
",",
"self",
".",
"_parent_",
".",
"_pass_through_notify_observers",
",",
"-",
"np",
".",
"inf",
... | 32.125 | 0.011364 |
def clean(self):
"""
Remove unused filters.
"""
for f in sorted(self.components.keys()):
unused = not any(self.switches[a][f] for a in self.analytes)
if unused:
self.remove(f) | [
"def",
"clean",
"(",
"self",
")",
":",
"for",
"f",
"in",
"sorted",
"(",
"self",
".",
"components",
".",
"keys",
"(",
")",
")",
":",
"unused",
"=",
"not",
"any",
"(",
"self",
".",
"switches",
"[",
"a",
"]",
"[",
"f",
"]",
"for",
"a",
"in",
"se... | 30 | 0.008097 |
def bytes2fsn(data, encoding="utf-8"):
"""
Args:
data (bytes): The data to convert
encoding (`str`): encoding used for Windows
Returns:
`fsnative`
Raises:
TypeError: If no `bytes` path is passed
ValueError: If decoding fails or the encoding is invalid
Turns `... | [
"def",
"bytes2fsn",
"(",
"data",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"data needs to be bytes\"",
")",
"if",
"is_win",
":",
"if",
"encoding",
"is",
"None",... | 30.4 | 0.000797 |
def update_actualremoterelieve_v1(self):
"""Constrain the actual relieve discharge to a remote location.
Required control parameter:
|HighestRemoteDischarge|
Required derived parameter:
|HighestRemoteSmoothPar|
Updated flux sequence:
|ActualRemoteRelieve|
Basic equation - disco... | [
"def",
"update_actualremoterelieve_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"f... | 35.057143 | 0.000264 |
def anonymous_required(function=None, redirect_url=None):
"""
Decorator requiring the current user to be anonymous (not logged in).
"""
if not redirect_url:
redirect_url = settings.LOGIN_REDIRECT_URL
actual_decorator = user_passes_test(
is_anonymous,
login_url=redirect_url,
... | [
"def",
"anonymous_required",
"(",
"function",
"=",
"None",
",",
"redirect_url",
"=",
"None",
")",
":",
"if",
"not",
"redirect_url",
":",
"redirect_url",
"=",
"settings",
".",
"LOGIN_REDIRECT_URL",
"actual_decorator",
"=",
"user_passes_test",
"(",
"is_anonymous",
"... | 26.9375 | 0.002242 |
def post_event_display_settings(self, id, **data):
"""
POST /events/:id/display_settings/
Updates the display settings for an event.
"""
return self.post("/events/{0}/display_settings/".format(id), data=data) | [
"def",
"post_event_display_settings",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"post",
"(",
"\"/events/{0}/display_settings/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | 35.857143 | 0.011673 |
def shortlex(start, other, excludestart=False):
"""Yield all unions of start with other in shortlex order.
>>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])]
['000', '100', '010', '001', '110', '101', '011', '111']
>>> ', '.join(''.join(sorted(s))
... for s in shortlex(set(), [{'... | [
"def",
"shortlex",
"(",
"start",
",",
"other",
",",
"excludestart",
"=",
"False",
")",
":",
"if",
"not",
"excludestart",
":",
"yield",
"start",
"queue",
"=",
"collections",
".",
"deque",
"(",
"[",
"(",
"start",
",",
"other",
")",
"]",
")",
"while",
"... | 29.344828 | 0.001138 |
def _variants_fields(fields, exclude_fields, info_ids):
"""Utility function to determine which fields to extract when loading
variants."""
if fields is None:
# no fields specified by user
# by default extract all standard and INFO fields
fields = config.STANDARD_VARIANT_FIELDS + info... | [
"def",
"_variants_fields",
"(",
"fields",
",",
"exclude_fields",
",",
"info_ids",
")",
":",
"if",
"fields",
"is",
"None",
":",
"# no fields specified by user",
"# by default extract all standard and INFO fields",
"fields",
"=",
"config",
".",
"STANDARD_VARIANT_FIELDS",
"+... | 45.5 | 0.001076 |
def accelerated_proximal_gradient(x, f, g, gamma, niter, callback=None,
**kwargs):
r"""Accelerated proximal gradient algorithm for convex optimization.
The method is known as "Fast Iterative Soft-Thresholding Algorithm"
(FISTA). See `[Beck2009]`_ for more information.
... | [
"def",
"accelerated_proximal_gradient",
"(",
"x",
",",
"f",
",",
"g",
",",
"gamma",
",",
"niter",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get and validate input",
"if",
"x",
"not",
"in",
"f",
".",
"domain",
":",
"raise",
"Ty... | 28.457447 | 0.000361 |
def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_... | [
"def",
"down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | 32.1875 | 0.000943 |
def saved_searches(self):
""" :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list """
return bind_api(
api=self,
path='/saved_searches/list.json',
payload_type='saved_search', payload_list=... | [
"def",
"saved_searches",
"(",
"self",
")",
":",
"return",
"bind_api",
"(",
"api",
"=",
"self",
",",
"path",
"=",
"'/saved_searches/list.json'",
",",
"payload_type",
"=",
"'saved_search'",
",",
"payload_list",
"=",
"True",
",",
"require_auth",
"=",
"True",
")"
... | 44.75 | 0.008219 |
def orthogonal_initialization(X,K):
"""
Initialize the centrodis by orthogonal_initialization.
Parameters
--------------------
X(data): array-like, shape= (m_samples,n_samples)
K: integer
number of K clusters
Returns
-------
centroids: array-like, shape (K,n_samples) ... | [
"def",
"orthogonal_initialization",
"(",
"X",
",",
"K",
")",
":",
"N",
",",
"M",
"=",
"X",
".",
"shape",
"centroids",
"=",
"X",
"[",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"N",
"-",
"1",
",",
"1",
")",
",",
":",
"]",
"data_norms",
... | 44.307692 | 0.028887 |
def make_message_multipart(message):
"""Convert a message into a multipart message."""
if not message.is_multipart():
multipart_message = email.mime.multipart.MIMEMultipart('alternative')
for header_key in set(message.keys()):
# Preserve duplicate headers
values = message... | [
"def",
"make_message_multipart",
"(",
"message",
")",
":",
"if",
"not",
"message",
".",
"is_multipart",
"(",
")",
":",
"multipart_message",
"=",
"email",
".",
"mime",
".",
"multipart",
".",
"MIMEMultipart",
"(",
"'alternative'",
")",
"for",
"header_key",
"in",... | 46.733333 | 0.001399 |
def _filter_schlumberger(configs):
"""Filter Schlumberger configurations
Schlumberger configurations are selected using the following criteria:
* For a given voltage dipole, there need to be at least two current
injections with electrodes located on the left and the right of the
voltage dipole... | [
"def",
"_filter_schlumberger",
"(",
"configs",
")",
":",
"# sort configs",
"configs_sorted",
"=",
"np",
".",
"hstack",
"(",
"(",
"np",
".",
"sort",
"(",
"configs",
"[",
":",
",",
"0",
":",
"2",
"]",
",",
"axis",
"=",
"1",
")",
",",
"np",
".",
"sort... | 30.777778 | 0.000389 |
def exp_trans(base=None, **kwargs):
"""
Create a exponential transform class for *base*
This is inverse of the log transform.
Parameters
----------
base : float
Base of the logarithm
kwargs : dict
Keyword arguments passed onto
:func:`trans_new`. Should not include
... | [
"def",
"exp_trans",
"(",
"base",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# default to e",
"if",
"base",
"is",
"None",
":",
"name",
"=",
"'power_e'",
"base",
"=",
"np",
".",
"exp",
"(",
"1",
")",
"else",
":",
"name",
"=",
"'power_{}'",
".",... | 21.135135 | 0.001222 |
def ln(self, h=''):
"Line Feed; default value is last cell height"
self.x=self.l_margin
if(isinstance(h, basestring)):
self.y+=self.lasth
else:
self.y+=h | [
"def",
"ln",
"(",
"self",
",",
"h",
"=",
"''",
")",
":",
"self",
".",
"x",
"=",
"self",
".",
"l_margin",
"if",
"(",
"isinstance",
"(",
"h",
",",
"basestring",
")",
")",
":",
"self",
".",
"y",
"+=",
"self",
".",
"lasth",
"else",
":",
"self",
"... | 29 | 0.023923 |
def _pair_deltas(seq, pars):
'''Add up nearest-neighbor parameters for a given sequence.
:param seq: DNA sequence for which to sum nearest neighbors
:type seq: str
:param pars: parameter set to use
:type pars: dict
:returns: nearest-neighbor delta_H and delta_S sums.
:rtype: tuple of floats... | [
"def",
"_pair_deltas",
"(",
"seq",
",",
"pars",
")",
":",
"delta0",
"=",
"0",
"delta1",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"seq",
")",
"-",
"1",
")",
":",
"curchar",
"=",
"seq",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"delta0",
... | 28.833333 | 0.001866 |
def _iterate_managers(connection, skip):
"""Iterate over instantiated managers."""
for idx, name, manager_cls in _iterate_manage_classes(skip):
if name in skip:
continue
try:
manager = manager_cls(connection=connection)
except TypeError as e:
click.se... | [
"def",
"_iterate_managers",
"(",
"connection",
",",
"skip",
")",
":",
"for",
"idx",
",",
"name",
",",
"manager_cls",
"in",
"_iterate_manage_classes",
"(",
"skip",
")",
":",
"if",
"name",
"in",
"skip",
":",
"continue",
"try",
":",
"manager",
"=",
"manager_c... | 34.25 | 0.00237 |
def FunctionalGroupColorMapping(maptype='jet', reverse=False):
"""Maps amino-acid functional groups to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with the other mapping functions, which all get called with
these argum... | [
"def",
"FunctionalGroupColorMapping",
"(",
"maptype",
"=",
"'jet'",
",",
"reverse",
"=",
"False",
")",
":",
"small_color",
"=",
"'#f76ab4'",
"nucleophilic_color",
"=",
"'#ff7f00'",
"hydrophobic_color",
"=",
"'#12ab0d'",
"aromatic_color",
"=",
"'#84380b'",
"acidic_colo... | 46.166667 | 0.022104 |
def search_streams(self, query, hls=False, limit=25, offset=0):
"""Search for streams and return them
:param query: the query string
:type query: :class:`str`
:param hls: If true, only return streams that have hls stream
:type hls: :class:`bool`
:param limit: maximum num... | [
"def",
"search_streams",
"(",
"self",
",",
"query",
",",
"hls",
"=",
"False",
",",
"limit",
"=",
"25",
",",
"offset",
"=",
"0",
")",
":",
"r",
"=",
"self",
".",
"kraken_request",
"(",
"'GET'",
",",
"'search/streams'",
",",
"params",
"=",
"{",
"'query... | 42.285714 | 0.002203 |
def set_default(self_,param_name,value):
"""
Set the default value of param_name.
Equivalent to setting param_name on the class.
"""
cls = self_.cls
setattr(cls,param_name,value) | [
"def",
"set_default",
"(",
"self_",
",",
"param_name",
",",
"value",
")",
":",
"cls",
"=",
"self_",
".",
"cls",
"setattr",
"(",
"cls",
",",
"param_name",
",",
"value",
")"
] | 27.5 | 0.026432 |
def _prompt(letters='yn', default=None):
"""
Wait for the user to type a character (and hit Enter). If the user enters
one of the characters in `letters`, return that character. If the user
hits Enter without entering a character, and `default` is specified,
returns `default`. Otherwise, asks the... | [
"def",
"_prompt",
"(",
"letters",
"=",
"'yn'",
",",
"default",
"=",
"None",
")",
":",
"while",
"True",
":",
"try",
":",
"input_text",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"sy... | 39.647059 | 0.001449 |
def removeBiosample(self, biosample):
"""
Removes the specified biosample from this repository.
"""
q = models.Biosample.delete().where(
models.Biosample.id == biosample.getId())
q.execute() | [
"def",
"removeBiosample",
"(",
"self",
",",
"biosample",
")",
":",
"q",
"=",
"models",
".",
"Biosample",
".",
"delete",
"(",
")",
".",
"where",
"(",
"models",
".",
"Biosample",
".",
"id",
"==",
"biosample",
".",
"getId",
"(",
")",
")",
"q",
".",
"e... | 33.714286 | 0.008264 |
async def send_code_request(self, phone, *, force_sms=False):
"""
Sends a code request to the specified phone number.
Args:
phone (`str` | `int`):
The phone to which the code will be sent.
force_sms (`bool`, optional):
Whether to force se... | [
"async",
"def",
"send_code_request",
"(",
"self",
",",
"phone",
",",
"*",
",",
"force_sms",
"=",
"False",
")",
":",
"phone",
"=",
"utils",
".",
"parse_phone",
"(",
"phone",
")",
"or",
"self",
".",
"_phone",
"phone_hash",
"=",
"self",
".",
"_phone_code_ha... | 31.657895 | 0.001613 |
def reply(self, text, loop_ms=500, max_len=None):
"""Reply to a string of text. If the input is not already
Unicode, it will be decoded as utf-8."""
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in ... | [
"def",
"reply",
"(",
"self",
",",
"text",
",",
"loop_ms",
"=",
"500",
",",
"max_len",
"=",
"None",
")",
":",
"if",
"type",
"(",
"text",
")",
"!=",
"types",
".",
"UnicodeType",
":",
"# Assume that non-Unicode text is encoded as utf-8, which",
"# should be somewha... | 34.065421 | 0.0008 |
def _filter_statements(statements, agents):
"""Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements t... | [
"def",
"_filter_statements",
"(",
"statements",
",",
"agents",
")",
":",
"filtered_statements",
"=",
"[",
"]",
"for",
"s",
"in",
"stmts",
":",
"if",
"all",
"(",
"[",
"a",
"is",
"not",
"None",
"for",
"a",
"in",
"s",
".",
"agent_list",
"(",
")",
"]",
... | 32.791667 | 0.002469 |
def _get_struct_linestylearray(self, shape_number):
"""Get the values for the LINESTYLEARRAY record."""
obj = _make_object("LineStyleArray")
obj.LineStyleCount = count = unpack_ui8(self._src)
if count == 0xFF:
obj.LineStyleCountExtended = count = unpack_ui16(self._src)
... | [
"def",
"_get_struct_linestylearray",
"(",
"self",
",",
"shape_number",
")",
":",
"obj",
"=",
"_make_object",
"(",
"\"LineStyleArray\"",
")",
"obj",
".",
"LineStyleCount",
"=",
"count",
"=",
"unpack_ui8",
"(",
"self",
".",
"_src",
")",
"if",
"count",
"==",
"0... | 39.047619 | 0.00119 |
def query(self, query, *args, prefetch=None, timeout=None):
"""
make a read only query. Ideal for select statements.
This method converts the query to a prepared statement
and uses a cursor to return the results. So you only get
so many rows at a time. This can dramatically incre... | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"prefetch",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"compiled_q",
",",
"compiled_args",
"=",
"compile_query",
"(",
"query",
")",
"query",
",",
"args",
"=",
"compiled_q",
",",... | 44.774194 | 0.00141 |
def _validate_importers(importers):
"""Validates the importers and decorates the callables with our output
formatter.
"""
# They could have no importers, that's chill
if importers is None:
return None
def _to_importer(priority, func):
assert isinstance(priority, int), priority
... | [
"def",
"_validate_importers",
"(",
"importers",
")",
":",
"# They could have no importers, that's chill",
"if",
"importers",
"is",
"None",
":",
"return",
"None",
"def",
"_to_importer",
"(",
"priority",
",",
"func",
")",
":",
"assert",
"isinstance",
"(",
"priority",
... | 34.6 | 0.001876 |
async def delete_activity(self, context: TurnContext, conversation_reference: ConversationReference):
"""
Deletes an activity that was previously sent to a channel. It should be noted that not all
channels support this feature.
:param context:
:param conversation_reference:
... | [
"async",
"def",
"delete_activity",
"(",
"self",
",",
"context",
":",
"TurnContext",
",",
"conversation_reference",
":",
"ConversationReference",
")",
":",
"try",
":",
"client",
"=",
"self",
".",
"create_connector_client",
"(",
"conversation_reference",
".",
"service... | 48 | 0.011679 |
def abort(status_code, detail='', headers=None, comment=None, **kw):
'''
Raise an HTTP status code, as specified. Useful for returning status
codes like 401 Unauthorized or 403 Forbidden.
:param status_code: The HTTP status code as an integer.
:param detail: The message to send along, as a string.
... | [
"def",
"abort",
"(",
"status_code",
",",
"detail",
"=",
"''",
",",
"headers",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"# If there is a traceback, we need to catch it for a re-raise",
"try",
":",
"_",
",",
"_",
",",
"traceback... | 36.172414 | 0.000929 |
def parse_location(location):
"""Parse latitude and longitude from string location.
Args:
location (str): String to parse
Returns:
tuple of float: Latitude and longitude of location
"""
def split_dms(text, hemisphere):
"""Split degrees, minutes and seconds string.
... | [
"def",
"parse_location",
"(",
"location",
")",
":",
"def",
"split_dms",
"(",
"text",
",",
"hemisphere",
")",
":",
"\"\"\"Split degrees, minutes and seconds string.\n\n Args:\n text (str): Text to split\n\n Returns::\n float: Decimal degrees\n \"... | 31.540984 | 0.000504 |
def chainCerts(data):
"""
Matches and returns any certificates found except the first match.
Regex code copied from L{twisted.internet.endpoints._parseSSL}.
Related ticket: https://twistedmatrix.com/trac/ticket/7732
@type path: L{bytes}
@param data: PEM-encoded data containing the certificates... | [
"def",
"chainCerts",
"(",
"data",
")",
":",
"matches",
"=",
"re",
".",
"findall",
"(",
"r'(-----BEGIN CERTIFICATE-----\\n.+?\\n-----END CERTIFICATE-----)'",
",",
"data",
",",
"flags",
"=",
"re",
".",
"DOTALL",
")",
"chainCertificates",
"=",
"[",
"Certificate",
"."... | 32.25 | 0.001506 |
def step(darray, *args, **kwargs):
"""
Step plot of DataArray index against values
Similar to :func:`matplotlib:matplotlib.pyplot.step`
Parameters
----------
where : {'pre', 'post', 'mid'}, optional, default 'pre'
Define where the steps should be placed:
- 'pre': The y value is... | [
"def",
"step",
"(",
"darray",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'ls'",
"in",
"kwargs",
".",
"keys",
"(",
")",
")",
"and",
"(",
"'linestyle'",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
")",
":",
"kwargs",
"[",
... | 38.315789 | 0.00067 |
def validator(names_or_instance, names=None, func=None):
"""Specify a callback function to fire on class validation OR property set
This function has two modes of operation:
1. Registering callback functions that validate Property values when
they are set, before the change is saved to the HasPrope... | [
"def",
"validator",
"(",
"names_or_instance",
",",
"names",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
"and",
"func",
"is",
"None",
":",
"if",
"callable",
"(",
"names_or_instance",
")",
":",
"return",
"ClassValidator",
... | 38.973684 | 0.000329 |
def create_organizations_parser(stream):
"""Create an organizations parser for the given stream.
Factory function that creates an organizations parser for the
given stream. The stream is only used to guess the type of the
required parser.
:param stream: stream used to guess the type of the parser
... | [
"def",
"create_organizations_parser",
"(",
"stream",
")",
":",
"import",
"sortinghat",
".",
"parsing",
"as",
"parsing",
"# First, try with default parser",
"for",
"p",
"in",
"parsing",
".",
"SORTINGHAT_ORGS_PARSERS",
":",
"klass",
"=",
"parsing",
".",
"SORTINGHAT_ORGS... | 30.8 | 0.001259 |
def user_config_dir(appname, roaming=True):
"""Return full path to the user-specific config dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"roaming" (boolean, default True) can be set False to not use the
Windo... | [
"def",
"user_config_dir",
"(",
"appname",
",",
"roaming",
"=",
"True",
")",
":",
"if",
"WINDOWS",
":",
"path",
"=",
"user_data_dir",
"(",
"appname",
",",
"roaming",
"=",
"roaming",
")",
"elif",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"path",
"="... | 41.344828 | 0.000815 |
def cylindrical(cls, mag, theta, z=0):
'''Returns a Vector instance from cylindircal coordinates'''
return cls(
mag * math.cos(theta), # X
mag * math.sin(theta), # Y
z # Z
) | [
"def",
"cylindrical",
"(",
"cls",
",",
"mag",
",",
"theta",
",",
"z",
"=",
"0",
")",
":",
"return",
"cls",
"(",
"mag",
"*",
"math",
".",
"cos",
"(",
"theta",
")",
",",
"# X",
"mag",
"*",
"math",
".",
"sin",
"(",
"theta",
")",
",",
"# Y",
"z",... | 32.857143 | 0.008475 |
def get_wildcard(self):
"""Return the wildcard bits notation of the netmask."""
return _convert(self._ip, notation=NM_WILDCARD,
inotation=IP_DOT, _check=False, _isnm=self._isnm) | [
"def",
"get_wildcard",
"(",
"self",
")",
":",
"return",
"_convert",
"(",
"self",
".",
"_ip",
",",
"notation",
"=",
"NM_WILDCARD",
",",
"inotation",
"=",
"IP_DOT",
",",
"_check",
"=",
"False",
",",
"_isnm",
"=",
"self",
".",
"_isnm",
")"
] | 53.5 | 0.009217 |
def request(self, method, url, fields=None, headers=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be use... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"method",
"=",
"method",
".",
"upper",
"(",
")",
"if",
"method",
"in",
"self",
".",
"_encode_u... | 48.619048 | 0.001921 |
def to_fastg(infile, outfile, circular=None):
'''Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs'''
if circular is... | [
"def",
"to_fastg",
"(",
"infile",
",",
"outfile",
",",
"circular",
"=",
"None",
")",
":",
"if",
"circular",
"is",
"None",
":",
"to_circularise",
"=",
"set",
"(",
")",
"elif",
"type",
"(",
"circular",
")",
"is",
"not",
"set",
":",
"f",
"=",
"utils",
... | 32.615385 | 0.001527 |
async def get_data(self):
"""Retrieve the data."""
url = '{}/{}'.format(self.url, 'all')
try:
with async_timeout.timeout(5, loop=self._loop):
if self.password is None:
response = await self._session.get(url)
else:
... | [
"async",
"def",
"get_data",
"(",
"self",
")",
":",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"'all'",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"5",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
":",
... | 41.9 | 0.002334 |
def has_bad_headers(self):
"""
Checks for bad headers i.e. newlines in subject, sender or recipients.
RFC5322 allows multiline CRLF with trailing whitespace (FWS) in headers
"""
headers = [self.sender, self.reply_to] + self.recipients
for header in headers:
if... | [
"def",
"has_bad_headers",
"(",
"self",
")",
":",
"headers",
"=",
"[",
"self",
".",
"sender",
",",
"self",
".",
"reply_to",
"]",
"+",
"self",
".",
"recipients",
"for",
"header",
"in",
"headers",
":",
"if",
"_has_newline",
"(",
"header",
")",
":",
"retur... | 38.318182 | 0.002315 |
def set_zone(timezone):
'''
Unlinks, then symlinks /etc/localtime to the set timezone.
The timezone is crucial to several system processes, each of which SHOULD
be restarted (for instance, whatever you system uses as its cron and
syslog daemons). This will not be automagically done and must be done... | [
"def",
"set_zone",
"(",
"timezone",
")",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'timedatectl'",
")",
":",
"try",
":",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'timedatectl set-timezone {0}'",
".",
"format",
"(",
"timezone",
")",
... | 33.27027 | 0.001972 |
def add_udev_trigger(self, trigger_action, subsystem):
"""
Subscribe to the requested udev subsystem and apply the given action.
"""
if self._py3_wrapper.udev_monitor.subscribe(self, trigger_action, subsystem):
if trigger_action == "refresh_and_freeze":
# FIXM... | [
"def",
"add_udev_trigger",
"(",
"self",
",",
"trigger_action",
",",
"subsystem",
")",
":",
"if",
"self",
".",
"_py3_wrapper",
".",
"udev_monitor",
".",
"subscribe",
"(",
"self",
",",
"trigger_action",
",",
"subsystem",
")",
":",
"if",
"trigger_action",
"==",
... | 55.625 | 0.00885 |
def adjustHspsForPlotting(self, titleAlignments):
"""
Our HSPs are about to be plotted. If we are using e-values, these need
to be adjusted.
@param titleAlignments: An instance of L{TitleAlignment}.
"""
# If we're using bit scores, there's nothing to do.
if self.... | [
"def",
"adjustHspsForPlotting",
"(",
"self",
",",
"titleAlignments",
")",
":",
"# If we're using bit scores, there's nothing to do.",
"if",
"self",
".",
"scoreClass",
"is",
"HigherIsBetterScore",
":",
"return",
"# Convert all e-values to high positive values, and keep track of the"... | 40.372093 | 0.001125 |
def pad_to_size(data, shape, value=0.0):
"""
This is similar to `pad`, except you specify the final shape of the array.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
shape : tuple
Final shape of padded array. Should be tuple of length ``data.ndim``.... | [
"def",
"pad_to_size",
"(",
"data",
",",
"shape",
",",
"value",
"=",
"0.0",
")",
":",
"shape",
"=",
"[",
"data",
".",
"shape",
"[",
"i",
"]",
"if",
"shape",
"[",
"i",
"]",
"==",
"-",
"1",
"else",
"shape",
"[",
"i",
"]",
"for",
"i",
"in",
"rang... | 32.659091 | 0.000676 |
def try_greyscale(pixels, alpha=False, dirty_alpha=True):
"""
Check if flatboxed RGB `pixels` could be converted to greyscale
If could - return iterator with greyscale pixels,
otherwise return `False` constant
"""
planes = 3 + bool(alpha)
res = list()
apix = list()
for row in pixels... | [
"def",
"try_greyscale",
"(",
"pixels",
",",
"alpha",
"=",
"False",
",",
"dirty_alpha",
"=",
"True",
")",
":",
"planes",
"=",
"3",
"+",
"bool",
"(",
"alpha",
")",
"res",
"=",
"list",
"(",
")",
"apix",
"=",
"list",
"(",
")",
"for",
"row",
"in",
"pi... | 27.727273 | 0.001585 |
def check_indexes_all_same(indexes, message="Indexes are not equal."):
"""Check that a list of Index objects are all equal.
Parameters
----------
indexes : iterable[pd.Index]
Iterable of indexes to check.
Raises
------
ValueError
If the indexes are not all the same.
"""... | [
"def",
"check_indexes_all_same",
"(",
"indexes",
",",
"message",
"=",
"\"Indexes are not equal.\"",
")",
":",
"iterator",
"=",
"iter",
"(",
"indexes",
")",
"first",
"=",
"next",
"(",
"iterator",
")",
"for",
"other",
"in",
"iterator",
":",
"same",
"=",
"(",
... | 28.32 | 0.001366 |
def acceptance_prob(old_cost, new_cost, T):
"""annealing equation, with modifications to work towards a lower value"""
#if start pos is not valid, always move
if old_cost == 1e20:
return 1.0
#if we have found a valid ps before, never move to nonvalid pos
if new_cost == 1e20:
return 0... | [
"def",
"acceptance_prob",
"(",
"old_cost",
",",
"new_cost",
",",
"T",
")",
":",
"#if start pos is not valid, always move",
"if",
"old_cost",
"==",
"1e20",
":",
"return",
"1.0",
"#if we have found a valid ps before, never move to nonvalid pos",
"if",
"new_cost",
"==",
"1e2... | 40.923077 | 0.011029 |
def main():
'''This is the main function of this script.
The current script args are shown below ::
Usage: checkplotlist [-h] [--search SEARCH] [--sortby SORTBY]
[--filterby FILTERBY] [--splitout SPLITOUT]
[--outprefix OUTPREFIX] [--maxkeyworke... | [
"def",
"main",
"(",
")",
":",
"####################",
"## PARSE THE ARGS ##",
"####################",
"aparser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"epilog",
"=",
"PROGEPILOG",
",",
"description",
"=",
"PROGDESC",
",",
"formatter_class",
"=",
"argparse",
"... | 38.147114 | 0.002236 |
def raise_for_invalid_annotation_value(self, line: str, position: int, key: str, value: str) -> None:
"""Raise an exception if the annotation is not defined.
:raises: IllegalAnnotationValueWarning or MissingAnnotationRegexWarning
"""
if self._in_debug_mode:
return
i... | [
"def",
"raise_for_invalid_annotation_value",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"if",
"self",
".",
"_in_debug_mode",
":",
"return",
"if",
"self",
... | 56.125 | 0.009858 |
def check_connection_state(self):
"""Check the state of the connection using connection state request.
This sends a CONNECTION_STATE_REQUEST. This method will only return
True, if the connection is established and no error code is returned
from the KNX/IP gateway
"""
if ... | [
"def",
"check_connection_state",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"self",
".",
"connection_state",
"=",
"-",
"1",
"return",
"False",
"frame",
"=",
"KNXIPFrame",
"(",
"KNXIPFrame",
".",
"CONNECTIONSTATE_REQUEST",
")",
"frame",
... | 40.402597 | 0.000628 |
def subgroup(self, t, i):
"""Handle parenthesis."""
current = []
# (?flags)
flags = self.get_flags(i)
if flags:
self.flags(flags[2:-1])
return [flags]
# (?#comment)
comments = self.get_comments(i)
if comments:
return ... | [
"def",
"subgroup",
"(",
"self",
",",
"t",
",",
"i",
")",
":",
"current",
"=",
"[",
"]",
"# (?flags)",
"flags",
"=",
"self",
".",
"get_flags",
"(",
"i",
")",
"if",
"flags",
":",
"self",
".",
"flags",
"(",
"flags",
"[",
"2",
":",
"-",
"1",
"]",
... | 22.636364 | 0.001925 |
def bam2mat(args):
"""
%prog bam2mat input.bam
Convert bam file to .mat format, which is simply numpy 2D array. Important
parameter is the resolution, which is the cell size. Small cell size lead
to more fine-grained heatmap, but leads to large .mat size and slower
plotting.
"""
import ... | [
"def",
"bam2mat",
"(",
"args",
")",
":",
"import",
"pysam",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"percentage",
"p",
"=",
"OptionParser",
"(",
"bam2mat",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--resolution\"",
",",
"default",
... | 33.24 | 0.000292 |
def by_population_density(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.population_density.name,
ascending=False,
... | [
"def",
"by_population_density",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"population_density",
".",
"name",
",",
"asce... | 40.666667 | 0.010681 |
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position] | [
"def",
"peek",
"(",
"self",
")",
":",
"if",
"self",
".",
"position",
">=",
"len",
"(",
"self",
".",
"tokens",
")",
":",
"return",
"None",
"return",
"self",
".",
"tokens",
"[",
"self",
".",
"position",
"]"
] | 23.8 | 0.008097 |
def simple_prot(x, start):
"""Find the first peak to the right of start"""
# start must b >= 1
for i in range(start,len(x)-1):
a,b,c = x[i-1], x[i], x[i+1]
if b - a > 0 and b -c >= 0:
return i
else:
return None | [
"def",
"simple_prot",
"(",
"x",
",",
"start",
")",
":",
"# start must b >= 1",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"len",
"(",
"x",
")",
"-",
"1",
")",
":",
"a",
",",
"b",
",",
"c",
"=",
"x",
"[",
"i",
"-",
"1",
"]",
",",
"x",
"["... | 23.181818 | 0.022642 |
def get_versions():
"""
Wrap in a function to ensure that we don't run this every time a CLI
command runs (yuck!)
Also protects import of `requests` from issues when grabbed by setuptools.
More on that inline
"""
# import in the func (rather than top-level scope) so that at setup time,
... | [
"def",
"get_versions",
"(",
")",
":",
"# import in the func (rather than top-level scope) so that at setup time,",
"# `requests` isn't required -- otherwise, setuptools will fail to run",
"# because requests isn't installed yet.",
"import",
"requests",
"try",
":",
"version_data",
"=",
"r... | 36.181818 | 0.001224 |
def pick_unused_port(pid=None, portserver_address=None):
"""A pure python implementation of PickUnusedPort.
Args:
pid: PID to tell the portserver to associate the reservation with. If
None, the current process's PID is used.
portserver_address: The address (path) of a unix domain socket
... | [
"def",
"pick_unused_port",
"(",
"pid",
"=",
"None",
",",
"portserver_address",
"=",
"None",
")",
":",
"try",
":",
"# Instead of `if _free_ports:` to handle the race condition.",
"port",
"=",
"_free_ports",
".",
"pop",
"(",
")",
"except",
"KeyError",
":",
"pass",
"... | 39.421053 | 0.000651 |
def read_config(filename):
"""Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: k... | [
"def",
"read_config",
"(",
"filename",
")",
":",
"file_type",
"=",
"\"yaml\"",
"if",
"filename",
".",
"endswith",
"(",
"\".yaml\"",
")",
"else",
"\"config\"",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"if",
"file_type",
"==",
"\"yaml\"",
... | 30.014286 | 0.000461 |
def _dedup(items, insensitive):
'''
Deduplicate an item list, and preserve order.
For case-insensitive lists, drop items if they case-insensitively match
a prior item.
'''
deduped = []
if insensitive:
i_deduped = []
for item in items:
lowered = item.lower()
... | [
"def",
"_dedup",
"(",
"items",
",",
"insensitive",
")",
":",
"deduped",
"=",
"[",
"]",
"if",
"insensitive",
":",
"i_deduped",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"lowered",
"=",
"item",
".",
"lower",
"(",
")",
"if",
"lowered",
"not",
... | 27.2 | 0.001776 |
def multi_path_generator(pathnames):
"""
yields (name,chunkgen) for all of the files found under the list
of pathnames given. This is recursive, so directories will have
their contents emitted. chunkgen is a function that can called and
iterated over to obtain the contents of the file in multiple
... | [
"def",
"multi_path_generator",
"(",
"pathnames",
")",
":",
"for",
"pathname",
"in",
"pathnames",
":",
"if",
"isdir",
"(",
"pathname",
")",
":",
"for",
"entry",
"in",
"directory_generator",
"(",
"pathname",
")",
":",
"yield",
"entry",
"else",
":",
"yield",
... | 35.266667 | 0.001842 |
def path(self):
"""HTTP full path constraint. (read-only).
"""
path = self.__prefix
if self is not self.over:
path = self.over.path + path
return path | [
"def",
"path",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"__prefix",
"if",
"self",
"is",
"not",
"self",
".",
"over",
":",
"path",
"=",
"self",
".",
"over",
".",
"path",
"+",
"path",
"return",
"path"
] | 28 | 0.009901 |
def __add_actions(self):
"""
Sets Component actions.
"""
LOGGER.debug("> Adding '{0}' Component actions.".format(self.__class__.__name__))
add_project_action = self.__engine.actions_manager.get_action(
"Actions|Umbra|Components|factory.script_editor|&File|Add Projec... | [
"def",
"__add_actions",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Adding '{0}' Component actions.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"add_project_action",
"=",
"self",
".",
"__engine",
".",
"actions_manage... | 53.333333 | 0.0086 |
def get_venue(self, id, **data):
"""
GET /venues/:id/
Returns a :format:`venue` object.
"""
return self.get("/venues/{0}/".format(id), data=data) | [
"def",
"get_venue",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/venues/{0}/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | 26.857143 | 0.015464 |
def get_grounded_agent(gene_name):
"""Return a grounded Agent based on an HGNC symbol."""
db_refs = {'TEXT': gene_name}
if gene_name in hgnc_map:
gene_name = hgnc_map[gene_name]
hgnc_id = hgnc_client.get_hgnc_id(gene_name)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
up_id = hgnc_cl... | [
"def",
"get_grounded_agent",
"(",
"gene_name",
")",
":",
"db_refs",
"=",
"{",
"'TEXT'",
":",
"gene_name",
"}",
"if",
"gene_name",
"in",
"hgnc_map",
":",
"gene_name",
"=",
"hgnc_map",
"[",
"gene_name",
"]",
"hgnc_id",
"=",
"hgnc_client",
".",
"get_hgnc_id",
"... | 34.692308 | 0.00216 |
def add_callback(self, user_gpio, edge=RISING_EDGE, func=None):
"""
Calls a user supplied function (a callback) whenever the
specified gpio edge is detected.
user_gpio:= 0-31.
edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
func:= user supplied callback... | [
"def",
"add_callback",
"(",
"self",
",",
"user_gpio",
",",
"edge",
"=",
"RISING_EDGE",
",",
"func",
"=",
"None",
")",
":",
"cb",
"=",
"Callback",
"(",
"self",
".",
"_notify",
",",
"user_gpio",
",",
"edge",
",",
"func",
")",
"yield",
"from",
"self",
"... | 29.073171 | 0.001623 |
def endpoint_loader(request, application, model, **kwargs):
"""Load an AJAX endpoint.
This will load either an ad-hoc endpoint or it will load up a model
endpoint depending on what it finds. It first attempts to load ``model``
as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if
... | [
"def",
"endpoint_loader",
"(",
"request",
",",
"application",
",",
"model",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"!=",
"\"POST\"",
":",
"raise",
"AJAXError",
"(",
"400",
",",
"_",
"(",
"'Invalid HTTP method used.'",
")",
")",
... | 30.606557 | 0.002076 |
def set_cell(self, column_family_id, column, value, timestamp=None):
"""Sets a value in this row.
The cell is determined by the ``row_key`` of this :class:`DirectRow`
and the ``column``. The ``column`` must be in an existing
:class:`.ColumnFamily` (as determined by ``column_family_id``)... | [
"def",
"set_cell",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"self",
".",
"_set_cell",
"(",
"column_family_id",
",",
"column",
",",
"value",
",",
"timestamp",
"=",
"timestamp",
",",
"state",... | 41.263158 | 0.001869 |
def load_object(path):
"""Return the Python object represented by dotted *path*."""
i = path.rfind('.')
module_name, object_name = path[:i], path[i + 1:]
# Load module.
try:
module = import_module(module_name)
except ImportError:
raise ImproperlyConfigured('Module %r not found' %... | [
"def",
"load_object",
"(",
"path",
")",
":",
"i",
"=",
"path",
".",
"rfind",
"(",
"'.'",
")",
"module_name",
",",
"object_name",
"=",
"path",
"[",
":",
"i",
"]",
",",
"path",
"[",
"i",
"+",
"1",
":",
"]",
"# Load module.",
"try",
":",
"module",
"... | 37.588235 | 0.001527 |
def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment
"""
result = self._wait_incrementing_start + (self.... | [
"def",
"incrementing_sleep",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"result",
"=",
"self",
".",
"_wait_incrementing_start",
"+",
"(",
"self",
".",
"_wait_incrementing_increment",
"*",
"(",
"previous_attempt_number",
"... | 49 | 0.008909 |
def make_folder_for_today(log_dir):
"""Creates the folder log_dir/yyyy/mm/dd in log_dir if it doesn't exist
and returns the full path of the folder."""
now = datetime.datetime.now()
sub_folders_list = ['{0:04d}'.format(now.year),
'{0:02d}'.format(now.month),
... | [
"def",
"make_folder_for_today",
"(",
"log_dir",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"sub_folders_list",
"=",
"[",
"'{0:04d}'",
".",
"format",
"(",
"now",
".",
"year",
")",
",",
"'{0:02d}'",
".",
"format",
"(",
"now",
... | 40.076923 | 0.001876 |
def show_scan_report(audio_filepaths, album_dir, r128_data):
""" Display loudness scan results. """
# track loudness/peak
for audio_filepath in audio_filepaths:
try:
loudness, peak = r128_data[audio_filepath]
except KeyError:
loudness, peak = "SKIPPED", "SKIPPED"
else:
loudness = "%.... | [
"def",
"show_scan_report",
"(",
"audio_filepaths",
",",
"album_dir",
",",
"r128_data",
")",
":",
"# track loudness/peak",
"for",
"audio_filepath",
"in",
"audio_filepaths",
":",
"try",
":",
"loudness",
",",
"peak",
"=",
"r128_data",
"[",
"audio_filepath",
"]",
"exc... | 34.655172 | 0.017425 |
def get_child(self, *types):
"""
:param types: list of requested types.
:return: the first (and in most useful cases only) child of specific type(s).
"""
children = list(self.get_children(*types))
return children[0] if any(children) else None | [
"def",
"get_child",
"(",
"self",
",",
"*",
"types",
")",
":",
"children",
"=",
"list",
"(",
"self",
".",
"get_children",
"(",
"*",
"types",
")",
")",
"return",
"children",
"[",
"0",
"]",
"if",
"any",
"(",
"children",
")",
"else",
"None"
] | 40.571429 | 0.010345 |
def phenotype_to_res_set(phenotype, resources):
"""
Converts a binary string to a set containing the resources indicated by
the bits in the string.
Inputs: phenotype - a binary string
resources - a list of string indicating which resources correspond
to which indices... | [
"def",
"phenotype_to_res_set",
"(",
"phenotype",
",",
"resources",
")",
":",
"assert",
"(",
"phenotype",
"[",
"0",
":",
"2",
"]",
"==",
"\"0b\"",
")",
"phenotype",
"=",
"phenotype",
"[",
"2",
":",
"]",
"# Fill in leading zeroes",
"while",
"len",
"(",
"phen... | 29.72 | 0.001304 |
def create_store(self):
""" Creates store object """
if self.store_class is not None:
return self.store_class.load(self.client.webfinger, self)
raise NotImplementedError("You need to specify PyPump.store_class or override PyPump.create_store method.") | [
"def",
"create_store",
"(",
"self",
")",
":",
"if",
"self",
".",
"store_class",
"is",
"not",
"None",
":",
"return",
"self",
".",
"store_class",
".",
"load",
"(",
"self",
".",
"client",
".",
"webfinger",
",",
"self",
")",
"raise",
"NotImplementedError",
"... | 47.166667 | 0.010417 |
def manual_migration():
"""
Simple interactive function to pause the deployment.
A manual migration can be done two different ways:
Option 1: Enter y to exit the current deployment. When migration is completed run deploy again.
Option 2: run the migration in a separate shell
"""
if env.IN... | [
"def",
"manual_migration",
"(",
")",
":",
"if",
"env",
".",
"INTERACTIVITY",
":",
"print",
"\"A manual migration can be done two different ways:\"",
"print",
"\"Option 1: Enter y to exit the current deployment. When migration is completed run deploy again.\"",
"print",
"\"Option 2: run... | 48.588235 | 0.009501 |
def get_cb_depth_set(cb_histogram, cb_cutoff):
''' Returns a set of barcodes with a minimum number of reads
'''
cb_keep_set = set()
if not cb_histogram:
return cb_keep_set
with read_cbhistogram(cb_histogram) as fh:
cb_map = dict(p.strip().split() for p in fh)
cb_keep_set = s... | [
"def",
"get_cb_depth_set",
"(",
"cb_histogram",
",",
"cb_cutoff",
")",
":",
"cb_keep_set",
"=",
"set",
"(",
")",
"if",
"not",
"cb_histogram",
":",
"return",
"cb_keep_set",
"with",
"read_cbhistogram",
"(",
"cb_histogram",
")",
"as",
"fh",
":",
"cb_map",
"=",
... | 38.769231 | 0.001938 |
def get_decimal_precision(number):
"""Return maximum precision of a decimal instance's fractional part.
Precision is extracted from the fractional part only.
"""
# Copied from: https://github.com/mahmoud/boltons/pull/59
assert isinstance(number, decimal.Decimal)
decimal_tuple = number.normalize(... | [
"def",
"get_decimal_precision",
"(",
"number",
")",
":",
"# Copied from: https://github.com/mahmoud/boltons/pull/59",
"assert",
"isinstance",
"(",
"number",
",",
"decimal",
".",
"Decimal",
")",
"decimal_tuple",
"=",
"number",
".",
"normalize",
"(",
")",
".",
"as_tuple... | 41.5 | 0.002358 |
def convert(self, version):
"""convert *MDF* to other version
Parameters
----------
version : str
new mdf file version from ('2.00', '2.10', '2.14', '3.00', '3.10',
'3.20', '3.30', '4.00', '4.10', '4.11'); default '4.10'
Returns
-------
o... | [
"def",
"convert",
"(",
"self",
",",
"version",
")",
":",
"version",
"=",
"validate_version_argument",
"(",
"version",
")",
"out",
"=",
"MDF",
"(",
"version",
"=",
"version",
")",
"out",
".",
"header",
".",
"start_time",
"=",
"self",
".",
"header",
".",
... | 39.694118 | 0.001879 |
def option_map(self):
"""Map command-line options to args."""
option_map = OrderedDict()
for arg in self.args.values():
for option in arg.options:
option_map[option] = arg
return option_map | [
"def",
"option_map",
"(",
"self",
")",
":",
"option_map",
"=",
"OrderedDict",
"(",
")",
"for",
"arg",
"in",
"self",
".",
"args",
".",
"values",
"(",
")",
":",
"for",
"option",
"in",
"arg",
".",
"options",
":",
"option_map",
"[",
"option",
"]",
"=",
... | 34.714286 | 0.008032 |
def update_panel(self, panel_obj, version=None, date_obj=None):
"""Replace a existing gene panel with a new one
Keeps the object id
Args:
panel_obj(dict)
version(float)
date_obj(datetime.datetime)
Returns:
updated_panel(dict)
"""... | [
"def",
"update_panel",
"(",
"self",
",",
"panel_obj",
",",
"version",
"=",
"None",
",",
"date_obj",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"Updating panel %s\"",
",",
"panel_obj",
"[",
"'panel_name'",
"]",
")",
"# update date of panel to \"today\"",
... | 30.676471 | 0.001859 |
def locked_delete(self):
"""Delete credentials from the SQLAlchemy datastore."""
filters = {self.key_name: self.key_value}
self.session.query(self.model_class).filter_by(**filters).delete() | [
"def",
"locked_delete",
"(",
"self",
")",
":",
"filters",
"=",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model_class",
")",
".",
"filter_by",
"(",
"*",
"*",
"filters",
"... | 52.5 | 0.00939 |
def to_html(graph: BELGraph) -> str:
"""Render the graph as an HTML string.
Common usage may involve writing to a file like:
>>> from pybel.examples import sialic_acid_graph
>>> with open('html_output.html', 'w') as file:
... print(to_html(sialic_acid_graph), file=file)
"""
context = g... | [
"def",
"to_html",
"(",
"graph",
":",
"BELGraph",
")",
"->",
"str",
":",
"context",
"=",
"get_network_summary_dict",
"(",
"graph",
")",
"summary_dict",
"=",
"graph",
".",
"summary_dict",
"(",
")",
"citation_years",
"=",
"context",
"[",
"'citation_years'",
"]",
... | 43.296296 | 0.002091 |
def spellcheck(word, wordlist, depth = 2):
"""
Given a word list and a depth parameter, return all words w' in the wordlist
with LevenshteinDistance(word, w') <= depth
:param word:
:param wordlist:
>>> Dic = ['pes', 'pesse', 'pease', 'peis', 'peisse', 'pise', 'peose', 'poese', 'poisen']
>>... | [
"def",
"spellcheck",
"(",
"word",
",",
"wordlist",
",",
"depth",
"=",
"2",
")",
":",
"Aut",
"=",
"LevenshteinAutomaton",
"(",
"word",
",",
"depth",
"=",
"depth",
")",
".",
"convert_to_deterministic",
"(",
")",
"W",
"=",
"make_worlist_trie",
"(",
"wordlist"... | 36.736842 | 0.009777 |
def find_log_dir(log_dir=None):
"""Returns the most suitable directory to put log files into.
Args:
log_dir: str|None, if specified, the logfile(s) will be created in that
directory. Otherwise if the --log_dir command-line flag is provided,
the logfile will be created in that directory. Other... | [
"def",
"find_log_dir",
"(",
"log_dir",
"=",
"None",
")",
":",
"# Get a list of possible log dirs (will try to use them in order).",
"if",
"log_dir",
":",
"# log_dir was explicitly specified as an arg, so use it and it alone.",
"dirs",
"=",
"[",
"log_dir",
"]",
"elif",
"FLAGS",
... | 38.68 | 0.0111 |
def _check_select(self):
'''Select task to fetch & process'''
while self._send_buffer:
_task = self._send_buffer.pop()
try:
# use force=False here to prevent automatic send_buffer append and get exception
self.send_task(_task, False)
ex... | [
"def",
"_check_select",
"(",
"self",
")",
":",
"while",
"self",
".",
"_send_buffer",
":",
"_task",
"=",
"self",
".",
"_send_buffer",
".",
"pop",
"(",
")",
"try",
":",
"# use force=False here to prevent automatic send_buffer append and get exception",
"self",
".",
"s... | 37.586538 | 0.002243 |
def cli_help(context, command_name, general_parser, command_parsers):
"""
Outputs help information.
See :py:mod:`swiftly.cli.help` for context usage information.
See :py:class:`CLIHelp` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param... | [
"def",
"cli_help",
"(",
"context",
",",
"command_name",
",",
"general_parser",
",",
"command_parsers",
")",
":",
"if",
"command_name",
"==",
"'for'",
":",
"command_name",
"=",
"'fordo'",
"with",
"context",
".",
"io_manager",
".",
"with_stdout",
"(",
")",
"as",... | 38.035714 | 0.000916 |
def _create_adapter_type(network_adapter, adapter_type,
network_adapter_label=''):
'''
Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual
ethernet card information
network_adapter
None or VirtualEthernet object
adapter_type
String, type... | [
"def",
"_create_adapter_type",
"(",
"network_adapter",
",",
"adapter_type",
",",
"network_adapter_label",
"=",
"''",
")",
":",
"log",
".",
"trace",
"(",
"'Configuring virtual machine network '",
"'adapter adapter_type=%s'",
",",
"adapter_type",
")",
"if",
"adapter_type",
... | 40.777778 | 0.001597 |
def _conditional_committors(source, sink, waypoint, tprob):
"""
Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this comp... | [
"def",
"_conditional_committors",
"(",
"source",
",",
"sink",
",",
"waypoint",
",",
"tprob",
")",
":",
"n_states",
"=",
"np",
".",
"shape",
"(",
"tprob",
")",
"[",
"0",
"]",
"forward_committors",
"=",
"_committors",
"(",
"[",
"source",
"]",
",",
"[",
"... | 32.575758 | 0.001354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.