text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _detect_eggs_in_folder(folder):
"""
Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively.
"""
eggs = {}
for x in os.listdir(folder):
zip = x.endswith(_zip_ext)
if zip:
... | [
"def",
"_detect_eggs_in_folder",
"(",
"folder",
")",
":",
"eggs",
"=",
"{",
"}",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"folder",
")",
":",
"zip",
"=",
"x",
".",
"endswith",
"(",
"_zip_ext",
")",
"if",
"zip",
":",
"root",
"=",
"x",
"[",
":"... | 28.53125 | 15.59375 |
def save_avatar(self, image):
"""Save an avatar as raw image, return new filename.
:param image: The image that needs to be saved.
"""
path = current_app.config['AVATARS_SAVE_PATH']
filename = uuid4().hex + '_raw.png'
image.save(os.path.join(path, filename))
retu... | [
"def",
"save_avatar",
"(",
"self",
",",
"image",
")",
":",
"path",
"=",
"current_app",
".",
"config",
"[",
"'AVATARS_SAVE_PATH'",
"]",
"filename",
"=",
"uuid4",
"(",
")",
".",
"hex",
"+",
"'_raw.png'",
"image",
".",
"save",
"(",
"os",
".",
"path",
".",... | 35.888889 | 12 |
def remove_accelerator(control, key):
"""
Removes an accelerator from control.
control: The control to affect.
key: The key to remove.
"""
key = str_to_key(key)
t = _tables.get(control, [])
for a in t:
if a[:2] == key:
t.remove(a)
if t:
_tables[control] = t
else:
del _tables[control]
upd... | [
"def",
"remove_accelerator",
"(",
"control",
",",
"key",
")",
":",
"key",
"=",
"str_to_key",
"(",
"key",
")",
"t",
"=",
"_tables",
".",
"get",
"(",
"control",
",",
"[",
"]",
")",
"for",
"a",
"in",
"t",
":",
"if",
"a",
"[",
":",
"2",
"]",
"==",
... | 18.736842 | 17.473684 |
def printPi(self):
"""
Prints all states state and their steady state probabilities.
Not recommended for large state spaces.
"""
assert self.pi is not None, "Calculate pi before calling printPi()"
assert len(self.mapping)>0, "printPi() can only be used in combination with... | [
"def",
"printPi",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pi",
"is",
"not",
"None",
",",
"\"Calculate pi before calling printPi()\"",
"assert",
"len",
"(",
"self",
".",
"mapping",
")",
">",
"0",
",",
"\"printPi() can only be used in combination with the direc... | 53.888889 | 25.888889 |
def get(self, name: str) -> Optional[ListEntry]:
"""Return the named entry in the list tree.
Args:
name: The entry name.
"""
parts = name.split(self._delimiter)
try:
node = self._find(self._root, *parts)
except KeyError:
return None
... | [
"def",
"get",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Optional",
"[",
"ListEntry",
"]",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"self",
".",
"_delimiter",
")",
"try",
":",
"node",
"=",
"self",
".",
"_find",
"(",
"self",
".",
"_roo... | 29.266667 | 17.4 |
def modules(self):
"""(:class:`productmd.modules.Modules`) -- Compose Modules metadata"""
if self._modules is not None:
return self._modules
paths = [
"metadata/modules.json",
]
self._modules = self._load_metadata(paths, productmd.modules.Modules)
... | [
"def",
"modules",
"(",
"self",
")",
":",
"if",
"self",
".",
"_modules",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_modules",
"paths",
"=",
"[",
"\"metadata/modules.json\"",
",",
"]",
"self",
".",
"_modules",
"=",
"self",
".",
"_load_metadata",
"(... | 33.2 | 18 |
def CrearLiqSecundariaBase(self, pto_emision=1, nro_orden=None,
nro_contrato=None,
cuit_comprador=None, nro_ing_bruto_comprador=None,
cod_puerto=None, des_puerto_localidad=None,
cod_grano=None, cantidad_tn=None,
cuit_vendedor=None, nro_act_vendedor=None, # ... | [
"def",
"CrearLiqSecundariaBase",
"(",
"self",
",",
"pto_emision",
"=",
"1",
",",
"nro_orden",
"=",
"None",
",",
"nro_contrato",
"=",
"None",
",",
"cuit_comprador",
"=",
"None",
",",
"nro_ing_bruto_comprador",
"=",
"None",
",",
"cod_puerto",
"=",
"None",
",",
... | 51.380952 | 19.428571 |
def create_user(self, username, password, tags=""):
"""
Creates a user.
:param string username: The name to give to the new user
:param string password: Password for the new user
:param string tags: Comma-separated list of tags for the user
:returns: boolean
"""
... | [
"def",
"create_user",
"(",
"self",
",",
"username",
",",
"password",
",",
"tags",
"=",
"\"\"",
")",
":",
"path",
"=",
"Client",
".",
"urls",
"[",
"'users_by_name'",
"]",
"%",
"username",
"body",
"=",
"json",
".",
"dumps",
"(",
"{",
"'password'",
":",
... | 41.384615 | 16.923077 |
def plotcommand(cosmology='WMAP5', plotname=None):
""" Example ways to interrogate the dataset and plot the commah output """
# Plot the c-M relation as a functon of redshift
xarray = 10**(np.arange(1, 15, 0.2))
yval = 'c'
# Specify the redshift range
zarray = np.arange(0, 5, 0.5)
xtitle ... | [
"def",
"plotcommand",
"(",
"cosmology",
"=",
"'WMAP5'",
",",
"plotname",
"=",
"None",
")",
":",
"# Plot the c-M relation as a functon of redshift",
"xarray",
"=",
"10",
"**",
"(",
"np",
".",
"arange",
"(",
"1",
",",
"15",
",",
"0.2",
")",
")",
"yval",
"=",... | 30.606952 | 19.371658 |
def kwargs(self):
"""Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass.
This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by
SerializableFactory.create and Validatable.validate.
"""
return {k: v for k, v in self._kwargs.items() ... | [
"def",
"kwargs",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_kwargs",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"self",
".",
"_INTERNAL_FIELDS",
"}"
] | 49.714286 | 24.428571 |
def requirement(self) -> FetchRequirement:
"""Indicates the data required to fulfill this search key."""
key_name = self.key
if key_name == b'ALL':
return FetchRequirement.NONE
elif key_name == b'KEYSET':
keyset_reqs = {key.requirement for key in self.filter_key_s... | [
"def",
"requirement",
"(",
"self",
")",
"->",
"FetchRequirement",
":",
"key_name",
"=",
"self",
".",
"key",
"if",
"key_name",
"==",
"b'ALL'",
":",
"return",
"FetchRequirement",
".",
"NONE",
"elif",
"key_name",
"==",
"b'KEYSET'",
":",
"keyset_reqs",
"=",
"{",... | 48.263158 | 13.473684 |
def isSameTypeWith(self, other, matchTags=True, matchConstraints=True):
"""Examine |ASN.1| type for equality with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
... | [
"def",
"isSameTypeWith",
"(",
"self",
",",
"other",
",",
"matchTags",
"=",
"True",
",",
"matchConstraints",
"=",
"True",
")",
":",
"return",
"(",
"self",
"is",
"other",
"or",
"(",
"not",
"matchTags",
"or",
"self",
".",
"tagSet",
"==",
"other",
".",
"ta... | 35.826087 | 21.304348 |
def from_file(filename, section='matrix'):
"""
Generate a matrix from a .ini file. Configuration is expected to be in a ``[matrix]`` section.
"""
config = parse_config(open(filename), section=section)
return from_config(config) | [
"def",
"from_file",
"(",
"filename",
",",
"section",
"=",
"'matrix'",
")",
":",
"config",
"=",
"parse_config",
"(",
"open",
"(",
"filename",
")",
",",
"section",
"=",
"section",
")",
"return",
"from_config",
"(",
"config",
")"
] | 40.333333 | 14.666667 |
def _get_globals():
"""Return current Python interpreter globals namespace"""
if _get_globals_callback is not None:
return _get_globals_callback()
else:
try:
from __main__ import __dict__ as namespace
except ImportError:
try:
# The import fails... | [
"def",
"_get_globals",
"(",
")",
":",
"if",
"_get_globals_callback",
"is",
"not",
"None",
":",
"return",
"_get_globals_callback",
"(",
")",
"else",
":",
"try",
":",
"from",
"__main__",
"import",
"__dict__",
"as",
"namespace",
"except",
"ImportError",
":",
"try... | 32.545455 | 13.5 |
def add_contacts(self, indices, indices2=None, threshold=0.3, periodic=True, count_contacts=False):
r"""
Adds the contacts to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with ... | [
"def",
"add_contacts",
"(",
"self",
",",
"indices",
",",
"indices2",
"=",
"None",
",",
"threshold",
"=",
"0.3",
",",
"periodic",
"=",
"True",
",",
"count_contacts",
"=",
"False",
")",
":",
"from",
".",
"distances",
"import",
"ContactFeature",
"atom_pairs",
... | 51.071429 | 35.285714 |
def dumpf(obj, path):
"""
Write an nginx configuration to file.
:param obj obj: nginx object (Conf, Server, Container)
:param str path: path to nginx configuration on disk
:returns: path the configuration was written to
"""
with open(path, 'w') as f:
dump(obj, f)
return path | [
"def",
"dumpf",
"(",
"obj",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"dump",
"(",
"obj",
",",
"f",
")",
"return",
"path"
] | 27.818182 | 14.545455 |
def list_from_args(args):
"""
Flatten list of args
So as to accept either an array
Or as many arguments
For example:
func(['x', 'y'])
func('x', 'y')
"""
# Empty args
if not args:
return []
# Get argument type
arg_type = type(args[0])
is_list = arg_type in LIS... | [
"def",
"list_from_args",
"(",
"args",
")",
":",
"# Empty args",
"if",
"not",
"args",
":",
"return",
"[",
"]",
"# Get argument type",
"arg_type",
"=",
"type",
"(",
"args",
"[",
"0",
"]",
")",
"is_list",
"=",
"arg_type",
"in",
"LIST_TYPES",
"# Check that the a... | 21.742857 | 19.171429 |
def p_file_lics_info_1(self, p):
"""file_lics_info : FILE_LICS_INFO file_lic_info_value"""
try:
self.builder.set_file_license_in_file(self.document, p[2])
except OrderError:
self.order_error('LicenseInfoInFile', 'FileName', p.lineno(1))
except SPDXValueError:
... | [
"def",
"p_file_lics_info_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"self",
".",
"builder",
".",
"set_file_license_in_file",
"(",
"self",
".",
"document",
",",
"p",
"[",
"2",
"]",
")",
"except",
"OrderError",
":",
"self",
".",
"order_error",
"(",
... | 44.6 | 17.9 |
def get_assessment_session_for_bank(self, bank_id, proxy):
"""Gets an ``AssessmentSession`` which is responsible for performing assessments for the given bank ``Id``.
arg: bank_id (osid.id.Id): the ``Id`` of a bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.As... | [
"def",
"get_assessment_session_for_bank",
"(",
"self",
",",
"bank_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see if the catalog Id is ... | 48.181818 | 19.272727 |
def payment_end(self, account, wallet):
"""
End a payment session. Marks the account as available for use in a
payment session.
:param account: Account to mark available
:type account: str
:param wallet: Wallet to end payment session for
:type wallet: str
... | [
"def",
"payment_end",
"(",
"self",
",",
"account",
",",
"wallet",
")",
":",
"account",
"=",
"self",
".",
"_process_value",
"(",
"account",
",",
"'account'",
")",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
... | 29.892857 | 23.964286 |
def find_implementations(project, resource, offset, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Find the places a given method is overridden.
Finds the places a method is implemented. Returns a list of
`Location`\s.
"""
name = worder.get_name_at(resource, ... | [
"def",
"find_implementations",
"(",
"project",
",",
"resource",
",",
"offset",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"name",
"=",
"worder",
".",
"get_name_at",
"(",
"resource",
",",
... | 42.272727 | 18.787879 |
def create_absolute_values_structure(layer, fields):
"""Helper function to create the structure for absolute values.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields: List of name field on which we want to aggregate.
:type fields: list
:return: The data structure.
... | [
"def",
"create_absolute_values_structure",
"(",
"layer",
",",
"fields",
")",
":",
"# Let's create a structure like :",
"# key is the index of the field : (flat table, definition name)",
"source_fields",
"=",
"layer",
".",
"keywords",
"[",
"'inasafe_fields'",
"]",
"absolute_fields... | 35.375 | 15.791667 |
def _is_at_qry_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the query sequence'''
hit_coords = nucmer_hit.qry_coords()
return hit_coords.end >= nucmer_hit.qry_length - self.qry_end_tolerance | [
"def",
"_is_at_qry_end",
"(",
"self",
",",
"nucmer_hit",
")",
":",
"hit_coords",
"=",
"nucmer_hit",
".",
"qry_coords",
"(",
")",
"return",
"hit_coords",
".",
"end",
">=",
"nucmer_hit",
".",
"qry_length",
"-",
"self",
".",
"qry_end_tolerance"
] | 62.25 | 23.75 |
def _legacy_pubs(buf):
"""SSH v1 public keys are not supported."""
leftover = buf.read()
if leftover:
log.warning('skipping leftover: %r', leftover)
code = util.pack('B', msg_code('SSH_AGENT_RSA_IDENTITIES_ANSWER'))
num = util.pack('L', 0) # no SSH v1 keys
return util.frame(code, num) | [
"def",
"_legacy_pubs",
"(",
"buf",
")",
":",
"leftover",
"=",
"buf",
".",
"read",
"(",
")",
"if",
"leftover",
":",
"log",
".",
"warning",
"(",
"'skipping leftover: %r'",
",",
"leftover",
")",
"code",
"=",
"util",
".",
"pack",
"(",
"'B'",
",",
"msg_code... | 38.875 | 14.25 |
def _analyze(self):
""" works out the updates to be performed """
if self.value is None or self.value == self.previous:
pass
elif self._operation == "add":
self._additions = self.value
elif self._operation == "remove":
self._removals = self.value
... | [
"def",
"_analyze",
"(",
"self",
")",
":",
"if",
"self",
".",
"value",
"is",
"None",
"or",
"self",
".",
"value",
"==",
"self",
".",
"previous",
":",
"pass",
"elif",
"self",
".",
"_operation",
"==",
"\"add\"",
":",
"self",
".",
"_additions",
"=",
"self... | 39.333333 | 11.533333 |
def _clean_css(self):
"""
Returns the cleaned CSS
:param stylesheet: The Stylesheet object to parse
:type stylesheet: tinycss.css21.Stylesheet
"""
# Init the cleaned CSS rules and contents string
css_rules = []
# For every rule in the CSS
for rul... | [
"def",
"_clean_css",
"(",
"self",
")",
":",
"# Init the cleaned CSS rules and contents string",
"css_rules",
"=",
"[",
"]",
"# For every rule in the CSS",
"for",
"rule",
"in",
"self",
".",
"stylesheet",
".",
"rules",
":",
"try",
":",
"# Clean the CSS rule",
"cleaned_r... | 28.730769 | 17.269231 |
def encode_hook(self, hook, msg):
"""
Encodes a commit hook dict into the protobuf message. Used in
bucket properties.
:param hook: the hook to encode
:type hook: dict
:param msg: the protobuf message to fill
:type msg: riak.pb.riak_pb2.RpbCommitHook
:rty... | [
"def",
"encode_hook",
"(",
"self",
",",
"hook",
",",
"msg",
")",
":",
"if",
"'name'",
"in",
"hook",
":",
"msg",
".",
"name",
"=",
"str_to_bytes",
"(",
"hook",
"[",
"'name'",
"]",
")",
"else",
":",
"self",
".",
"encode_modfun",
"(",
"hook",
",",
"ms... | 31.8125 | 13.0625 |
def read(self, frames, raw=False):
"""Read samples from an input stream.
The function does not return until the required number of
frames has been read. This may involve waiting for the
operating system to supply the data.
If raw data is requested, the raw cffi data buffer is
... | [
"def",
"read",
"(",
"self",
",",
"frames",
",",
"raw",
"=",
"False",
")",
":",
"channels",
",",
"_",
"=",
"_split",
"(",
"self",
".",
"channels",
")",
"dtype",
",",
"_",
"=",
"_split",
"(",
"self",
".",
"dtype",
")",
"data",
"=",
"ffi",
".",
"n... | 40.35 | 18.65 |
def info(self):
"""list of tuples with QPImage meta data"""
info = []
# meta data
meta = self.meta
for key in meta:
info.append((key, self.meta[key]))
# background correction
for imdat in [self._amp, self._pha]:
info += imdat.info
r... | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"[",
"]",
"# meta data",
"meta",
"=",
"self",
".",
"meta",
"for",
"key",
"in",
"meta",
":",
"info",
".",
"append",
"(",
"(",
"key",
",",
"self",
".",
"meta",
"[",
"key",
"]",
")",
")",
"# backg... | 29.090909 | 13.727273 |
def make_feature_dict(feature_sequence):
"""A feature dict is a convenient way to organize a sequence of Feature
object (which you have got, e.g., from parse_GFF).
The function returns a dict with all the feature types as keys. Each value
of this dict is again a dict, now of feature names. The values o... | [
"def",
"make_feature_dict",
"(",
"feature_sequence",
")",
":",
"res",
"=",
"{",
"}",
"for",
"f",
"in",
"feature_sequence",
":",
"if",
"f",
".",
"type",
"not",
"in",
"res",
":",
"res",
"[",
"f",
".",
"type",
"]",
"=",
"{",
"}",
"res_ftype",
"=",
"re... | 37.848485 | 22.757576 |
def load_locate_library(candidates, cygwin_lib, name,
win_cls=None, cygwin_cls=None, others_cls=None,
find_library=None, check_symbols=None):
"""Locates and loads a library.
Returns: the loaded library
arguments:
* candidates -- candidates list for lo... | [
"def",
"load_locate_library",
"(",
"candidates",
",",
"cygwin_lib",
",",
"name",
",",
"win_cls",
"=",
"None",
",",
"cygwin_cls",
"=",
"None",
",",
"others_cls",
"=",
"None",
",",
"find_library",
"=",
"None",
",",
"check_symbols",
"=",
"None",
")",
":",
"if... | 39.442623 | 20.229508 |
def update_account(self, email=None, company_name=None, first_name=None,
last_name=None, address=None, postal_code=None, city=None,
state=None, country=None, phone=None):
"""
::
POST /:login
:param email: Email address
:type email: :... | [
"def",
"update_account",
"(",
"self",
",",
"email",
"=",
"None",
",",
"company_name",
"=",
"None",
",",
"first_name",
"=",
"None",
",",
"last_name",
"=",
"None",
",",
"address",
"=",
"None",
",",
"postal_code",
"=",
"None",
",",
"city",
"=",
"None",
",... | 29.625 | 15.0625 |
def changed_bytes(self, other):
"""
Gets the set of changed bytes between self and other.
"""
changes = set()
l.warning("FastMemory.changed_bytes(): This implementation is very slow and only for debug purposes.")
for addr,v in self._contents.items():
for i i... | [
"def",
"changed_bytes",
"(",
"self",
",",
"other",
")",
":",
"changes",
"=",
"set",
"(",
")",
"l",
".",
"warning",
"(",
"\"FastMemory.changed_bytes(): This implementation is very slow and only for debug purposes.\"",
")",
"for",
"addr",
",",
"v",
"in",
"self",
".",
... | 32.75 | 17.125 |
def LighterColor(self, level):
'''Create a new instance based on this one but lighter.
Parameters:
:level:
The amount by which the color should be lightened to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).LighterColor(... | [
"def",
"LighterColor",
"(",
"self",
",",
"level",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"self",
".",
"__hsl",
"return",
"Color",
"(",
"(",
"h",
",",
"s",
",",
"min",
"(",
"l",
"+",
"level",
",",
"1",
")",
")",
",",
"'hsl'",
",",
"self",
"... | 27.315789 | 24.684211 |
def overlay(main_parent_node, overlay_parent_node, eof_action='repeat', **kwargs):
"""Overlay one video on top of another.
Args:
x: Set the expression for the x coordinates of the overlaid video on the main video. Default value is 0. In
case the expression is invalid, it is set to a huge va... | [
"def",
"overlay",
"(",
"main_parent_node",
",",
"overlay_parent_node",
",",
"eof_action",
"=",
"'repeat'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'eof_action'",
"]",
"=",
"eof_action",
"return",
"FilterNode",
"(",
"[",
"main_parent_node",
",",
"ove... | 54.088889 | 32.133333 |
def clean(self, list_article_candidates):
"""Iterates over each article_candidate and cleans every extracted data.
:param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A list, the list with the cleaned ArticleCandidate-Objects
"... | [
"def",
"clean",
"(",
"self",
",",
"list_article_candidates",
")",
":",
"# Save cleaned article_candidates in results.",
"results",
"=",
"[",
"]",
"for",
"article_candidate",
"in",
"list_article_candidates",
":",
"article_candidate",
".",
"title",
"=",
"self",
".",
"do... | 51 | 30.25 |
def cmd_p4a(self, *args):
'''
Run p4a commands. Args must come after --, or
use --alias to make an alias
'''
self.check_requirements()
self.install_platform()
args = args[0]
if args and args[0] == '--alias':
print('To set up p4a in this shell s... | [
"def",
"cmd_p4a",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"check_requirements",
"(",
")",
"self",
".",
"install_platform",
"(",
")",
"args",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'--alias'",
":... | 40 | 18.4 |
def find_user(session, username):
"""Find user by name - returns user ID."""
resp = _make_request(session, FIND_USER_URL, username)
if not resp:
raise VooblyError('user not found')
try:
return int(resp[0]['uid'])
except ValueError:
raise VooblyError('user not found') | [
"def",
"find_user",
"(",
"session",
",",
"username",
")",
":",
"resp",
"=",
"_make_request",
"(",
"session",
",",
"FIND_USER_URL",
",",
"username",
")",
"if",
"not",
"resp",
":",
"raise",
"VooblyError",
"(",
"'user not found'",
")",
"try",
":",
"return",
"... | 33.666667 | 12.333333 |
def last_modified(self):
"""
The last modified time of the requirement's source distribution archive(s) (a number).
The value of this property is based on the :attr:`related_archives`
property. If no related archives are found the current time is
reported. In the balance between... | [
"def",
"last_modified",
"(",
"self",
")",
":",
"mtimes",
"=",
"list",
"(",
"map",
"(",
"os",
".",
"path",
".",
"getmtime",
",",
"self",
".",
"related_archives",
")",
")",
"return",
"max",
"(",
"mtimes",
")",
"if",
"mtimes",
"else",
"time",
".",
"time... | 49.333333 | 23.5 |
def unfollow(user, obj, send_action=False, flag=''):
"""
Removes a "follow" relationship.
Set ``send_action`` to ``True`` (``False is default) to also send a
``<user> stopped following <object>`` action signal.
Pass a string value to ``flag`` to determine which type of "follow" relationship you wa... | [
"def",
"unfollow",
"(",
"user",
",",
"obj",
",",
"send_action",
"=",
"False",
",",
"flag",
"=",
"''",
")",
":",
"check",
"(",
"obj",
")",
"qs",
"=",
"apps",
".",
"get_model",
"(",
"'actstream'",
",",
"'follow'",
")",
".",
"objects",
".",
"filter",
... | 30.172414 | 24.448276 |
def is_collection(item):
"""
Returns True if the item is a collection class: list, tuple, set, frozenset
or any other class that resembles one of these (using abstract base classes).
>>> is_collection(0)
False
>>> is_collection(0.1)
False
>>> is_collection('')
False
>>> is_colle... | [
"def",
"is_collection",
"(",
"item",
")",
":",
"return",
"not",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")",
"and",
"isinstance",
"(",
"item",
",",
"(",
"collections",
".",
"Set",
",",
"collections",
".",
"Sequence",
")",
")"
] | 26.071429 | 23.285714 |
def heightmap_get_normal(
hm: np.ndarray, x: float, y: float, waterLevel: float
) -> Tuple[float, float, float]:
"""Return the map normal at given coordinates.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
x (float): The x coordinate.
y (float): The y ... | [
"def",
"heightmap_get_normal",
"(",
"hm",
":",
"np",
".",
"ndarray",
",",
"x",
":",
"float",
",",
"y",
":",
"float",
",",
"waterLevel",
":",
"float",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"cn",
"=",
"ffi",
".",
"... | 35.764706 | 20.882353 |
def set_mode_send(self, target_system, base_mode, custom_mode, force_mavlink1=False):
'''
THIS INTERFACE IS DEPRECATED. USE COMMAND_LONG with
MAV_CMD_DO_SET_MODE INSTEAD. Set the system mode, as
defined by enum MAV_MODE. There is no target component
... | [
"def",
"set_mode_send",
"(",
"self",
",",
"target_system",
",",
"base_mode",
",",
"custom_mode",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"set_mode_encode",
"(",
"target_system",
",",
"base_mode",
",",
"... | 60.714286 | 38.142857 |
def unlearn(taskPkgName, deleteAll=False):
""" Find the task named taskPkgName, and delete any/all user-owned
.cfg files in the user's resource directory which apply to that task.
Like a unix utility, this returns 0 on success (no files found or only
1 found but deleted). For multiple files found, this... | [
"def",
"unlearn",
"(",
"taskPkgName",
",",
"deleteAll",
"=",
"False",
")",
":",
"# this WILL throw an exception if the taskPkgName isn't found",
"flist",
"=",
"cfgpars",
".",
"getUsrCfgFilesForPyPkg",
"(",
"taskPkgName",
")",
"# can raise",
"if",
"flist",
"is",
"None",
... | 41.869565 | 21.304348 |
def predict(self, X):
"""Perform regression on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------... | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_program'",
")",
":",
"raise",
"NotFittedError",
"(",
"'SymbolicRegressor not fitted.'",
")",
"X",
"=",
"check_array",
"(",
"X",
")",
"_",
",",
"n_features",
"... | 31.37931 | 20.448276 |
def _websafe_component(c, alt=False):
"""Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value.
"""
# This suck... | [
"def",
"_websafe_component",
"(",
"c",
",",
"alt",
"=",
"False",
")",
":",
"# This sucks, but floating point between 0 and 1 is quite fuzzy...",
"# So we just change the scale a while to make the equality tests",
"# work, otherwise it gets wrong at some decimal far to the right.",
"sc",
... | 26.090909 | 22.848485 |
def mdownload(args):
"""
%prog mdownload links.txt
Multiple download a list of files. Use formats.html.links() to extract the
links file.
"""
from jcvi.apps.grid import Jobs
p = OptionParser(mdownload.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not... | [
"def",
"mdownload",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"grid",
"import",
"Jobs",
"p",
"=",
"OptionParser",
"(",
"mdownload",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | 22.894737 | 18.789474 |
def _init_config(self):
"""If no config file exists, create it and add default options.
Default LevelDB path is specified based on OS
dynamic loading is set to infura by default in the file
Returns: leveldb directory
"""
system = platform.system().lower()
leveld... | [
"def",
"_init_config",
"(",
"self",
")",
":",
"system",
"=",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"leveldb_fallback_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"if",
"system",
".",
"startswith",
"(",
"\"d... | 38.911111 | 20.333333 |
def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if i... | [
"def",
"detect_number_of_cores",
"(",
")",
":",
"# Linux, Unix and MacOS:",
"if",
"hasattr",
"(",
"os",
",",
"\"sysconf\"",
")",
":",
"if",
"\"SC_NPROCESSORS_ONLN\"",
"in",
"os",
".",
"sysconf_names",
":",
"# Linux & Unix:",
"ncpus",
"=",
"os",
".",
"sysconf",
"... | 30.857143 | 17.238095 |
def __raise_user_error(self, view):
"""
Raises an error if the given View has been set read only and the user attempted to edit its content.
:param view: View.
:type view: QWidget
"""
raise foundations.exceptions.UserError("{0} | Cannot perform action, '{1}' View has be... | [
"def",
"__raise_user_error",
"(",
"self",
",",
"view",
")",
":",
"raise",
"foundations",
".",
"exceptions",
".",
"UserError",
"(",
"\"{0} | Cannot perform action, '{1}' View has been set read only!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
","... | 40.2 | 28.4 |
def run_node(self, node, stim):
''' Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer sto... | [
"def",
"run_node",
"(",
"self",
",",
"node",
",",
"stim",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"string_types",
")",
":",
"node",
"=",
"self",
".",
"nodes",
"[",
"node",
"]",
"result",
"=",
"node",
".",
"transformer",
".",
"transform",
"(",... | 38.5 | 20.772727 |
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _par... | [
"def",
"get",
"(",
"self",
",",
"url",
"=",
"None",
",",
"delimiter",
"=",
"\"/\"",
")",
":",
"params",
"=",
"{",
"'Delimiter'",
":",
"delimiter",
"}",
"bucket",
",",
"obj_key",
"=",
"_parse_url",
"(",
"url",
")",
"if",
"bucket",
":",
"params",
"[",
... | 33.608696 | 18.304348 |
def Analyze(self, hashes):
"""Looks up hashes in VirusTotal using the VirusTotal HTTP API.
The API is documented here:
https://www.virustotal.com/en/documentation/public-api/
Args:
hashes (list[str]): hashes to look up.
Returns:
list[HashAnalysis]: analysis results.
Raises:
... | [
"def",
"Analyze",
"(",
"self",
",",
"hashes",
")",
":",
"if",
"not",
"self",
".",
"_api_key",
":",
"raise",
"RuntimeError",
"(",
"'No API key specified for VirusTotal lookup.'",
")",
"hash_analyses",
"=",
"[",
"]",
"json_response",
"=",
"self",
".",
"_QueryHashe... | 28.181818 | 20.909091 |
def create_package(package_format, owner, repo, **kwargs):
"""Create a new package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
upload = getattr(client, "packages_upload_%s_with_http_info" % package_format)
data, _, headers = upload(
owner=o... | [
"def",
"create_package",
"(",
"package_format",
",",
"owner",
",",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"upload",
"=",
"getattr",
"(",
"client",
",",
"\"... | 35.076923 | 21.153846 |
def _brentq_cdf(self, value):
"""Helper function to compute percent_point.
As scipy.stats.gaussian_kde doesn't provide this functionality out of the box we need
to make a numerical approach:
- First we scalarize and bound cumulative_distribution.
- Then we define a function `f(... | [
"def",
"_brentq_cdf",
"(",
"self",
",",
"value",
")",
":",
"# The decorator expects an instance method, but usually are decorated before being bounded",
"bound_cdf",
"=",
"partial",
"(",
"scalarize",
"(",
"GaussianKDE",
".",
"cumulative_distribution",
")",
",",
"self",
")",... | 41.6 | 30.52 |
def getAttribute(self, attrName, defaultValue=None):
'''
getAttribute - Gets an attribute on this tag. Be wary using this for classname, maybe use addClass/removeClass. Attribute names are all lowercase.
@return - The attribute value, or None if none exists.
'''
if a... | [
"def",
"getAttribute",
"(",
"self",
",",
"attrName",
",",
"defaultValue",
"=",
"None",
")",
":",
"if",
"attrName",
"in",
"TAG_ITEM_BINARY_ATTRIBUTES",
":",
"if",
"attrName",
"in",
"self",
".",
"_attributes",
":",
"attrVal",
"=",
"self",
".",
"_attributes",
"... | 42.941176 | 27.529412 |
def create(self, basedir, outdir, name, prefix=None, dereference=True):
"""
:API: public
"""
basedir = ensure_text(basedir)
tarpath = os.path.join(outdir, '{}.{}'.format(ensure_text(name), self.extension))
with open_tar(tarpath, self.mode, dereference=dereference, errorlevel=1) as tar:
ta... | [
"def",
"create",
"(",
"self",
",",
"basedir",
",",
"outdir",
",",
"name",
",",
"prefix",
"=",
"None",
",",
"dereference",
"=",
"True",
")",
":",
"basedir",
"=",
"ensure_text",
"(",
"basedir",
")",
"tarpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | 36.7 | 21.7 |
def list(self, teamId, max=None, **request_parameters):
"""List team memberships for a team, by ID.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all team memberships re... | [
"def",
"list",
"(",
"self",
",",
"teamId",
",",
"max",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"teamId",
",",
"basestring",
",",
"may_be_none",
"=",
"False",
")",
"check_type",
"(",
"max",
",",
"int",
")",
"params... | 41.933333 | 26.511111 |
def send_batches(self, batch_list):
"""Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict
"""
if isinstance(batch_list, BaseMessage):
batch_list = ... | [
"def",
"send_batches",
"(",
"self",
",",
"batch_list",
")",
":",
"if",
"isinstance",
"(",
"batch_list",
",",
"BaseMessage",
")",
":",
"batch_list",
"=",
"batch_list",
".",
"SerializeToString",
"(",
")",
"return",
"self",
".",
"_post",
"(",
"'/batches'",
",",... | 29.923077 | 18.307692 |
def calc_resp(password_hash, server_challenge):
"""calc_resp generates the LM response given a 16-byte password hash and the
challenge from the Type-2 message.
@param password_hash
16-byte password hash
@param server_challenge
8-byte challenge from Type-2 message
... | [
"def",
"calc_resp",
"(",
"password_hash",
",",
"server_challenge",
")",
":",
"# padding with zeros to make the hash 21 bytes long",
"password_hash",
"+=",
"b'\\0'",
"*",
"(",
"21",
"-",
"len",
"(",
"password_hash",
")",
")",
"res",
"=",
"b''",
"dobj",
"=",
"des",
... | 34.869565 | 14.478261 |
def get_ip(self, address):
"""
Get an IPAddress object with the IP address (string) from the API.
e.g manager.get_ip('80.69.175.210')
"""
res = self.get_request('/ip_address/' + address)
return IPAddress(cloud_manager=self, **res['ip_address']) | [
"def",
"get_ip",
"(",
"self",
",",
"address",
")",
":",
"res",
"=",
"self",
".",
"get_request",
"(",
"'/ip_address/'",
"+",
"address",
")",
"return",
"IPAddress",
"(",
"cloud_manager",
"=",
"self",
",",
"*",
"*",
"res",
"[",
"'ip_address'",
"]",
")"
] | 35.75 | 16.5 |
def cond(pred, then_func, else_func):
"""Run an if-then-else using user-defined condition and computation
This operator simulates a if-like branch which chooses to do one of
the two customized computations according to the specified condition.
`pred` is a scalar MXNet NDArray,
indicating which bra... | [
"def",
"cond",
"(",
"pred",
",",
"then_func",
",",
"else_func",
")",
":",
"def",
"_to_python_scalar",
"(",
"inputs",
",",
"type_",
",",
"name",
")",
":",
"\"\"\"Converts \"inputs\", possibly typed mxnet NDArray, a numpy ndarray, other python types,\n to the given type\... | 35.753846 | 21.953846 |
def debug_toolbar_callback(request):
"""Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office."""
if request.is_ajax():
return False
if not hasattr(request, 'user'):
return False
if not request.user.is_authenticated:
return Fal... | [
"def",
"debug_toolbar_callback",
"(",
"request",
")",
":",
"if",
"request",
".",
"is_ajax",
"(",
")",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'user'",
")",
":",
"return",
"False",
"if",
"not",
"request",
".",
"user",
".",
... | 27.470588 | 15.941176 |
def execute_shell(self, shell=None, parent_environ=None, rcfile=None,
norc=False, stdin=False, command=None, quiet=False,
block=None, actions_callback=None, post_actions_callback=None,
context_filepath=None, start_new_session=False, detached=False,
... | [
"def",
"execute_shell",
"(",
"self",
",",
"shell",
"=",
"None",
",",
"parent_environ",
"=",
"None",
",",
"rcfile",
"=",
"None",
",",
"norc",
"=",
"False",
",",
"stdin",
"=",
"False",
",",
"command",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"bloc... | 44.376068 | 22.350427 |
def overrides_a_method(class_node: astroid.node_classes.NodeNG, name: str) -> bool:
"""return True if <name> is a method overridden from an ancestor"""
for ancestor in class_node.ancestors():
if name in ancestor and isinstance(ancestor[name], astroid.FunctionDef):
return True
return Fals... | [
"def",
"overrides_a_method",
"(",
"class_node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"for",
"ancestor",
"in",
"class_node",
".",
"ancestors",
"(",
")",
":",
"if",
"name",
"in",
"ancestor",
"... | 52.666667 | 21.166667 |
def _shorten_url(self, text):
'''Shorten a URL and make sure to not cut of html entities.'''
if len(text) > self._max_url_length and self._max_url_length != -1:
text = text[0:self._max_url_length - 3]
amp = text.rfind('&')
close = text.rfind(';')
if amp !... | [
"def",
"_shorten_url",
"(",
"self",
",",
"text",
")",
":",
"if",
"len",
"(",
"text",
")",
">",
"self",
".",
"_max_url_length",
"and",
"self",
".",
"_max_url_length",
"!=",
"-",
"1",
":",
"text",
"=",
"text",
"[",
"0",
":",
"self",
".",
"_max_url_leng... | 32.285714 | 21.142857 |
def stream(self, model, position):
"""Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering.
.. code-block:: pycon
# Create a user so we have a record
>>> engine = Engine()
>>> user = User(id=3, email="user@domain.com")
... | [
"def",
"stream",
"(",
"self",
",",
"model",
",",
"position",
")",
":",
"validate_not_abstract",
"(",
"model",
")",
"if",
"not",
"model",
".",
"Meta",
".",
"stream",
"or",
"not",
"model",
".",
"Meta",
".",
"stream",
".",
"get",
"(",
"\"arn\"",
")",
":... | 41.6 | 19.05 |
def get_oauth_url(self):
""" Returns the URL with OAuth params """
params = OrderedDict()
if "?" in self.url:
url = self.url[:self.url.find("?")]
for key, value in parse_qsl(urlparse(self.url).query):
params[key] = value
else:
url = se... | [
"def",
"get_oauth_url",
"(",
"self",
")",
":",
"params",
"=",
"OrderedDict",
"(",
")",
"if",
"\"?\"",
"in",
"self",
".",
"url",
":",
"url",
"=",
"self",
".",
"url",
"[",
":",
"self",
".",
"url",
".",
"find",
"(",
"\"?\"",
")",
"]",
"for",
"key",
... | 34.7 | 18.75 |
def parse_condition(self, query, prev_key=None, last_prev_key=None):
"""
Creates a recursive generator for parsing some types of Query()
conditions
:param query: Query object
:param prev_key: The key at the next-higher level
:return: generator object, the last of which w... | [
"def",
"parse_condition",
"(",
"self",
",",
"query",
",",
"prev_key",
"=",
"None",
",",
"last_prev_key",
"=",
"None",
")",
":",
"# use this to determine gt/lt/eq on prev_query",
"logger",
".",
"debug",
"(",
"u'query: {} prev_query: {}'",
".",
"format",
"(",
"query",... | 46.100775 | 18.069767 |
def searchString( self, instring, maxMatches=_MAX_INT ):
"""Another extension to scanString, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
maxMatches argument, to clip searching after 'n' matches are found.
"""
... | [
"def",
"searchString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
")",
":",
"return",
"ParseResults",
"(",
"[",
"t",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",
")",
"]",
... | 65.666667 | 22.833333 |
def _mul16(ins):
''' Multiplies tow last 16bit values on top of the stack and
and returns the value on top of the stack
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
*... | [
"def",
"_mul16",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"_int_ops",
"(",
"op1",
",",
"op2",
")",
"is",
"not",
"None",
":",
"# If any of the operands is constant",
"op1",
",",
"... | 31.196078 | 18.137255 |
def covar_plotter3d_matplotlib(embedding, rieman_metric, inspect_points_idx, ax,
colors):
"""3 Dimensional Covariance plotter using matplotlib backend."""
for pts_idx in inspect_points_idx:
plot_ellipse_matplotlib( cov=rieman_metric[pts_idx],
p... | [
"def",
"covar_plotter3d_matplotlib",
"(",
"embedding",
",",
"rieman_metric",
",",
"inspect_points_idx",
",",
"ax",
",",
"colors",
")",
":",
"for",
"pts_idx",
"in",
"inspect_points_idx",
":",
"plot_ellipse_matplotlib",
"(",
"cov",
"=",
"rieman_metric",
"[",
"pts_idx"... | 50.111111 | 13.666667 |
def make_comparison_png(self, outpath=None, include_legend=False):
"""
Creates a thematic map image with a three color beside it
:param outpath: if specified, will save the image instead of showing it
:param include_legend: if true will include the thamatic map label legend
"""
... | [
"def",
"make_comparison_png",
"(",
"self",
",",
"outpath",
"=",
"None",
",",
"include_legend",
"=",
"False",
")",
":",
"from",
"matplotlib",
".",
"patches",
"import",
"Patch",
"fig",
",",
"axs",
"=",
"plt",
".",
"subplots",
"(",
"ncols",
"=",
"2",
",",
... | 38.875 | 18.125 |
def load_effects(self, patients=None, only_nonsynonymous=False,
all_effects=False, filter_fn=None, **kwargs):
"""Load a dictionary of patient_id to varcode.EffectCollection
Note that this only loads one effect per variant.
Parameters
----------
patients : s... | [
"def",
"load_effects",
"(",
"self",
",",
"patients",
"=",
"None",
",",
"only_nonsynonymous",
"=",
"False",
",",
"all_effects",
"=",
"False",
",",
"filter_fn",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filter_fn",
"=",
"first_not_none_param",
"(",
"[... | 45.212121 | 22.757576 |
def render(data, saltenv='base', sls='', argline='', **kwargs): # pylint: disable=unused-argument
'''
Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption.
'''
translate_newlines = kwargs.get('translate_newlines', False)
return _decrypt_object(data, translate_newline... | [
"def",
"render",
"(",
"data",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"argline",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"translate_newlines",
"=",
"kwargs",
".",
"get",
"(",
"'translate_newlines'... | 56 | 38 |
def _resolve_default(data_type, listify=False):
"""Retrieve the default value for a given data type."""
if isinstance(data_type, _ATOMIC):
# A Python's object type needs to be left as is instead of being
# wrapped into a NumPy type.
out = (data_type.default if isinstance(data_type, Objec... | [
"def",
"_resolve_default",
"(",
"data_type",
",",
"listify",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data_type",
",",
"_ATOMIC",
")",
":",
"# A Python's object type needs to be left as is instead of being",
"# wrapped into a NumPy type.",
"out",
"=",
"(",
"dat... | 48.233333 | 17.2 |
def get_cached_moderated_reddits(self):
"""Return a cached dictionary of the user's moderated reddits.
This list is used internally. Consider using the `get_my_moderation`
function instead.
"""
if self._mod_subs is None:
self._mod_subs = {'mod': self.reddit_session.... | [
"def",
"get_cached_moderated_reddits",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mod_subs",
"is",
"None",
":",
"self",
".",
"_mod_subs",
"=",
"{",
"'mod'",
":",
"self",
".",
"reddit_session",
".",
"get_subreddit",
"(",
"'mod'",
")",
"}",
"for",
"sub",
... | 41.583333 | 20.333333 |
def to_csv(self, filename, stimuli=None, inhibitors=None, prepend=""):
"""
Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli nam... | [
"def",
"to_csv",
"(",
"self",
",",
"filename",
",",
"stimuli",
"=",
"None",
",",
"inhibitors",
"=",
"None",
",",
"prepend",
"=",
"\"\"",
")",
":",
"self",
".",
"to_dataframe",
"(",
"stimuli",
",",
"inhibitors",
",",
"prepend",
")",
".",
"to_csv",
"(",
... | 37.526316 | 26.263158 |
def get_agenda_for_sentence(self, sentence: str) -> List[str]:
"""
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point... | [
"def",
"get_agenda_for_sentence",
"(",
"self",
",",
"sentence",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"agenda",
"=",
"[",
"]",
"sentence",
"=",
"sentence",
".",
"lower",
"(",
")",
"if",
"sentence",
".",
"startswith",
"(",
"\"there is a box... | 52.226667 | 24.866667 |
def _parse_pot(pot):
"""Parse the potential so it can be fed to C"""
from .integrateFullOrbit import _parse_scf_pot
#Figure out what's in pot
if not isinstance(pot,list):
pot= [pot]
#Initialize everything
pot_type= []
pot_args= []
npot= len(pot)
for p in pot:
# Prepar... | [
"def",
"_parse_pot",
"(",
"pot",
")",
":",
"from",
".",
"integrateFullOrbit",
"import",
"_parse_scf_pot",
"#Figure out what's in pot",
"if",
"not",
"isinstance",
"(",
"pot",
",",
"list",
")",
":",
"pot",
"=",
"[",
"pot",
"]",
"#Initialize everything",
"pot_type"... | 47.226667 | 15.133333 |
def get_eventhub_info(self):
"""
Get details on the specified EventHub.
Keys in the details dictionary include:
-'name'
-'type'
-'created_at'
-'partition_count'
-'partition_ids'
:rtype: dict
"""
alt_creds = {
... | [
"def",
"get_eventhub_info",
"(",
"self",
")",
":",
"alt_creds",
"=",
"{",
"\"username\"",
":",
"self",
".",
"_auth_config",
".",
"get",
"(",
"\"iot_username\"",
")",
",",
"\"password\"",
":",
"self",
".",
"_auth_config",
".",
"get",
"(",
"\"iot_password\"",
... | 41.27027 | 19.324324 |
def get_state(self, scaling_group):
"""
Returns the current state of the specified scaling group as a
dictionary.
"""
uri = "/%s/%s/state" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
data = resp_body["group"]
r... | [
"def",
"get_state",
"(",
"self",
",",
"scaling_group",
")",
":",
"uri",
"=",
"\"/%s/%s/state\"",
"%",
"(",
"self",
".",
"uri_base",
",",
"utils",
".",
"get_id",
"(",
"scaling_group",
")",
")",
"resp",
",",
"resp_body",
"=",
"self",
".",
"api",
".",
"me... | 40.333333 | 15 |
def tag_add(package, tag, pkghash):
"""
Add a new tag for a given package hash.
Unlike versions, tags can have an arbitrary format, and can be modified
and deleted.
When a package is pushed, it gets the "latest" tag.
"""
team, owner, pkg = parse_package(package)
session = _get_session(... | [
"def",
"tag_add",
"(",
"package",
",",
"tag",
",",
"pkghash",
")",
":",
"team",
",",
"owner",
",",
"pkg",
"=",
"parse_package",
"(",
"package",
")",
"session",
"=",
"_get_session",
"(",
"team",
")",
"session",
".",
"put",
"(",
"\"{url}/api/tag/{owner}/{pkg... | 25.391304 | 18.26087 |
def get_all_names(chebi_ids):
'''Returns all names'''
all_names = [get_names(chebi_id) for chebi_id in chebi_ids]
return [x for sublist in all_names for x in sublist] | [
"def",
"get_all_names",
"(",
"chebi_ids",
")",
":",
"all_names",
"=",
"[",
"get_names",
"(",
"chebi_id",
")",
"for",
"chebi_id",
"in",
"chebi_ids",
"]",
"return",
"[",
"x",
"for",
"sublist",
"in",
"all_names",
"for",
"x",
"in",
"sublist",
"]"
] | 43.75 | 15.75 |
def get_slice_from_res_id(self, start, end):
"""Returns a new `Polypeptide` containing the `Residues` in start/end range.
Parameters
----------
start : str
string representing start residue id (PDB numbering)
end : str
string representing end residue id (... | [
"def",
"get_slice_from_res_id",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"id_dict",
"=",
"{",
"str",
"(",
"m",
".",
"id",
")",
":",
"m",
"for",
"m",
"in",
"self",
".",
"_monomers",
"}",
"slice_polymer",
"=",
"Polypeptide",
"(",
"[",
"id_dict"... | 33.45 | 21 |
def _search(self, trie, strings, limit=None):
"""Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection]
"""
results = [trie.has_key... | [
"def",
"_search",
"(",
"self",
",",
"trie",
",",
"strings",
",",
"limit",
"=",
"None",
")",
":",
"results",
"=",
"[",
"trie",
".",
"has_keys_with_prefix",
"(",
"s",
")",
"for",
"s",
"in",
"strings",
"]",
"if",
"not",
"any",
"(",
"results",
")",
":"... | 32.1875 | 13.25 |
def Marginal(self, i, name=''):
"""Gets the marginal distribution of the indicated variable.
i: index of the variable we want
Returns: Pmf
"""
pmf = Pmf(name=name)
for vs, prob in self.Items():
pmf.Incr(vs[i], prob)
return pmf | [
"def",
"Marginal",
"(",
"self",
",",
"i",
",",
"name",
"=",
"''",
")",
":",
"pmf",
"=",
"Pmf",
"(",
"name",
"=",
"name",
")",
"for",
"vs",
",",
"prob",
"in",
"self",
".",
"Items",
"(",
")",
":",
"pmf",
".",
"Incr",
"(",
"vs",
"[",
"i",
"]",... | 26 | 13.909091 |
def set_contents(self, stream, progress_callback=None):
"""Save contents of stream to part of file instance.
If a the MultipartObject is completed this methods raises an
``MultipartAlreadyCompleted`` exception.
:param stream: File-like stream.
:param size: Size of stream if kno... | [
"def",
"set_contents",
"(",
"self",
",",
"stream",
",",
"progress_callback",
"=",
"None",
")",
":",
"size",
",",
"checksum",
"=",
"self",
".",
"multipart",
".",
"file",
".",
"update_contents",
"(",
"stream",
",",
"seek",
"=",
"self",
".",
"start_byte",
"... | 40.823529 | 17.823529 |
def _get_element_text(self, element):
"""
Return the textual content of the element and its children
"""
text = ''
if element.text is not None:
text += element.text
for child in element.getchildren():
text += self._get_element_text(child)
i... | [
"def",
"_get_element_text",
"(",
"self",
",",
"element",
")",
":",
"text",
"=",
"''",
"if",
"element",
".",
"text",
"is",
"not",
"None",
":",
"text",
"+=",
"element",
".",
"text",
"for",
"child",
"in",
"element",
".",
"getchildren",
"(",
")",
":",
"t... | 32.416667 | 9.083333 |
def added(self, context):
"""Ingredient method called before anything else."""
context.ansi = ANSIFormatter(self._enable)
context.aprint = context.ansi.aprint | [
"def",
"added",
"(",
"self",
",",
"context",
")",
":",
"context",
".",
"ansi",
"=",
"ANSIFormatter",
"(",
"self",
".",
"_enable",
")",
"context",
".",
"aprint",
"=",
"context",
".",
"ansi",
".",
"aprint"
] | 44.75 | 7.25 |
def build(ctx, project, build): # pylint:disable=redefined-outer-name
"""Commands for build jobs."""
ctx.obj = ctx.obj or {}
ctx.obj['project'] = project
ctx.obj['build'] = build | [
"def",
"build",
"(",
"ctx",
",",
"project",
",",
"build",
")",
":",
"# pylint:disable=redefined-outer-name",
"ctx",
".",
"obj",
"=",
"ctx",
".",
"obj",
"or",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'project'",
"]",
"=",
"project",
"ctx",
".",
"obj",
"[",
... | 38.2 | 12.6 |
def drop_trailing_zeros(num):
"""
Drops the trailing zeros in a float that is printed.
"""
txt = '%f' %(num)
txt = txt.rstrip('0')
if txt.endswith('.'):
txt = txt[:-1]
return txt | [
"def",
"drop_trailing_zeros",
"(",
"num",
")",
":",
"txt",
"=",
"'%f'",
"%",
"(",
"num",
")",
"txt",
"=",
"txt",
".",
"rstrip",
"(",
"'0'",
")",
"if",
"txt",
".",
"endswith",
"(",
"'.'",
")",
":",
"txt",
"=",
"txt",
"[",
":",
"-",
"1",
"]",
"... | 22.888889 | 13.333333 |
def str2dict(dotted_str, value=None, separator='.'):
""" Convert dotted string to dict splitting by :separator: """
dict_ = {}
parts = dotted_str.split(separator)
d, prev = dict_, None
for part in parts:
prev = d
d = d.setdefault(part, {})
else:
if value is not None:
... | [
"def",
"str2dict",
"(",
"dotted_str",
",",
"value",
"=",
"None",
",",
"separator",
"=",
"'.'",
")",
":",
"dict_",
"=",
"{",
"}",
"parts",
"=",
"dotted_str",
".",
"split",
"(",
"separator",
")",
"d",
",",
"prev",
"=",
"dict_",
",",
"None",
"for",
"p... | 29.333333 | 14.833333 |
def replace_col(self, line, ndx):
"""
replace a grids column at index 'ndx' with 'line'
"""
for row in range(len(line)):
self.set_tile(row, ndx, line[row]) | [
"def",
"replace_col",
"(",
"self",
",",
"line",
",",
"ndx",
")",
":",
"for",
"row",
"in",
"range",
"(",
"len",
"(",
"line",
")",
")",
":",
"self",
".",
"set_tile",
"(",
"row",
",",
"ndx",
",",
"line",
"[",
"row",
"]",
")"
] | 32.666667 | 5.833333 |
def remote_url(connector, env, repo, filename):
"""
return a str containing a link to the rpm in the pulp repository
"""
dl_base = connector.base_url.replace('/pulp/api/v2', '/pulp/repos')
repoid = '%s-%s' % (repo, env)
_r = connector.get('/repositories/%s/' % repoid)
if not _r.status_code... | [
"def",
"remote_url",
"(",
"connector",
",",
"env",
",",
"repo",
",",
"filename",
")",
":",
"dl_base",
"=",
"connector",
".",
"base_url",
".",
"replace",
"(",
"'/pulp/api/v2'",
",",
"'/pulp/repos'",
")",
"repoid",
"=",
"'%s-%s'",
"%",
"(",
"repo",
",",
"e... | 36.761905 | 21.904762 |
def save_password(entry, password, username=None):
"""
Saves the given password in the user's keychain.
:param entry: The entry in the keychain. This is a caller specific key.
:param password: The password to save in the keychain.
:param username: The username to get the password for. Defau... | [
"def",
"save_password",
"(",
"entry",
",",
"password",
",",
"username",
"=",
"None",
")",
":",
"if",
"username",
"is",
"None",
":",
"username",
"=",
"get_username",
"(",
")",
"has_keychain",
"=",
"initialize_keychain",
"(",
")",
"if",
"has_keychain",
":",
... | 32.85 | 21.85 |
def _clear_dead_entities(self):
"""Finalize deletion of any Entities that are marked dead.
In the interest of performance, this method duplicates code from the
`delete_entity` method. If that method is changed, those changes should
be duplicated here as well.
"""
... | [
"def",
"_clear_dead_entities",
"(",
"self",
")",
":",
"for",
"entity",
"in",
"self",
".",
"_dead_entities",
":",
"for",
"component_type",
"in",
"self",
".",
"_entities",
"[",
"entity",
"]",
":",
"self",
".",
"_components",
"[",
"component_type",
"]",
".",
... | 35.789474 | 19.842105 |
def management_policies(self):
"""Instance depends on the API version:
* 2018-07-01: :class:`ManagementPoliciesOperations<azure.mgmt.storage.v2018_07_01.operations.ManagementPoliciesOperations>`
"""
api_version = self._get_api_version('management_policies')
if api_version == ... | [
"def",
"management_policies",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'management_policies'",
")",
"if",
"api_version",
"==",
"'2018-07-01'",
":",
"from",
".",
"v2018_07_01",
".",
"operations",
"import",
"ManagementPoliciesO... | 61 | 37.181818 |
def print_gce_info(zone, project, instance_name, data):
""" outputs information about our Rackspace instance """
try:
instance_info = _get_gce_compute().instances().get(
project=project,
zone=zone,
instance=instance_name
).execute()
log_yellow(pformat(... | [
"def",
"print_gce_info",
"(",
"zone",
",",
"project",
",",
"instance_name",
",",
"data",
")",
":",
"try",
":",
"instance_info",
"=",
"_get_gce_compute",
"(",
")",
".",
"instances",
"(",
")",
".",
"get",
"(",
"project",
"=",
"project",
",",
"zone",
"=",
... | 40.272727 | 12.272727 |
def _token_at_col_in_line(line, column, token, token_len=None):
"""True if token is at column."""
if not token_len:
token_len = len(token)
remaining_len = len(line) - column
return (remaining_len >= token_len and
line[column:column + token_len] == token) | [
"def",
"_token_at_col_in_line",
"(",
"line",
",",
"column",
",",
"token",
",",
"token_len",
"=",
"None",
")",
":",
"if",
"not",
"token_len",
":",
"token_len",
"=",
"len",
"(",
"token",
")",
"remaining_len",
"=",
"len",
"(",
"line",
")",
"-",
"column",
... | 31.555556 | 16.555556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.