text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def ascdiff(decl, lat):
""" Returns the Ascensional Difference of a point. """
delta = math.radians(decl)
phi = math.radians(lat)
ad = math.asin(math.tan(delta) * math.tan(phi))
return math.degrees(ad) | [
"def",
"ascdiff",
"(",
"decl",
",",
"lat",
")",
":",
"delta",
"=",
"math",
".",
"radians",
"(",
"decl",
")",
"phi",
"=",
"math",
".",
"radians",
"(",
"lat",
")",
"ad",
"=",
"math",
".",
"asin",
"(",
"math",
".",
"tan",
"(",
"delta",
")",
"*",
... | 36 | 10.666667 |
def cached_get(timeout, *params):
"""Decorator applied specifically to a view's get method"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(view_or_request, *args, **kwargs):
# The type of the request gets muddled when using a fu... | [
"def",
"cached_get",
"(",
"timeout",
",",
"*",
"params",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"_wrapped_view",
"(",
"view_or_re... | 40.395349 | 20.034884 |
def py(self, output):
"""Output data as a nicely-formatted python data structure"""
import pprint
pprint.pprint(output, stream=self.outfile) | [
"def",
"py",
"(",
"self",
",",
"output",
")",
":",
"import",
"pprint",
"pprint",
".",
"pprint",
"(",
"output",
",",
"stream",
"=",
"self",
".",
"outfile",
")"
] | 40.25 | 12 |
def get_next(self):
"""Get the billing cycle after this one. May return None"""
return BillingCycle.objects.filter(date_range__gt=self.date_range).order_by('date_range').first() | [
"def",
"get_next",
"(",
"self",
")",
":",
"return",
"BillingCycle",
".",
"objects",
".",
"filter",
"(",
"date_range__gt",
"=",
"self",
".",
"date_range",
")",
".",
"order_by",
"(",
"'date_range'",
")",
".",
"first",
"(",
")"
] | 63.666667 | 28.666667 |
def nth(self, index):
"""
Return a query that selects the element at `index` (starts from 0).
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.nth(2).results
... | [
"def",
"nth",
"(",
"self",
",",
"index",
")",
":",
"def",
"_transform",
"(",
"xs",
")",
":",
"# pylint: disable=missing-docstring, invalid-name",
"try",
":",
"return",
"[",
"next",
"(",
"islice",
"(",
"iter",
"(",
"xs",
")",
",",
"index",
",",
"None",
")... | 28.857143 | 25.214286 |
def _loop(self, barrier):
"""Actual thread"""
if sys.platform != "win32":
self.loop = asyncio.new_event_loop()
else:
self.loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(self.loop)
barrier.wait()
try:
self.loop.run_forever()
... | [
"def",
"_loop",
"(",
"self",
",",
"barrier",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"\"win32\"",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"else",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"ProactorEventLoop... | 27.461538 | 14.615385 |
def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int]) -> None:
"""Simulate an op that is a mixtures of unitaries."""
probs, unitaries = zip(*protocols.mixture(op))
# We work around numpy barfing on choosing from a list of
# numpy arrays (wh... | [
"def",
"_simulate_mixture",
"(",
"self",
",",
"op",
":",
"ops",
".",
"Operation",
",",
"data",
":",
"_StateAndBuffer",
",",
"indices",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"probs",
",",
"unitaries",
"=",
"zip",
"(",
"*",
"protocols",
... | 54.571429 | 16.785714 |
def _refine_upcheck(merge, min_goodness):
"""Remove from the merge any entries which would be covered by entries
between their current position and the merge insertion position.
For example, the third entry of::
0011 -> N
0100 -> N
1000 -> N
X000 -> NE
Cannot be merged... | [
"def",
"_refine_upcheck",
"(",
"merge",
",",
"min_goodness",
")",
":",
"# Remove any entries which would be covered by entries above the merge",
"# position.",
"changed",
"=",
"False",
"for",
"i",
"in",
"sorted",
"(",
"merge",
".",
"entries",
",",
"reverse",
"=",
"Tru... | 39.826087 | 23.673913 |
def set_is_valid_rss(self):
"""Check to if this is actually a valid RSS feed"""
if self.title and self.link and self.description:
self.is_valid_rss = True
else:
self.is_valid_rss = False | [
"def",
"set_is_valid_rss",
"(",
"self",
")",
":",
"if",
"self",
".",
"title",
"and",
"self",
".",
"link",
"and",
"self",
".",
"description",
":",
"self",
".",
"is_valid_rss",
"=",
"True",
"else",
":",
"self",
".",
"is_valid_rss",
"=",
"False"
] | 38.166667 | 10.666667 |
def get_config_section(self, name):
"""
Get a section of a configuration
"""
if self.config.has_section(name):
return self.config.items(name)
return [] | [
"def",
"get_config_section",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"name",
")",
":",
"return",
"self",
".",
"config",
".",
"items",
"(",
"name",
")",
"return",
"[",
"]"
] | 28.142857 | 4.428571 |
def to_svg(self, converter=None):
"""Return a SVGDumper for this instruction.
:param converter: a :class:`
knittingpattern.convert.InstructionSVGCache.InstructionSVGCache` or
:obj:`None`. If :obj:`None` is given, the :func:`
knittingpattern.convert.InstructionSVGCache.defa... | [
"def",
"to_svg",
"(",
"self",
",",
"converter",
"=",
"None",
")",
":",
"if",
"converter",
"is",
"None",
":",
"from",
"knittingpattern",
".",
"convert",
".",
"InstructionSVGCache",
"import",
"default_svg_cache",
"converter",
"=",
"default_svg_cache",
"(",
")",
... | 41.066667 | 15.2 |
def stats(self, start, end, fields=None):
'''Perform a multivariate statistic calculation of this
:class:`ColumnTS` from a *start* date/datetime to an
*end* date/datetime.
:param start: Start date for analysis.
:param end: End date for analysis.
:param fields: Optional subset of :meth:`fields` to perfo... | [
"def",
"stats",
"(",
"self",
",",
"start",
",",
"end",
",",
"fields",
"=",
"None",
")",
":",
"start",
"=",
"self",
".",
"pickler",
".",
"dumps",
"(",
"start",
")",
"end",
"=",
"self",
".",
"pickler",
".",
"dumps",
"(",
"end",
")",
"backend",
"=",... | 41.133333 | 16.333333 |
def plot_decorate_rebits(basis=None, rebit_axes=REBIT_AXES):
"""
Decorates a figure with the boundary of rebit state space
and basis labels drawn from a :ref:`~qinfer.tomography.TomographyBasis`.
:param qinfer.tomography.TomographyBasis basis: Basis to use in
labeling axes.
:param list rebi... | [
"def",
"plot_decorate_rebits",
"(",
"basis",
"=",
"None",
",",
"rebit_axes",
"=",
"REBIT_AXES",
")",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"basis",
"is",
"not",
"None",
":",
"labels",
"=",
"list",
"(",
"map",
"(",
"r'$\\langle\\!\\langle {} ... | 35.25 | 21.5 |
def check_for_change(self):
"""
Determines if a new release has been made.
"""
r = self.local_renderer
lm = self.last_manifest
last_fingerprint = lm.fingerprint
current_fingerprint = self.get_target_geckodriver_version_number()
self.vprint('last_fingerprin... | [
"def",
"check_for_change",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"lm",
"=",
"self",
".",
"last_manifest",
"last_fingerprint",
"=",
"lm",
".",
"fingerprint",
"current_fingerprint",
"=",
"self",
".",
"get_target_geckodriver_version_number",
... | 40.666667 | 14.4 |
def getcoef(self):
"""Get final coefficient map array."""
global mp_Z_Y1
return np.swapaxes(mp_Z_Y1, 0, self.xstep.cri.axisK+1)[0] | [
"def",
"getcoef",
"(",
"self",
")",
":",
"global",
"mp_Z_Y1",
"return",
"np",
".",
"swapaxes",
"(",
"mp_Z_Y1",
",",
"0",
",",
"self",
".",
"xstep",
".",
"cri",
".",
"axisK",
"+",
"1",
")",
"[",
"0",
"]"
] | 30.2 | 21 |
def create_n_gram_df(df, n_pad):
"""
Given input dataframe, create feature dataframe of shifted characters
"""
n_pad_2 = int((n_pad - 1)/2)
for i in range(n_pad_2):
df['char-{}'.format(i+1)] = df['char'].shift(i + 1)
df['type-{}'.format(i+1)] = df['type'].shift(i + 1)
df['cha... | [
"def",
"create_n_gram_df",
"(",
"df",
",",
"n_pad",
")",
":",
"n_pad_2",
"=",
"int",
"(",
"(",
"n_pad",
"-",
"1",
")",
"/",
"2",
")",
"for",
"i",
"in",
"range",
"(",
"n_pad_2",
")",
":",
"df",
"[",
"'char-{}'",
".",
"format",
"(",
"i",
"+",
"1"... | 40.636364 | 13.181818 |
async def unban(self, channel, target, range=0):
"""
Unban user from channel. Target can be either a user or a host.
See ban documentation for the range parameter.
"""
if target in self.users:
host = self.users[target]['hostname']
else:
host = targ... | [
"async",
"def",
"unban",
"(",
"self",
",",
"channel",
",",
"target",
",",
"range",
"=",
"0",
")",
":",
"if",
"target",
"in",
"self",
".",
"users",
":",
"host",
"=",
"self",
".",
"users",
"[",
"target",
"]",
"[",
"'hostname'",
"]",
"else",
":",
"h... | 36.307692 | 14.615385 |
def _complete_parameters(param, variables):
"""Replace any parameters passed as {} in the yaml file with the variable names that are passed in
Only strings, lists of strings, and dictionaries of strings can have
replaceable values at the moment.
"""
if isinstance(param, list):
return [_com... | [
"def",
"_complete_parameters",
"(",
"param",
",",
"variables",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"list",
")",
":",
"return",
"[",
"_complete_parameters",
"(",
"x",
",",
"variables",
")",
"for",
"x",
"in",
"param",
"]",
"elif",
"isinstance",
... | 40.833333 | 22.333333 |
def controlled(num_ptr_bits, U):
"""
Given a one-qubit gate matrix U, construct a controlled-U on all pointer
qubits.
"""
d = 2 ** (1 + num_ptr_bits)
m = np.eye(d)
m[d - 2:, d - 2:] = U
return m | [
"def",
"controlled",
"(",
"num_ptr_bits",
",",
"U",
")",
":",
"d",
"=",
"2",
"**",
"(",
"1",
"+",
"num_ptr_bits",
")",
"m",
"=",
"np",
".",
"eye",
"(",
"d",
")",
"m",
"[",
"d",
"-",
"2",
":",
",",
"d",
"-",
"2",
":",
"]",
"=",
"U",
"retur... | 24.222222 | 16.444444 |
def base62_encode(cls, num):
"""Encode a number in Base X.
`num`: The number to encode
`alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479
"""
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
... | [
"def",
"base62_encode",
"(",
"cls",
",",
"num",
")",
":",
"alphabet",
"=",
"\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"if",
"num",
"==",
"0",
":",
"return",
"alphabet",
"[",
"0",
"]",
"arr",
"=",
"[",
"]",
"base",
"=",
"len",
"(",
... | 26.809524 | 19.095238 |
def to_bel_path(graph, path: str, mode: str = 'w', **kwargs) -> None:
"""Write the BEL graph as a canonical BEL Script to the given path.
:param BELGraph graph: the BEL Graph to output as a BEL Script
:param path: A file path
:param mode: The file opening mode. Defaults to 'w'
"""
with open(pat... | [
"def",
"to_bel_path",
"(",
"graph",
",",
"path",
":",
"str",
",",
"mode",
":",
"str",
"=",
"'w'",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"with",
"open",
"(",
"path",
",",
"mode",
"=",
"mode",
",",
"*",
"*",
"kwargs",
")",
"as",
"bel_f... | 42.222222 | 16 |
def remover(self, id_equipamento):
"""Remove um equipamento a partir do seu identificador.
Além de remover o equipamento, a API também remove:
- O relacionamento do equipamento com os tipos de acessos.
- O relacionamento do equipamento com os roteiros.
- O relaciona... | [
"def",
"remover",
"(",
"self",
",",
"id_equipamento",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_equipamento",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'O identificador do equipamento é inválido ou não foi informado.')",
"",
"url",
"=",
"'equipamento/... | 41 | 24.266667 |
async def _notify(self, message: BaseMessage, responder: Responder):
"""
Notify all callbacks that a message was received.
"""
for cb in self._listeners:
coro = cb(message, responder, self.fsm_creates_task)
if not self.fsm_creates_task:
self._regi... | [
"async",
"def",
"_notify",
"(",
"self",
",",
"message",
":",
"BaseMessage",
",",
"responder",
":",
"Responder",
")",
":",
"for",
"cb",
"in",
"self",
".",
"_listeners",
":",
"coro",
"=",
"cb",
"(",
"message",
",",
"responder",
",",
"self",
".",
"fsm_cre... | 36.555556 | 13.222222 |
def find_person_by_id(self, person_id):
"""doc: http://open.youku.com/docs/docs?id=87
"""
url = 'https://openapi.youku.com/v2/persons/show.json'
params = {
'client_id': self.client_id,
'person_id': person_id
}
r = requests.get(url, params=params)
... | [
"def",
"find_person_by_id",
"(",
"self",
",",
"person_id",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/persons/show.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'person_id'",
":",
"person_id",
"}",
"r",
"=",
"requests",
... | 32.272727 | 11 |
def organize_models(self, outdir, force_rerun=False):
"""Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again even i... | [
"def",
"organize_models",
"(",
"self",
",",
"outdir",
",",
"force_rerun",
"=",
"False",
")",
":",
"uniprot_to_swissmodel",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"u",
",",
"models",
"in",
"self",
".",
"all_models",
".",
"items",
"(",
")",
":",
"for... | 50.461538 | 27.692308 |
def _get_least_permissions_aces(self, resources):
""" Get ACEs with the least permissions that fit all resources.
To have access to polymorph on N collections, user MUST have
access to all of them. If this is true, ACEs are returned, that
allows 'view' permissions to current request pri... | [
"def",
"_get_least_permissions_aces",
"(",
"self",
",",
"resources",
")",
":",
"factories",
"=",
"[",
"res",
".",
"view",
".",
"_factory",
"for",
"res",
"in",
"resources",
"]",
"contexts",
"=",
"[",
"factory",
"(",
"self",
".",
"request",
")",
"for",
"fa... | 39.88 | 19.8 |
def device_filter(self):
"""The device filter to use.
:rtype: dict
"""
if isinstance(self._device_filter, str):
return self._decode_query(self._device_filter)
return self._device_filter | [
"def",
"device_filter",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_device_filter",
",",
"str",
")",
":",
"return",
"self",
".",
"_decode_query",
"(",
"self",
".",
"_device_filter",
")",
"return",
"self",
".",
"_device_filter"
] | 28.875 | 13.5 |
def key_hash_algo(self, value):
"""
A unicode string of the hash algorithm to use when creating the
certificate identifier - "sha1" (default), or "sha256".
"""
if value not in set(['sha1', 'sha256']):
raise ValueError(_pretty_message(
'''
... | [
"def",
"key_hash_algo",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"set",
"(",
"[",
"'sha1'",
",",
"'sha256'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"_pretty_message",
"(",
"'''\n hash_algo must be one of \"sha1\", \"sha25... | 30.666667 | 17.733333 |
def load(self, filename):
'''load rally and rally_land points from a file.
returns number of points loaded'''
f = open(filename, mode='r')
self.clear()
for line in f:
if line.startswith('#'):
continue
line = line.strip()
if not... | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"mode",
"=",
"'r'",
")",
"self",
".",
"clear",
"(",
")",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"conti... | 38 | 18.9 |
def pick(rest):
"Pick between a few options"
question = rest.strip()
choices = util.splitem(question)
if len(choices) == 1:
return "I can't pick if you give me only one choice!"
else:
pick = random.choice(choices)
certainty = random.sample(phrases.certainty_opts, 1)[0]
return "%s... %s %s" % (pick, certain... | [
"def",
"pick",
"(",
"rest",
")",
":",
"question",
"=",
"rest",
".",
"strip",
"(",
")",
"choices",
"=",
"util",
".",
"splitem",
"(",
"question",
")",
"if",
"len",
"(",
"choices",
")",
"==",
"1",
":",
"return",
"\"I can't pick if you give me only one choice!... | 32 | 16 |
def run_forever(self, start_at='once'):
"""
Starts the scheduling engine
@param start_at: 'once' -> start immediately
'next_minute' -> start at the first second of the next minutes
'next_hour' -> start 00:00 (min) next hour
... | [
"def",
"run_forever",
"(",
"self",
",",
"start_at",
"=",
"'once'",
")",
":",
"if",
"start_at",
"not",
"in",
"(",
"'once'",
",",
"'next_minute'",
",",
"'next_hour'",
",",
"'tomorrow'",
")",
":",
"raise",
"ValueError",
"(",
"\"start_at parameter must be one of the... | 43.75 | 17.083333 |
def get_payload(self):
"""Return Payload."""
return bytes(
[self.major_version >> 8 & 255, self.major_version & 255,
self.minor_version >> 8 & 255, self.minor_version & 255]) | [
"def",
"get_payload",
"(",
"self",
")",
":",
"return",
"bytes",
"(",
"[",
"self",
".",
"major_version",
">>",
"8",
"&",
"255",
",",
"self",
".",
"major_version",
"&",
"255",
",",
"self",
".",
"minor_version",
">>",
"8",
"&",
"255",
",",
"self",
".",
... | 42.2 | 19.2 |
def _iter_backtrack(ex, rand=False):
"""Iterate through all satisfying points using backtrack algorithm."""
if ex is One:
yield dict()
elif ex is not Zero:
if rand:
v = random.choice(ex.inputs) if rand else ex.top
else:
v = ex.top
points = [{v: 0}, {v:... | [
"def",
"_iter_backtrack",
"(",
"ex",
",",
"rand",
"=",
"False",
")",
":",
"if",
"ex",
"is",
"One",
":",
"yield",
"dict",
"(",
")",
"elif",
"ex",
"is",
"not",
"Zero",
":",
"if",
"rand",
":",
"v",
"=",
"random",
".",
"choice",
"(",
"ex",
".",
"in... | 32.4375 | 15.4375 |
def obj_name(self, obj: Union[str, Element]) -> str:
""" Return the formatted name used for the supplied definition """
if isinstance(obj, str):
obj = self.obj_for(obj)
if isinstance(obj, SlotDefinition):
return underscore(self.aliased_slot_name(obj))
else:
... | [
"def",
"obj_name",
"(",
"self",
",",
"obj",
":",
"Union",
"[",
"str",
",",
"Element",
"]",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"self",
".",
"obj_for",
"(",
"obj",
")",
"if",
"isinstance",
"(",
... | 47.25 | 13 |
def experiment_details_csv(request, pk):
"""This view generates a csv output file of an experiment.
The view writes to a csv table the animal, genotype, age (in days), assay and values."""
experiment = get_object_or_404(Experiment, pk=pk)
response = HttpResponse(content_type='text/csv')
response['Con... | [
"def",
"experiment_details_csv",
"(",
"request",
",",
"pk",
")",
":",
"experiment",
"=",
"get_object_or_404",
"(",
"Experiment",
",",
"pk",
"=",
"pk",
")",
"response",
"=",
"HttpResponse",
"(",
"content_type",
"=",
"'text/csv'",
")",
"response",
"[",
"'Content... | 41.958333 | 16.75 |
def path_enhance(R, n, window='hann', max_ratio=2.0, min_ratio=None, n_filters=7,
zero_mean=False, clip=True, **kwargs):
'''Multi-angle path enhancement for self- and cross-similarity matrices.
This function convolves multiple diagonal smoothing filters with a self-similarity (or
recurrenc... | [
"def",
"path_enhance",
"(",
"R",
",",
"n",
",",
"window",
"=",
"'hann'",
",",
"max_ratio",
"=",
"2.0",
",",
"min_ratio",
"=",
"None",
",",
"n_filters",
"=",
"7",
",",
"zero_mean",
"=",
"False",
",",
"clip",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"... | 37.869231 | 29.361538 |
def op(name,
data,
bucket_count=None,
display_name=None,
description=None,
collections=None):
"""Create a legacy histogram summary op.
Arguments:
name: A unique name for the generated summary node.
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_c... | [
"def",
"op",
"(",
"name",
",",
"data",
",",
"bucket_count",
"=",
"None",
",",
"display_name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"collections",
"=",
"None",
")",
":",
"# TODO(nickfelt): remove on-demand imports once dep situation is fixed.",
"import"... | 40.775 | 20.4 |
def _rotate_context(context, direction):
"""Moves the current position to 'position' and rotates the context according to 'direction'
:param context: Cairo context
:param direction: Direction enum
"""
if direction is Direction.UP:
pass
elif direction is Direc... | [
"def",
"_rotate_context",
"(",
"context",
",",
"direction",
")",
":",
"if",
"direction",
"is",
"Direction",
".",
"UP",
":",
"pass",
"elif",
"direction",
"is",
"Direction",
".",
"RIGHT",
":",
"context",
".",
"rotate",
"(",
"deg2rad",
"(",
"90",
")",
")",
... | 37.428571 | 5.357143 |
def prepare_connection():
"""Set dafault connection for ElasticSearch.
.. warning::
In case of using multiprocessing/multithreading, connection will
be probably initialized in the main process/thread and the same
connection (socket) will be used in all processes/threads. This
w... | [
"def",
"prepare_connection",
"(",
")",
":",
"elasticsearch_host",
"=",
"getattr",
"(",
"settings",
",",
"'ELASTICSEARCH_HOST'",
",",
"'localhost'",
")",
"elasticsearch_port",
"=",
"getattr",
"(",
"settings",
",",
"'ELASTICSEARCH_PORT'",
",",
"9200",
")",
"connection... | 50.666667 | 28.2 |
def _logging_callback(level, domain, message, data):
""" Callback that outputs libgphoto2's logging message via
Python's standard logging facilities.
:param level: libgphoto2 logging level
:param domain: component the message originates from
:param message: logging message
:param data: ... | [
"def",
"_logging_callback",
"(",
"level",
",",
"domain",
",",
"message",
",",
"data",
")",
":",
"domain",
"=",
"ffi",
".",
"string",
"(",
"domain",
")",
".",
"decode",
"(",
")",
"message",
"=",
"ffi",
".",
"string",
"(",
"message",
")",
".",
"decode"... | 35.5 | 11.6875 |
def _element_get_id(self, element):
"""Get id of reaction or species element.
In old levels the name is used as the id. This method returns the
correct attribute depending on the level.
"""
if self._reader._level > 1:
entry_id = element.get('id')
else:
... | [
"def",
"_element_get_id",
"(",
"self",
",",
"element",
")",
":",
"if",
"self",
".",
"_reader",
".",
"_level",
">",
"1",
":",
"entry_id",
"=",
"element",
".",
"get",
"(",
"'id'",
")",
"else",
":",
"entry_id",
"=",
"element",
".",
"get",
"(",
"'name'",... | 33.636364 | 12.545455 |
def engagement_context(self):
"""
Access the engagement_context
:returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
:rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
"""
if self._engagement_context... | [
"def",
"engagement_context",
"(",
"self",
")",
":",
"if",
"self",
".",
"_engagement_context",
"is",
"None",
":",
"self",
".",
"_engagement_context",
"=",
"EngagementContextList",
"(",
"self",
".",
"_version",
",",
"flow_sid",
"=",
"self",
".",
"_solution",
"["... | 40.714286 | 18 |
def read_cyclic_can_msg(self, channel, count):
"""
Reads back the list of CAN messages for automatically sending.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int count: The number of cyclic CAN messages to be received.... | [
"def",
"read_cyclic_can_msg",
"(",
"self",
",",
"channel",
",",
"count",
")",
":",
"c_channel",
"=",
"BYTE",
"(",
"channel",
")",
"c_can_msg",
"=",
"(",
"CanMsg",
"*",
"count",
")",
"(",
")",
"c_count",
"=",
"DWORD",
"(",
"count",
")",
"UcanReadCyclicCan... | 47.428571 | 21.714286 |
def get_sv_chroms(items, exclude_file):
"""Retrieve chromosomes to process on, avoiding extra skipped chromosomes.
"""
exclude_regions = {}
for region in pybedtools.BedTool(exclude_file):
if int(region.start) == 0:
exclude_regions[region.chrom] = int(region.end)
out = []
with... | [
"def",
"get_sv_chroms",
"(",
"items",
",",
"exclude_file",
")",
":",
"exclude_regions",
"=",
"{",
"}",
"for",
"region",
"in",
"pybedtools",
".",
"BedTool",
"(",
"exclude_file",
")",
":",
"if",
"int",
"(",
"region",
".",
"start",
")",
"==",
"0",
":",
"e... | 44.928571 | 16.714286 |
def PatchAt(cls, n, module, method_wrapper=None, module_alias=None, method_name_modifier=utils.identity, blacklist_predicate=_False, whitelist_predicate=_True, return_type_predicate=_None, getmembers_predicate=inspect.isfunction, admit_private=False, explanation=""):
"""
This classmethod lets you easily patch a... | [
"def",
"PatchAt",
"(",
"cls",
",",
"n",
",",
"module",
",",
"method_wrapper",
"=",
"None",
",",
"module_alias",
"=",
"None",
",",
"method_name_modifier",
"=",
"utils",
".",
"identity",
",",
"blacklist_predicate",
"=",
"_False",
",",
"whitelist_predicate",
"=",... | 57.266667 | 54.76 |
def embed(parent_locals=None, parent_globals=None, exec_lines=None,
remove_pyqt_hook=True, N=0):
"""
Starts interactive session. Similar to keyboard command in matlab.
Wrapper around IPython.embed
"""
import utool as ut
from functools import partial
import IPython
if parent_g... | [
"def",
"embed",
"(",
"parent_locals",
"=",
"None",
",",
"parent_globals",
"=",
"None",
",",
"exec_lines",
"=",
"None",
",",
"remove_pyqt_hook",
"=",
"True",
",",
"N",
"=",
"0",
")",
":",
"import",
"utool",
"as",
"ut",
"from",
"functools",
"import",
"part... | 35.306931 | 15.821782 |
def ds_geom(ds, t_srs=None):
"""Return dataset bbox envelope as geom
"""
gt = ds.GetGeoTransform()
ds_srs = get_ds_srs(ds)
if t_srs is None:
t_srs = ds_srs
ns = ds.RasterXSize
nl = ds.RasterYSize
x = np.array([0, ns, ns, 0, 0], dtype=float)
y = np.array([0, 0, nl, nl, 0], dty... | [
"def",
"ds_geom",
"(",
"ds",
",",
"t_srs",
"=",
"None",
")",
":",
"gt",
"=",
"ds",
".",
"GetGeoTransform",
"(",
")",
"ds_srs",
"=",
"get_ds_srs",
"(",
"ds",
")",
"if",
"t_srs",
"is",
"None",
":",
"t_srs",
"=",
"ds_srs",
"ns",
"=",
"ds",
".",
"Ras... | 33.952381 | 15.285714 |
def _computeChart(chart, date):
""" Internal function to return a new chart for
a specific date using properties from old chart.
"""
pos = chart.pos
hsys = chart.hsys
IDs = [obj.id for obj in chart.objects]
return Chart(date, pos, IDs=IDs, hsys=hsys) | [
"def",
"_computeChart",
"(",
"chart",
",",
"date",
")",
":",
"pos",
"=",
"chart",
".",
"pos",
"hsys",
"=",
"chart",
".",
"hsys",
"IDs",
"=",
"[",
"obj",
".",
"id",
"for",
"obj",
"in",
"chart",
".",
"objects",
"]",
"return",
"Chart",
"(",
"date",
... | 30.555556 | 11.888889 |
def read(self, size=-1):
"""Read up to *size* bytes.
This function reads from the buffer multiple times until the requested
number of bytes can be satisfied. This means that this function may
block to wait for more data, even if some data is available. The only
time a short read... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"self",
".",
"_check_readable",
"(",
")",
"chunks",
"=",
"[",
"]",
"bytes_read",
"=",
"0",
"bytes_left",
"=",
"size",
"while",
"True",
":",
"chunk",
"=",
"self",
".",
"_buffer",
".",... | 37.964286 | 18.107143 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Upd... | [
"def",
"fix_config",
"(",
"self",
",",
"options",
")",
":",
"options",
"=",
"super",
"(",
"UpdateStorageValue",
",",
"self",
")",
".",
"fix_config",
"(",
"options",
")",
"opt",
"=",
"\"storage_name\"",
"if",
"opt",
"not",
"in",
"options",
":",
"options",
... | 34.291667 | 20.625 |
def drop_schema(self):
"""Drop all gauged tables"""
try:
self.cursor.execute("""
DROP TABLE IF EXISTS gauged_data;
DROP TABLE IF EXISTS gauged_keys;
DROP TABLE IF EXISTS gauged_writer_history;
DROP TABLE IF EXISTS gauged_cache;
... | [
"def",
"drop_schema",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"\"\"\"\n DROP TABLE IF EXISTS gauged_data;\n DROP TABLE IF EXISTS gauged_keys;\n DROP TABLE IF EXISTS gauged_writer_history;\n ... | 41.846154 | 11.769231 |
def render_template_for_path(request, path, context=None, use_cache=True, def_name=None):
'''
Convenience method that directly renders a template, given a direct path to it.
'''
return get_template_for_path(path, use_cache).render(context, request, def_name) | [
"def",
"render_template_for_path",
"(",
"request",
",",
"path",
",",
"context",
"=",
"None",
",",
"use_cache",
"=",
"True",
",",
"def_name",
"=",
"None",
")",
":",
"return",
"get_template_for_path",
"(",
"path",
",",
"use_cache",
")",
".",
"render",
"(",
"... | 54 | 40.4 |
def parse(cls, fptr, offset, length):
"""Parse component mapping box.
Parameters
----------
fptr : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
--... | [
"def",
"parse",
"(",
"cls",
",",
"fptr",
",",
"offset",
",",
"length",
")",
":",
"num_bytes",
"=",
"offset",
"+",
"length",
"-",
"fptr",
".",
"tell",
"(",
")",
"num_components",
"=",
"int",
"(",
"num_bytes",
"/",
"4",
")",
"read_buffer",
"=",
"fptr",... | 29.482759 | 16.931034 |
def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
super(SpyderPluginWidget, self).visibility_changed(enable)
if enable:
self.explorer.is_visible.emit() | [
"def",
"visibility_changed",
"(",
"self",
",",
"enable",
")",
":",
"super",
"(",
"SpyderPluginWidget",
",",
"self",
")",
".",
"visibility_changed",
"(",
"enable",
")",
"if",
"enable",
":",
"self",
".",
"explorer",
".",
"is_visible",
".",
"emit",
"(",
")"
] | 43 | 10.6 |
def options(self, path=None, url_kwargs=None, **kwargs):
"""
Sends an OPTIONS request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
... | [
"def",
"options",
"(",
"self",
",",
"path",
"=",
"None",
",",
"url_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_session",
".",
"options",
"(",
"self",
".",
"_url",
"(",
"path",
",",
"url_kwargs",
")",
",",
"*",
... | 36.615385 | 17.230769 |
def load_filter_plugins(entrypoint_group: str) -> Iterable[Filter]:
"""
Load all blacklist plugins that are registered with pkg_resources
Parameters
==========
entrypoint_group: str
The entrypoint group name to load plugins from
Returns
=======
List of Blacklist:
A list... | [
"def",
"load_filter_plugins",
"(",
"entrypoint_group",
":",
"str",
")",
"->",
"Iterable",
"[",
"Filter",
"]",
":",
"global",
"loaded_filter_plugins",
"enabled_plugins",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"config",
"=",
"BandersnatchConfig",
"(",
")",... | 31.622222 | 20.022222 |
def post_notification(self, ntype, sender, *args, **kwargs):
"""Post notification to all registered observers.
The registered callback will be called as::
callback(ntype, sender, *args, **kwargs)
Parameters
----------
ntype : hashable
The notification t... | [
"def",
"post_notification",
"(",
"self",
",",
"ntype",
",",
"sender",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"ntype",
"==",
"None",
"or",
"sender",
"==",
"None",
")",
":",
"raise",
"NotificationError",
"(",
"\"Notification type a... | 34 | 19.421053 |
def get_pk_attrnames(obj) -> List[str]:
"""
Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns
"""
return [attrname
for attrname, column in gen_columns(obj)
... | [
"def",
"get_pk_attrnames",
"(",
"obj",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"attrname",
"for",
"attrname",
",",
"column",
"in",
"gen_columns",
"(",
"obj",
")",
"if",
"column",
".",
"primary_key",
"]"
] | 23.857143 | 18.857143 |
def create_redirect_web_page(web_dir, org_name, kibana_url):
""" Create HTML pages with the org name that redirect to
the Kibana dashboard filtered for this org """
html_redirect = """
<html>
<head>
"""
html_redirect += """<meta http-equiv="refresh" content="0; URL=%s/app/kibana"""\
... | [
"def",
"create_redirect_web_page",
"(",
"web_dir",
",",
"org_name",
",",
"kibana_url",
")",
":",
"html_redirect",
"=",
"\"\"\"\n <html>\n <head>\n \"\"\"",
"html_redirect",
"+=",
"\"\"\"<meta http-equiv=\"refresh\" content=\"0; URL=%s/app/kibana\"\"\"",
"%",
"kibana_ur... | 43.038462 | 10.153846 |
def run_selection(self):
"""
Run selected text or current line in console.
If some text is selected, then execute that text in console.
If no text is selected, then execute current line, unless current line
is empty. Then, advance cursor to next line. If cursor is on las... | [
"def",
"run_selection",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"get_current_editor",
"(",
")",
".",
"get_selection_as_executable_code",
"(",
")",
"if",
"text",
":",
"self",
".",
"exec_in_extconsole",
".",
"emit",
"(",
"text",
".",
"rstrip",
"(",
... | 44.125 | 21.958333 |
def _warning_handler(self, code: int):
"""处理300~399段状态码,抛出对应警告.
Parameters:
(code): - 响应的状态码
Return:
(bool): - 已知的警告类型则返回True,否则返回False
"""
if code == 300:
warnings.warn(
"ExpireWarning",
RuntimeWarning,
... | [
"def",
"_warning_handler",
"(",
"self",
",",
"code",
":",
"int",
")",
":",
"if",
"code",
"==",
"300",
":",
"warnings",
".",
"warn",
"(",
"\"ExpireWarning\"",
",",
"RuntimeWarning",
",",
"stacklevel",
"=",
"3",
")",
"elif",
"code",
"==",
"301",
":",
"wa... | 23.592593 | 16.37037 |
def Division(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Divides one vertex by another
:param left: the vertex to be divided
:param right: the vertex to divide
"""
return Double(context.jvm_view().DivisionVertex, lab... | [
"def",
"Division",
"(",
"left",
":",
"vertex_constructor_param_types",
",",
"right",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"jvm_vie... | 46.875 | 26.375 |
def iter(self, **kwargs):
"""Compute a range of orbits between two dates
Keyword Arguments:
dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over
start (Date or None): Date of the first point
stop (Date, timedelta or None): Date of the la... | [
"def",
"iter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'dates'",
"not",
"in",
"kwargs",
":",
"start",
"=",
"kwargs",
".",
"setdefault",
"(",
"'start'",
",",
"self",
".",
"orbit",
".",
"date",
")",
"stop",
"=",
"kwargs",
".",
"get",
... | 42.2 | 27.316667 |
def generate_keys(transform, field, evaluator, value):
'''
Generates the query keys for the default structure of the query index.
The structure of the key: [field_name, value].
It supports custom sorting, in which case the value is substituted
bu the result of transform(value).
@param transform... | [
"def",
"generate_keys",
"(",
"transform",
",",
"field",
",",
"evaluator",
",",
"value",
")",
":",
"if",
"evaluator",
"==",
"Evaluator",
".",
"equals",
":",
"return",
"dict",
"(",
"key",
"=",
"(",
"field",
",",
"transform",
"(",
"value",
")",
")",
")",
... | 40.821429 | 17.035714 |
def patch_table(self,
dataset_id,
table_id,
project_id=None,
description=None,
expiration_time=None,
external_data_configuration=None,
friendly_name=None,
label... | [
"def",
"patch_table",
"(",
"self",
",",
"dataset_id",
",",
"table_id",
",",
"project_id",
"=",
"None",
",",
"description",
"=",
"None",
",",
"expiration_time",
"=",
"None",
",",
"external_data_configuration",
"=",
"None",
",",
"friendly_name",
"=",
"None",
","... | 43.224299 | 22.252336 |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.metricName is not None:
self.metricName = self.args.metricName
if self.args.measurement is not None:
self.measurement = self.args.... | [
"def",
"get_arguments",
"(",
"self",
")",
":",
"ApiCli",
".",
"get_arguments",
"(",
"self",
")",
"if",
"self",
".",
"args",
".",
"metricName",
"is",
"not",
"None",
":",
"self",
".",
"metricName",
"=",
"self",
".",
"args",
".",
"metricName",
"if",
"self... | 30.970588 | 15.382353 |
def validate(self, input, is_substitute): # ToDo: apply 'no substitute' for initial load validations
"""
Performs validation
:param input: object to validate
:param is_substitute: will be used for what-if in the future
:return: validation result if violated or None
"""
... | [
"def",
"validate",
"(",
"self",
",",
"input",
",",
"is_substitute",
")",
":",
"# ToDo: apply 'no substitute' for initial load validations",
"constraint",
"=",
"self",
".",
"__get_constraint",
"(",
"input",
")",
"to_validate",
"=",
"self",
".",
"__get_to_validate",
"("... | 46.5 | 14.9 |
def replace_symbol_to_number(pinyin):
"""把声调替换为数字"""
def _replace(match):
symbol = match.group(0) # 带声调的字符
# 返回使用数字标识声调的字符
return PHONETIC_SYMBOL_DICT[symbol]
# 替换拼音中的带声调字符
return RE_PHONETIC_SYMBOL.sub(_replace, pinyin) | [
"def",
"replace_symbol_to_number",
"(",
"pinyin",
")",
":",
"def",
"_replace",
"(",
"match",
")",
":",
"symbol",
"=",
"match",
".",
"group",
"(",
"0",
")",
"# 带声调的字符",
"# 返回使用数字标识声调的字符",
"return",
"PHONETIC_SYMBOL_DICT",
"[",
"symbol",
"]",
"# 替换拼音中的带声调字符",
"r... | 28.222222 | 12.666667 |
def _config(self, args, config):
""" Get configuration for the current used listing.
"""
webexports = dict((x.args, x) for x in config.subsections('webexport'))
webexport = webexports.get(args.webexport)
if webexport is None:
if args.webexport == u'default':
... | [
"def",
"_config",
"(",
"self",
",",
"args",
",",
"config",
")",
":",
"webexports",
"=",
"dict",
"(",
"(",
"x",
".",
"args",
",",
"x",
")",
"for",
"x",
"in",
"config",
".",
"subsections",
"(",
"'webexport'",
")",
")",
"webexport",
"=",
"webexports",
... | 50 | 20.571429 |
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
"""Send an RPC to a device.
See :meth:`AbstractDeviceAdapter.send_rpc`.
"""
self._ensure_connection(conn_id, True)
connection_string = self._get_property(conn_id, "connection_string")
msg = dict(addr... | [
"async",
"def",
"send_rpc",
"(",
"self",
",",
"conn_id",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
")",
":",
"self",
".",
"_ensure_connection",
"(",
"conn_id",
",",
"True",
")",
"connection_string",
"=",
"self",
".",
"_get_property",
"... | 44.058824 | 29.588235 |
def getCursor(self):
"""
Get a Dictionary Cursor for executing queries
"""
if self.connection is None:
self.Connect()
return self.connection.cursor(MySQLdb.cursors.DictCursor) | [
"def",
"getCursor",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"self",
".",
"Connect",
"(",
")",
"return",
"self",
".",
"connection",
".",
"cursor",
"(",
"MySQLdb",
".",
"cursors",
".",
"DictCursor",
")"
] | 23.125 | 14.625 |
def check_call(self, cmd):
"""Calls a command through SSH.
"""
ret, _ = self._call(cmd, False)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret) | [
"def",
"check_call",
"(",
"self",
",",
"cmd",
")",
":",
"ret",
",",
"_",
"=",
"self",
".",
"_call",
"(",
"cmd",
",",
"False",
")",
"if",
"ret",
"!=",
"0",
":",
"# pragma: no cover",
"raise",
"RemoteCommandFailure",
"(",
"command",
"=",
"cmd",
",",
"r... | 35.833333 | 5.833333 |
def set_properties(self, eid, value, idx='*'):
"""
Set the value and/or attributes of an xml element, marked with the matching eid attribute, using the
properties of the specified object.
"""
if value.__class__ not in Template.class_cache:
props = []
for n... | [
"def",
"set_properties",
"(",
"self",
",",
"eid",
",",
"value",
",",
"idx",
"=",
"'*'",
")",
":",
"if",
"value",
".",
"__class__",
"not",
"in",
"Template",
".",
"class_cache",
":",
"props",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"value",
"... | 50 | 15.875 |
def get_property_by_inheritance(self, obj, prop):
# pylint: disable=too-many-branches, too-many-nested-blocks
"""
Get the property asked in parameter to this object or from defined templates of this
object
todo: rewrite this function which is really too complex!
:param ... | [
"def",
"get_property_by_inheritance",
"(",
"self",
",",
"obj",
",",
"prop",
")",
":",
"# pylint: disable=too-many-branches, too-many-nested-blocks",
"if",
"prop",
"==",
"'register'",
":",
"# We do not inherit the register property",
"return",
"None",
"# If I have the property, ... | 40.713376 | 15.375796 |
def dmrs_tikz_dependency(xs, **kwargs):
"""
Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs.
DMRSs use the `tikz-dependency` package for visualization.
"""
def link_label(link):
return '{}/{}'.format(link.rargname or '', link.post)
def label_edge(link):
if link... | [
"def",
"dmrs_tikz_dependency",
"(",
"xs",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"link_label",
"(",
"link",
")",
":",
"return",
"'{}/{}'",
".",
"format",
"(",
"link",
".",
"rargname",
"or",
"''",
",",
"link",
".",
"post",
")",
"def",
"label_edge",
... | 34.517241 | 17.413793 |
def default_route_options():
"""
Default callback for OPTIONS request
:rtype: Response
"""
response_obj = OrderedDict()
response_obj["status"] = True
response_obj["data"] = "Ok"
return Response(response_obj, content_type="application/json", charset="utf-... | [
"def",
"default_route_options",
"(",
")",
":",
"response_obj",
"=",
"OrderedDict",
"(",
")",
"response_obj",
"[",
"\"status\"",
"]",
"=",
"True",
"response_obj",
"[",
"\"data\"",
"]",
"=",
"\"Ok\"",
"return",
"Response",
"(",
"response_obj",
",",
"content_type",... | 28.454545 | 15.545455 |
def xor_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions
will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFai... | [
"def",
"xor_",
"(",
"*",
"validation_func",
"# type: ValidationFuncs",
")",
":",
"# type: (...) -> Callable",
"validation_func",
"=",
"_process_validation_function_s",
"(",
"list",
"(",
"validation_func",
")",
",",
"auto_and_wrapper",
"=",
"False",
")",
"if",
"len",
"... | 44.085106 | 27.446809 |
def DeleteInstance(self, InstanceName, **extra):
# pylint: disable=invalid-name
"""
Delete an instance.
This method performs the DeleteInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If t... | [
"def",
"DeleteInstance",
"(",
"self",
",",
"InstanceName",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name",
"exc",
"=",
"None",
"method_name",
"=",
"'DeleteInstance'",
"if",
"self",
".",
"_operation_recorders",
":",
"self",
".",
"operation_recor... | 33.6 | 19.485714 |
def register_vm(datacenter, name, vmx_path, resourcepool_object, host_object=None):
'''
Registers a virtual machine to the inventory with the given vmx file, on success
it returns the vim.VirtualMachine managed object reference
datacenter
Datacenter object of the virtual machine, vim.Datacenter... | [
"def",
"register_vm",
"(",
"datacenter",
",",
"name",
",",
"vmx_path",
",",
"resourcepool_object",
",",
"host_object",
"=",
"None",
")",
":",
"try",
":",
"if",
"host_object",
":",
"task",
"=",
"datacenter",
".",
"vmFolder",
".",
"RegisterVM_Task",
"(",
"path... | 41.1875 | 25.8125 |
def get_field_to_observations_map(generator, query_for_tag=''):
"""Return a field to `Observations` dict for the event generator.
Args:
generator: A generator over event protos.
query_for_tag: A string that if specified, only create observations for
events with this tag name.
Returns:
A dict m... | [
"def",
"get_field_to_observations_map",
"(",
"generator",
",",
"query_for_tag",
"=",
"''",
")",
":",
"def",
"increment",
"(",
"stat",
",",
"event",
",",
"tag",
"=",
"''",
")",
":",
"assert",
"stat",
"in",
"TRACKED_FIELDS",
"field_to_obs",
"[",
"stat",
"]",
... | 37.536585 | 17.682927 |
def ParseOptions(cls, options, config_object, category=None, names=None):
"""Parses and validates arguments using the appropriate helpers.
Args:
options (argparse.Namespace): parser options.
config_object (object): object to be configured by an argument helper.
category (Optional[str]): categ... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"config_object",
",",
"category",
"=",
"None",
",",
"names",
"=",
"None",
")",
":",
"for",
"helper_name",
",",
"helper_class",
"in",
"cls",
".",
"_helper_classes",
".",
"items",
"(",
")",
":",
"if",... | 44.681818 | 22.818182 |
def js2str(js, sort_keys=True, indent=4):
"""Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
}
**中文文... | [
"def",
"js2str",
"(",
"js",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"js",
",",
"sort_keys",
"=",
"sort_keys",
",",
"indent",
"=",
"indent",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\... | 23.894737 | 20.684211 |
def read_stats(self):
""" Read current ports statistics from chassis.
:return: dictionary {port name {group name, {stat name: stat value}}}
"""
self.statistics = TgnObjectsDict()
for port in self.session.ports.values():
self.statistics[port] = port.read_port_stats()... | [
"def",
"read_stats",
"(",
"self",
")",
":",
"self",
".",
"statistics",
"=",
"TgnObjectsDict",
"(",
")",
"for",
"port",
"in",
"self",
".",
"session",
".",
"ports",
".",
"values",
"(",
")",
":",
"self",
".",
"statistics",
"[",
"port",
"]",
"=",
"port",... | 34.2 | 17.4 |
def probability_lt(self, x):
"""
Returns the probability of a random variable being less than the
given value.
"""
if self.mean is None:
return
return normdist(x=x, mu=self.mean, sigma=self.standard_deviation) | [
"def",
"probability_lt",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"mean",
"is",
"None",
":",
"return",
"return",
"normdist",
"(",
"x",
"=",
"x",
",",
"mu",
"=",
"self",
".",
"mean",
",",
"sigma",
"=",
"self",
".",
"standard_deviation",
"... | 32.75 | 16.25 |
def create_manifest_from_s3_files(self):
"""
To create a manifest db for the current
:return:
"""
for k in self.s3.list_objects(Bucket=self.sitename)['Contents']:
key = k["Key"]
files = []
if key not in [self.manifest_file]:
fil... | [
"def",
"create_manifest_from_s3_files",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
".",
"s3",
".",
"list_objects",
"(",
"Bucket",
"=",
"self",
".",
"sitename",
")",
"[",
"'Contents'",
"]",
":",
"key",
"=",
"k",
"[",
"\"Key\"",
"]",
"files",
"=",
... | 33.363636 | 10.090909 |
def resolve_command(self, ctx, args):
"""
Overrides clicks ``resolve_command`` method
and appends *Did you mean ...* suggestions
to the raised exception message.
"""
original_cmd_name = click.utils.make_str(args[0])
try:
return super(DYMMixin, self).r... | [
"def",
"resolve_command",
"(",
"self",
",",
"ctx",
",",
"args",
")",
":",
"original_cmd_name",
"=",
"click",
".",
"utils",
".",
"make_str",
"(",
"args",
"[",
"0",
"]",
")",
"try",
":",
"return",
"super",
"(",
"DYMMixin",
",",
"self",
")",
".",
"resol... | 45.111111 | 23.222222 |
def set_common_datas(self, element, name, datas):
"""Populated common data for an element from dictionnary datas
"""
element.name = str(name)
if "description" in datas:
element.description = str(datas["description"]).strip()
if isinstance(element, Sampleable) and ele... | [
"def",
"set_common_datas",
"(",
"self",
",",
"element",
",",
"name",
",",
"datas",
")",
":",
"element",
".",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"\"description\"",
"in",
"datas",
":",
"element",
".",
"description",
"=",
"str",
"(",
"datas",
"["... | 38.388889 | 17.333333 |
def ls_dir(dirname):
"""Returns files and subdirectories within a given directory.
Returns a pair of lists, containing the names of directories and files
in ``dirname``.
Raises
------
OSError : Accessing the given directory path failed
Parameters
----------
dirname : str
T... | [
"def",
"ls_dir",
"(",
"dirname",
")",
":",
"ls",
"=",
"os",
".",
"listdir",
"(",
"dirname",
")",
"files",
"=",
"[",
"p",
"for",
"p",
"in",
"ls",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
... | 28.473684 | 23.210526 |
def bb(self,*args,**kwargs):
"""
NAME:
bb
PURPOSE:
return Galactic latitude
INPUT:
t - (optional) time at which to get bb (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(defau... | [
"def",
"bb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"bb",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[",
... | 23.375 | 28 |
def nextversion(current_version):
"""Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version` is too far from PEP 386),
... | [
"def",
"nextversion",
"(",
"current_version",
")",
":",
"norm_ver",
"=",
"verlib",
".",
"suggest_normalized_version",
"(",
"current_version",
")",
"if",
"norm_ver",
"is",
"None",
":",
"return",
"None",
"norm_ver",
"=",
"verlib",
".",
"NormalizedVersion",
"(",
"n... | 47.142857 | 23.5 |
def markdown(text, mode='', context='', raw=False):
"""Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
this is the reposi... | [
"def",
"markdown",
"(",
"text",
",",
"mode",
"=",
"''",
",",
"context",
"=",
"''",
",",
"raw",
"=",
"False",
")",
":",
"return",
"gh",
".",
"markdown",
"(",
"text",
",",
"mode",
",",
"context",
",",
"raw",
")"
] | 42.153846 | 20 |
def set_language(self, language):
"""
Set the given language for all the text fragments.
:param language: the language of the text fragments
:type language: :class:`~aeneas.language.Language`
"""
self.log([u"Setting language: '%s'", language])
for fragment in se... | [
"def",
"set_language",
"(",
"self",
",",
"language",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Setting language: '%s'\"",
",",
"language",
"]",
")",
"for",
"fragment",
"in",
"self",
".",
"fragments",
":",
"fragment",
".",
"language",
"=",
"language"
] | 36.5 | 11.9 |
def get_recent_repeated_responses(chatbot, conversation, sample=10, threshold=3, quantity=3):
"""
A filter that eliminates possibly repetitive responses to prevent
a chat bot from repeating statements that it has recently said.
"""
from collections import Counter
# Get the most recent statement... | [
"def",
"get_recent_repeated_responses",
"(",
"chatbot",
",",
"conversation",
",",
"sample",
"=",
"10",
",",
"threshold",
"=",
"3",
",",
"quantity",
"=",
"3",
")",
":",
"from",
"collections",
"import",
"Counter",
"# Get the most recent statements from the conversation"... | 31.576923 | 21.807692 |
def refresh_win(self, resizing=False):
""" set_encoding is False when resizing """
#self.init_window(set_encoding)
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
self._win.addstr(0,
int((self.maxX - len(self._title)) / 2),
... | [
"def",
"refresh_win",
"(",
"self",
",",
"resizing",
"=",
"False",
")",
":",
"#self.init_window(set_encoding)",
"self",
".",
"_win",
".",
"bkgdset",
"(",
"' '",
",",
"curses",
".",
"color_pair",
"(",
"3",
")",
")",
"self",
".",
"_win",
".",
"erase",
"(",
... | 36.727273 | 8.636364 |
def detach(self, overlay):
"""
Give each animation a unique, mutable layout so they can run
independently.
"""
# See #868
for i, a in enumerate(self.animations):
a.layout = a.layout.clone()
if overlay and i:
a.preclear = False | [
"def",
"detach",
"(",
"self",
",",
"overlay",
")",
":",
"# See #868",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"self",
".",
"animations",
")",
":",
"a",
".",
"layout",
"=",
"a",
".",
"layout",
".",
"clone",
"(",
")",
"if",
"overlay",
"and",
... | 30.5 | 10.7 |
def gen_tmp_file(i):
"""
Input: {
(suffix) - temp file suffix
(prefix) - temp file prefix
(remove_dir) - if 'yes', remove dir
}
Output: {
return - return code = 0, if successful
> 0... | [
"def",
"gen_tmp_file",
"(",
"i",
")",
":",
"xs",
"=",
"i",
".",
"get",
"(",
"'suffix'",
",",
"''",
")",
"xp",
"=",
"i",
".",
"get",
"(",
"'prefix'",
",",
"''",
")",
"s",
"=",
"i",
".",
"get",
"(",
"'string'",
",",
"''",
")",
"import",
"tempfi... | 23.16129 | 19.870968 |
async def get_entity_by_id(self, get_entity_by_id_request):
"""Return one or more user entities.
Searching by phone number only finds entities when their phone number
is in your contacts (and not always even then), and can't be used to
find Google Voice contacts.
"""
res... | [
"async",
"def",
"get_entity_by_id",
"(",
"self",
",",
"get_entity_by_id_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"GetEntityByIdResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'contacts/getentitybyid'",
",",
"get_entity_by_id_request",
... | 45.636364 | 19.181818 |
def _retry(function):
"""
Internal mechanism to try to send data to multiple Solr Hosts if
the query fails on the first one.
"""
def inner(self, **kwargs):
last_exception = None
#for host in self.router.get_hosts(**kwargs):
for host in self.ho... | [
"def",
"_retry",
"(",
"function",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"last_exception",
"=",
"None",
"#for host in self.router.get_hosts(**kwargs):",
"for",
"host",
"in",
"self",
".",
"host",
":",
"try",
":",
"return",
... | 40.041667 | 15.125 |
def efficiency_capacity_demand_difference(slots, events, X, **kwargs):
"""
A function that calculates the total difference between demand for an event
and the slot capacity it is scheduled in.
"""
overflow = 0
for row, event in enumerate(events):
for col, slot in enumerate(slots):
... | [
"def",
"efficiency_capacity_demand_difference",
"(",
"slots",
",",
"events",
",",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"overflow",
"=",
"0",
"for",
"row",
",",
"event",
"in",
"enumerate",
"(",
"events",
")",
":",
"for",
"col",
",",
"slot",
"in",
"en... | 39.3 | 14.9 |
def splittable(src):
"""
:returns: True if the source is splittable, False otherwise
"""
return (src.__class__.__iter__ is not BaseSeismicSource.__iter__
and getattr(src, 'mutex_weight', 1) == 1 and src.splittable) | [
"def",
"splittable",
"(",
"src",
")",
":",
"return",
"(",
"src",
".",
"__class__",
".",
"__iter__",
"is",
"not",
"BaseSeismicSource",
".",
"__iter__",
"and",
"getattr",
"(",
"src",
",",
"'mutex_weight'",
",",
"1",
")",
"==",
"1",
"and",
"src",
".",
"sp... | 39.5 | 17.166667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.