text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_client(client_id):
"""Load the client.
Needed for grant_type client_credentials.
Add support for OAuth client_credentials access type, with user
inactivation support.
:param client_id: The client ID.
:returns: The client instance or ``None``.
"""
client = Client.query.get(clie... | [
"def",
"get_client",
"(",
"client_id",
")",
":",
"client",
"=",
"Client",
".",
"query",
".",
"get",
"(",
"client_id",
")",
"if",
"client",
"and",
"client",
".",
"user",
".",
"active",
":",
"return",
"client"
] | 26.642857 | 15.214286 |
def authenticate(self, request):
""" Attempt to authenticate the request.
:param request: django.http.Request instance
:return bool: True if success else raises HTTP_401
"""
authenticators = self._meta.authenticators
if request.method == 'OPTIONS' and ADREST_ALLOW_OPT... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
")",
":",
"authenticators",
"=",
"self",
".",
"_meta",
".",
"authenticators",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
"and",
"ADREST_ALLOW_OPTIONS",
":",
"self",
".",
"auth",
"=",
"AnonimousAuthent... | 31.785714 | 18.107143 |
def integer(token):
"""
Convert numeric strings into integers.
@type token: str
@param token: String to parse.
@rtype: int
@return: Parsed integer value.
"""
token = token.strip()
neg = False
if token.startswith(compat.b('-')):
... | [
"def",
"integer",
"(",
"token",
")",
":",
"token",
"=",
"token",
".",
"strip",
"(",
")",
"neg",
"=",
"False",
"if",
"token",
".",
"startswith",
"(",
"compat",
".",
"b",
"(",
"'-'",
")",
")",
":",
"token",
"=",
"token",
"[",
"1",
":",
"]",
"neg"... | 30.206897 | 14.137931 |
def readfp(self, fp, filename=None):
"""Like read() but the argument must be a file-like object.
The `fp' argument must have a `readline' method. Optional
second argument is the `filename', which if not given, is
taken from fp.name. If fp has no `name' attribute, `<???>' is
us... | [
"def",
"readfp",
"(",
"self",
",",
"fp",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"try",
":",
"filename",
"=",
"fp",
".",
"name",
"except",
"AttributeError",
":",
"filename",
"=",
"'<???>'",
"self",
".",
"_read",
"... | 33.733333 | 16.933333 |
def write_inp(self):
"""
Returns the material definition as a string in Abaqus INP format.
"""
template = self.get_template()
plastic_table = self.get_plastic_table()
return template.substitute({
"class": self.__class__.__name__,
"label": self.label,
"young_modulus": self... | [
"def",
"write_inp",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"get_template",
"(",
")",
"plastic_table",
"=",
"self",
".",
"get_plastic_table",
"(",
")",
"return",
"template",
".",
"substitute",
"(",
"{",
"\"class\"",
":",
"self",
".",
"__class_... | 40.733333 | 11.266667 |
def match_metric(regex):
'''
Display the current values of all metrics whose names match the
given regular expression.
.. versionadded:: 2016.11.0
.. code-block:: bash
salt '*' trafficserver.match_metric regex
'''
if _TRAFFICCTL:
cmd = _traffic_ctl('metric', 'match', regex... | [
"def",
"match_metric",
"(",
"regex",
")",
":",
"if",
"_TRAFFICCTL",
":",
"cmd",
"=",
"_traffic_ctl",
"(",
"'metric'",
",",
"'match'",
",",
"regex",
")",
"else",
":",
"cmd",
"=",
"_traffic_ctl",
"(",
"'-m'",
",",
"regex",
")",
"return",
"_subprocess",
"("... | 22.588235 | 23.058824 |
def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages | [
"def",
"check_messages",
"(",
"*",
"messages",
":",
"str",
")",
"->",
"Callable",
":",
"def",
"store_messages",
"(",
"func",
")",
":",
"func",
".",
"checks_msgs",
"=",
"messages",
"return",
"func",
"return",
"store_messages"
] | 28.625 | 17.375 |
def _parse_size(self, size, has_time=False):
"""Parse size inputs"""
if has_time:
size = size or 4
else:
size = size or 10
if isinstance(size, str):
size = {'column': size}
if isinstance(size, dict):
if 'column' not in size:
... | [
"def",
"_parse_size",
"(",
"self",
",",
"size",
",",
"has_time",
"=",
"False",
")",
":",
"if",
"has_time",
":",
"size",
"=",
"size",
"or",
"4",
"else",
":",
"size",
"=",
"size",
"or",
"10",
"if",
"isinstance",
"(",
"size",
",",
"str",
")",
":",
"... | 38.029412 | 14.823529 |
def dif(a, b):
""" copy from http://stackoverflow.com/a/8545526 """
return [i for i in range(len(a)) if a[i] != b[i]] | [
"def",
"dif",
"(",
"a",
",",
"b",
")",
":",
"return",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
"if",
"a",
"[",
"i",
"]",
"!=",
"b",
"[",
"i",
"]",
"]"
] | 41 | 13 |
def cql_encode_datetime(self, val):
"""
Converts a :class:`datetime.datetime` object to a (string) integer timestamp
with millisecond precision.
"""
timestamp = calendar.timegm(val.utctimetuple())
return str(long(timestamp * 1e3 + getattr(val, 'microsecond', 0) / 1e3)) | [
"def",
"cql_encode_datetime",
"(",
"self",
",",
"val",
")",
":",
"timestamp",
"=",
"calendar",
".",
"timegm",
"(",
"val",
".",
"utctimetuple",
"(",
")",
")",
"return",
"str",
"(",
"long",
"(",
"timestamp",
"*",
"1e3",
"+",
"getattr",
"(",
"val",
",",
... | 44.428571 | 15.571429 |
def set_visa_attribute(self, name, state):
"""Sets the state of an attribute.
:param name: Attribute for which the state is to be modified. (Attributes.*)
:param state: The state of the attribute to be set for the specified object.
:return: return value of the library call.
:rty... | [
"def",
"set_visa_attribute",
"(",
"self",
",",
"name",
",",
"state",
")",
":",
"return",
"self",
".",
"visalib",
".",
"set_attribute",
"(",
"self",
".",
"session",
",",
"name",
",",
"state",
")"
] | 48.111111 | 20 |
def unprotected_ids(doc, options):
u"""Returns a list of unprotected IDs within the document doc."""
identifiedElements = findElementsWithId(doc.documentElement)
if not (options.protect_ids_noninkscape or
options.protect_ids_list or
options.protect_ids_prefix):
return identif... | [
"def",
"unprotected_ids",
"(",
"doc",
",",
"options",
")",
":",
"identifiedElements",
"=",
"findElementsWithId",
"(",
"doc",
".",
"documentElement",
")",
"if",
"not",
"(",
"options",
".",
"protect_ids_noninkscape",
"or",
"options",
".",
"protect_ids_list",
"or",
... | 42.583333 | 10.208333 |
def api_key(self, api_key):
"""
Sets the api_key of this GlobalSignCredentials.
Unique ID for API client (provided by GlobalSign).
:param api_key: The api_key of this GlobalSignCredentials.
:type: str
"""
if api_key is None:
raise ValueError("Invalid... | [
"def",
"api_key",
"(",
"self",
",",
"api_key",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `api_key`, must not be `None`\"",
")",
"if",
"api_key",
"is",
"not",
"None",
"and",
"len",
"(",
"api_key",
")",
">",
... | 38.785714 | 22.5 |
def licenses(
ctx,
summary=False,
from_classifier=False,
with_system=False,
with_authors=False,
with_urls=False,
):
""" List dependency licenses.
"""
licenses_command = "pip-licenses --order=license"
report.info(ctx, "package.licenses", "listing licenses of package dependencies"... | [
"def",
"licenses",
"(",
"ctx",
",",
"summary",
"=",
"False",
",",
"from_classifier",
"=",
"False",
",",
"with_system",
"=",
"False",
",",
"with_authors",
"=",
"False",
",",
"with_urls",
"=",
"False",
",",
")",
":",
"licenses_command",
"=",
"\"pip-licenses --... | 34.965517 | 20.137931 |
async def wasAdded(self, node):
'''
Fire the onAdd() callbacks for node creation.
'''
for func in self.onadds:
try:
retn = func(node)
if s_coro.iscoro(retn):
await retn
except asyncio.CancelledError:
... | [
"async",
"def",
"wasAdded",
"(",
"self",
",",
"node",
")",
":",
"for",
"func",
"in",
"self",
".",
"onadds",
":",
"try",
":",
"retn",
"=",
"func",
"(",
"node",
")",
"if",
"s_coro",
".",
"iscoro",
"(",
"retn",
")",
":",
"await",
"retn",
"except",
"... | 31.6 | 16.533333 |
def list_function_versions(FunctionName,
region=None, key=None, keyid=None, profile=None):
'''
List the versions available for the given function.
Returns list of function versions
CLI Example:
.. code-block:: yaml
versions:
- {...}
- {...}
... | [
"def",
"list_function_versions",
"(",
"FunctionName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",... | 29.62963 | 24.148148 |
def make_dict_unstructure_fn(cl, converter, **kwargs):
# type: (Type[T], Converter) -> Callable[[T], Dict[str, Any]]
"""Generate a specialized dict unstructuring function for a class."""
cl_name = cl.__name__
fn_name = "unstructure_" + cl_name
globs = {"__c_u": converter.unstructure}
lines = []
... | [
"def",
"make_dict_unstructure_fn",
"(",
"cl",
",",
"converter",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Type[T], Converter) -> Callable[[T], Dict[str, Any]]",
"cl_name",
"=",
"cl",
".",
"__name__",
"fn_name",
"=",
"\"unstructure_\"",
"+",
"cl_name",
"globs",
"=",... | 40.609589 | 17.835616 |
def _do_cb(self, cb, error_cb, *args, **kw):
"""
Called internally by callback(). Does cb and error_cb selection.
"""
try:
res = self.work(*args, **kw)
except Exception as e:
if error_cb is None:
show_err()
elif error_cb:
... | [
"def",
"_do_cb",
"(",
"self",
",",
"cb",
",",
"error_cb",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"work",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
... | 28.714286 | 12.285714 |
def assign_operation_ids(spec, operids):
""" used to assign caller provided operationId values into a spec """
empty_dict = {}
for path_name, path_data in six.iteritems(spec['paths']):
for method, method_data in six.iteritems(path_data):
oper_id = operids.get(path_name, empty_dict).get... | [
"def",
"assign_operation_ids",
"(",
"spec",
",",
"operids",
")",
":",
"empty_dict",
"=",
"{",
"}",
"for",
"path_name",
",",
"path_data",
"in",
"six",
".",
"iteritems",
"(",
"spec",
"[",
"'paths'",
"]",
")",
":",
"for",
"method",
",",
"method_data",
"in",... | 39.6 | 19.9 |
def _get_int_removals_helper(self, spec_amts_oxi, oxid_el, oxid_els, numa):
"""
This is a helper method for get_removals_int_oxid!
Args:
spec_amts_oxi - a dict of species to their amounts in the structure
oxid_el - the element to oxidize
oxid_els - the full l... | [
"def",
"_get_int_removals_helper",
"(",
"self",
",",
"spec_amts_oxi",
",",
"oxid_el",
",",
"oxid_els",
",",
"numa",
")",
":",
"# If Mn is the oxid_el, we have a mixture of Mn2+, Mn3+, determine the minimum oxidation state for Mn",
"#this is the state we want to oxidize!",
"oxid_old",... | 47.953488 | 26.55814 |
def get_measurement_metadata(self, fields, ids=None, noneval=nan,
output_format='DataFrame'):
"""
Get the metadata fields of specified measurements (all if None given).
Parameters
----------
fields : str | iterable of str
Names of met... | [
"def",
"get_measurement_metadata",
"(",
"self",
",",
"fields",
",",
"ids",
"=",
"None",
",",
"noneval",
"=",
"nan",
",",
"output_format",
"=",
"'DataFrame'",
")",
":",
"fields",
"=",
"to_list",
"(",
"fields",
")",
"func",
"=",
"lambda",
"x",
":",
"x",
... | 41.194444 | 17.916667 |
def serialize(expr):
"""Serialize input expr into a parsable value.
:rtype: str"""
result = None
if isinstance(expr, string_types):
result = expr
elif expr is not None:
result = '=py:{0}'.format(expr)
return result | [
"def",
"serialize",
"(",
"expr",
")",
":",
"result",
"=",
"None",
"if",
"isinstance",
"(",
"expr",
",",
"string_types",
")",
":",
"result",
"=",
"expr",
"elif",
"expr",
"is",
"not",
"None",
":",
"result",
"=",
"'=py:{0}'",
".",
"format",
"(",
"expr",
... | 17.571429 | 21.571429 |
def open_allowed(self) -> bool:
"""Door can be opened unattended."""
return next(
attr['Value'] for attr in self._device_json.get('Attributes', [])
if attr.get('AttributeDisplayName') == 'isunattendedopenallowed')\
== "1" | [
"def",
"open_allowed",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"next",
"(",
"attr",
"[",
"'Value'",
"]",
"for",
"attr",
"in",
"self",
".",
"_device_json",
".",
"get",
"(",
"'Attributes'",
",",
"[",
"]",
")",
"if",
"attr",
".",
"get",
"(",
"'... | 44.666667 | 21 |
def start(self):
"""
Launch the process and start processing the DAG.
"""
self._process = DagFileProcessor._launch_process(
self._result_queue,
self.file_path,
self._pickle_dags,
self._dag_id_white_list,
"DagFileProcessor{}".for... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_process",
"=",
"DagFileProcessor",
".",
"_launch_process",
"(",
"self",
".",
"_result_queue",
",",
"self",
".",
"file_path",
",",
"self",
".",
"_pickle_dags",
",",
"self",
".",
"_dag_id_white_list",
",",
... | 33.666667 | 10.833333 |
def get_inclusion_states(self, transactions, tips):
# type: (Iterable[TransactionHash], Iterable[TransactionHash]) -> dict
"""
Get the inclusion states of a set of transactions. This is for
determining if a transaction was accepted and confirmed by the
network or not. You can sea... | [
"def",
"get_inclusion_states",
"(",
"self",
",",
"transactions",
",",
"tips",
")",
":",
"# type: (Iterable[TransactionHash], Iterable[TransactionHash]) -> dict",
"return",
"core",
".",
"GetInclusionStatesCommand",
"(",
"self",
".",
"adapter",
")",
"(",
"transactions",
"="... | 35.875 | 22.958333 |
def _logfile_sigterm_handler(*_):
# type: (...) -> None
"""Handle exit signals and write out a log file.
Raises:
SystemExit: Contains the signal as the return code.
"""
logging.error('Received SIGTERM.')
write_logfile()
print('Received signal. Please see the log file for more inform... | [
"def",
"_logfile_sigterm_handler",
"(",
"*",
"_",
")",
":",
"# type: (...) -> None",
"logging",
".",
"error",
"(",
"'Received SIGTERM.'",
")",
"write_logfile",
"(",
")",
"print",
"(",
"'Received signal. Please see the log file for more information.'",
",",
"file",
"=",
... | 30.416667 | 16.833333 |
def p_call_expr(self, p):
"""call_expr : member_expr arguments
| call_expr arguments
| call_expr LBRACKET expr RBRACKET
| call_expr PERIOD identifier
"""
if len(p) == 3:
p[0] = ast.FunctionCall(p[1], p[2])
elif le... | [
"def",
"p_call_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"FunctionCall",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")",
"elif",
"len",
"(",
"p",
")",
... | 35.916667 | 10.333333 |
def create_signature(secret, value, digestmod='sha256', encoding='utf-8'):
""" Create HMAC Signature from secret for value. """
if isinstance(secret, str):
secret = secret.encode(encoding)
if isinstance(value, str):
value = value.encode(encoding)
if isinstance(digestmod, str):
... | [
"def",
"create_signature",
"(",
"secret",
",",
"value",
",",
"digestmod",
"=",
"'sha256'",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"secret",
",",
"str",
")",
":",
"secret",
"=",
"secret",
".",
"encode",
"(",
"encoding",
")",
... | 32.5 | 17.357143 |
def snapshot(self, mode):
'''
Take a snapshot of the system.
'''
self._init_env()
self._save_cfg_packages(self._get_changed_cfg_pkgs(self._get_cfg_pkgs()))
self._save_payload(*self._scan_payload()) | [
"def",
"snapshot",
"(",
"self",
",",
"mode",
")",
":",
"self",
".",
"_init_env",
"(",
")",
"self",
".",
"_save_cfg_packages",
"(",
"self",
".",
"_get_changed_cfg_pkgs",
"(",
"self",
".",
"_get_cfg_pkgs",
"(",
")",
")",
")",
"self",
".",
"_save_payload",
... | 29.875 | 22.625 |
def make_from_catalogue(cls, catalogue, spacing, dilate):
'''
Defines the grid on the basis of the catalogue
'''
new = cls()
cat_bbox = get_catalogue_bounding_polygon(catalogue)
if dilate > 0:
cat_bbox = cat_bbox.dilate(dilate)
# Define Grid spacing
... | [
"def",
"make_from_catalogue",
"(",
"cls",
",",
"catalogue",
",",
"spacing",
",",
"dilate",
")",
":",
"new",
"=",
"cls",
"(",
")",
"cat_bbox",
"=",
"get_catalogue_bounding_polygon",
"(",
"catalogue",
")",
"if",
"dilate",
">",
"0",
":",
"cat_bbox",
"=",
"cat... | 34 | 18.56 |
def digital_write(self, pin, value):
"""
Set the specified pin to the specified value.
:param pin: pin number
:param value: pin value
:return: No return value
"""
# The command value is not a fixed value, but needs to be calculated using the
# pin's por... | [
"def",
"digital_write",
"(",
"self",
",",
"pin",
",",
"value",
")",
":",
"# The command value is not a fixed value, but needs to be calculated using the",
"# pin's port number",
"#",
"#",
"port",
"=",
"pin",
"//",
"8",
"calculated_command",
"=",
"self",
".",
"_command_h... | 30.233333 | 23.433333 |
def p_notminus_assignment(self, t):
'''notminus_assignment : IDENT EQ NOTMINUS'''
self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","notMinus"])) | [
"def",
"p_notminus_assignment",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"accu",
".",
"add",
"(",
"Term",
"(",
"'obs_vlabel'",
",",
"[",
"self",
".",
"name",
",",
"\"gen(\\\"\"",
"+",
"t",
"[",
"1",
"]",
"+",
"\"\\\")\"",
",",
"\"notMinus\"",
"]... | 55 | 18.333333 |
def get_df(self, data_file):
"""
读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考
https://github.com/rainx/pytdx/issues/133
:param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat
:return: pandas DataFrame格式的历史财务数据
"""
crawler = QAHistoryFinancialCrawle... | [
"def",
"get_df",
"(",
"self",
",",
"data_file",
")",
":",
"crawler",
"=",
"QAHistoryFinancialCrawler",
"(",
")",
"with",
"open",
"(",
"data_file",
",",
"'rb'",
")",
"as",
"df",
":",
"data",
"=",
"crawler",
".",
"parse",
"(",
"download_file",
"=",
"df",
... | 27.375 | 18.25 |
def skos_related(rdf):
"""Make sure that skos:related is stated in both directions (S23)."""
for s, o in rdf.subject_objects(SKOS.related):
rdf.add((o, SKOS.related, s)) | [
"def",
"skos_related",
"(",
"rdf",
")",
":",
"for",
"s",
",",
"o",
"in",
"rdf",
".",
"subject_objects",
"(",
"SKOS",
".",
"related",
")",
":",
"rdf",
".",
"add",
"(",
"(",
"o",
",",
"SKOS",
".",
"related",
",",
"s",
")",
")"
] | 45.5 | 7.75 |
def set_xy_labels(units, kpc_per_arcsec, xlabelsize, ylabelsize, xyticksize):
"""Set the x and y labels of the figure, and set the fontsize of those labels.
The x and y labels are always the distance scales, thus the labels are either arc-seconds or kpc and depend on the \
units the figure is plotted in.
... | [
"def",
"set_xy_labels",
"(",
"units",
",",
"kpc_per_arcsec",
",",
"xlabelsize",
",",
"ylabelsize",
",",
"xyticksize",
")",
":",
"if",
"units",
"in",
"'arcsec'",
"or",
"kpc_per_arcsec",
"is",
"None",
":",
"plt",
".",
"xlabel",
"(",
"'x (arcsec)'",
",",
"fonts... | 38 | 26.088235 |
def _add_or_remove_flag(self, flag, add):
"""
Add the given `flag` if `add` is True, remove it otherwise.
"""
meth = self.add_flag if add else self.remove_flag
meth(flag) | [
"def",
"_add_or_remove_flag",
"(",
"self",
",",
"flag",
",",
"add",
")",
":",
"meth",
"=",
"self",
".",
"add_flag",
"if",
"add",
"else",
"self",
".",
"remove_flag",
"meth",
"(",
"flag",
")"
] | 34.166667 | 11.166667 |
def prepare_destruction(self):
"""Prepares the model for destruction
Unregister itself as observer from the state machine and the root state
"""
if self.state_machine is None:
logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
self.destructi... | [
"def",
"prepare_destruction",
"(",
"self",
")",
":",
"if",
"self",
".",
"state_machine",
"is",
"None",
":",
"logger",
".",
"verbose",
"(",
"\"Multiple calls of prepare destruction for {0}\"",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"destruction_signal",... | 42.227273 | 14.863636 |
def errata_applicability(self, synchronous=True, **kwargs):
"""Force regenerate errata applicability
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's respon... | [
"def",
"errata_applicability",
"(",
"self",
",",
"synchronous",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"# shadow the passed-in kwargs",
"kwargs",
".",
"update",
"(",
"self",
".",
"_server_config",
".",... | 52.9375 | 24.375 |
def get_xml_attr(source, name, path=None):
"""Get the XML attribute with name from source. If path is not Mone, it will instead get the
XML attribute with name from the child indicated by path.
"""
if path is None:
return source.attrib[name]
else:
return get_xml_attr(get_xml_child(source, path), name) | [
"def",
"get_xml_attr",
"(",
"source",
",",
"name",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"source",
".",
"attrib",
"[",
"name",
"]",
"else",
":",
"return",
"get_xml_attr",
"(",
"get_xml_child",
"(",
"source",
","... | 39.125 | 13 |
def case(*, to, **kwargs):
"""Converts an identifier from one case type to another.
An identifier is an ASCII string consisting of letters, digits and underscores, not starting with a digit.
The supported case types are camelCase, PascalCase, snake_case, and CONSTANT_CASE,
identified as camel, pascal, s... | [
"def",
"case",
"(",
"*",
",",
"to",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"expect exactly one source string argument\"",
")",
"[",
"(",
"typ",
",",
"string",
")",
"]",
"=",
"... | 39.823529 | 25.54902 |
def delete_serv_obj(self, tenant_id):
"""Creates and stores the service object associated with a tenant. """
self.del_obj(tenant_id, self.service_attr[tenant_id])
del self.service_attr[tenant_id] | [
"def",
"delete_serv_obj",
"(",
"self",
",",
"tenant_id",
")",
":",
"self",
".",
"del_obj",
"(",
"tenant_id",
",",
"self",
".",
"service_attr",
"[",
"tenant_id",
"]",
")",
"del",
"self",
".",
"service_attr",
"[",
"tenant_id",
"]"
] | 54 | 6 |
def token_getter(remote, token=''):
"""Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default... | [
"def",
"token_getter",
"(",
"remote",
",",
"token",
"=",
"''",
")",
":",
"session_key",
"=",
"token_session_key",
"(",
"remote",
".",
"name",
")",
"if",
"session_key",
"not",
"in",
"session",
"and",
"current_user",
".",
"is_authenticated",
":",
"# Fetch key fr... | 32.928571 | 18.785714 |
def parse(filename=""):
"Open, read and eval the resource from the source file"
# use the provided resource file:
s = open(filename).read()
##s.decode("latin1").encode("utf8")
import datetime, decimal
rsrc = eval(s)
return rsrc | [
"def",
"parse",
"(",
"filename",
"=",
"\"\"",
")",
":",
"# use the provided resource file:",
"s",
"=",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
"##s.decode(\"latin1\").encode(\"utf8\")",
"import",
"datetime",
",",
"decimal",
"rsrc",
"=",
"eval",
"(",... | 31 | 13.75 |
def last(self):
"""
Returns the last batch for the batched sequence.
:rtype: :class:`Batch` instance.
"""
start = max(self.number - 1, 0) * self.size
return Batch(start, self.size, self.total_size) | [
"def",
"last",
"(",
"self",
")",
":",
"start",
"=",
"max",
"(",
"self",
".",
"number",
"-",
"1",
",",
"0",
")",
"*",
"self",
".",
"size",
"return",
"Batch",
"(",
"start",
",",
"self",
".",
"size",
",",
"self",
".",
"total_size",
")"
] | 29.875 | 13.375 |
def _set_tieBreaking(self, v, load=False):
"""
Setter method for tieBreaking, mapped from YANG variable /brocade_mpls_rpc/show_mpls_te_path/input/tieBreaking (tie-breaking)
If this variable is read-only (config: false) in the
source YANG file, then _set_tieBreaking is considered as a private
method.... | [
"def",
"_set_tieBreaking",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | 82.833333 | 41.375 |
def rprint(sep='\n', end='\n', file=sys.stdout, flush=False):
"""A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
... | [
"def",
"rprint",
"(",
"sep",
"=",
"'\\n'",
",",
"end",
"=",
"'\\n'",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"flush",
"=",
"False",
")",
":",
"try",
":",
"first_item",
"=",
"(",
"yield",
")",
"file",
".",
"write",
"(",
"str",
"(",
"first_ite... | 30.708333 | 17.666667 |
def QA_SU_save_stock_transaction(
client=DATABASE,
ui_log=None,
ui_progress=None
):
"""save stock_transaction
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
stock_list = QA_fetch_get_stock_list().code.unique().tolist()
coll = client.st... | [
"def",
"QA_SU_save_stock_transaction",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"stock_list",
"=",
"QA_fetch_get_stock_list",
"(",
")",
".",
"code",
".",
"unique",
"(",
")",
".",
"tolist",
"(",
... | 29.1 | 18.3 |
def _parse_shape_list(shape_list, crs):
""" Checks if the given list of shapes is in correct format and parses geometry objects
:param shape_list: The parameter `shape_list` from class initialization
:type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.P... | [
"def",
"_parse_shape_list",
"(",
"shape_list",
",",
"crs",
")",
":",
"if",
"not",
"isinstance",
"(",
"shape_list",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'Splitter must be initialized with a list of shapes'",
")",
"return",
"[",
"AreaSplitter",
".",
"... | 51.363636 | 26.090909 |
def get_numeric_value(string_value):
""" parses string_value and returns only number-like part
"""
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | [
"def",
"get_numeric_value",
"(",
"string_value",
")",
":",
"num_chars",
"=",
"[",
"'.'",
",",
"'+'",
",",
"'-'",
"]",
"number",
"=",
"''",
"for",
"c",
"in",
"string_value",
":",
"if",
"c",
".",
"isdigit",
"(",
")",
"or",
"c",
"in",
"num_chars",
":",
... | 28.555556 | 10.333333 |
def get_organisation_information(self, query_params=None):
'''
Get information fot this organisation. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | [
"def",
"get_organisation_information",
"(",
"self",
",",
"query_params",
"=",
"None",
")",
":",
"return",
"self",
".",
"fetch_json",
"(",
"uri_path",
"=",
"self",
".",
"base_uri",
",",
"query_params",
"=",
"query_params",
"or",
"{",
"}",
")"
] | 34.5 | 20.25 |
def render(self, ctx=None):
'''
Render the current value into a :class:`bitstring.Bits` object
:rtype: :class:`bitstring.Bits`
:return: the rendered field
'''
self._initialize()
if ctx is None:
ctx = RenderContext()
#
# if we are calle... | [
"def",
"render",
"(",
"self",
",",
"ctx",
"=",
"None",
")",
":",
"self",
".",
"_initialize",
"(",
")",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"RenderContext",
"(",
")",
"#",
"# if we are called from within render, return a dummy object...",
"#",
"if",
"... | 31.545455 | 19.818182 |
def validate(self):
"""Validation of configuration to check for required values"""
if not self.server.enabled:
if self.security.signature_certificate_file is self.security.defaults['signature_certificate_file']:
print("ISSUE: If you are not configuring a server, you need to... | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"server",
".",
"enabled",
":",
"if",
"self",
".",
"security",
".",
"signature_certificate_file",
"is",
"self",
".",
"security",
".",
"defaults",
"[",
"'signature_certificate_file'",
"]",
":"... | 62.303571 | 49.875 |
def as_labeller(x, default=label_value, multi_line=True):
"""
Coerse to labeller function
Parameters
----------
x : function | dict
Object to coerce
default : function | str
Default labeller. If it is a string,
it should be the name of one the labelling
functions... | [
"def",
"as_labeller",
"(",
"x",
",",
"default",
"=",
"label_value",
",",
"multi_line",
"=",
"True",
")",
":",
"if",
"x",
"is",
"None",
":",
"x",
"=",
"default",
"# One of the labelling functions as string",
"with",
"suppress",
"(",
"KeyError",
",",
"TypeError"... | 27.574074 | 15.907407 |
def str_to_python_object(input_str):
""" a conversion that will import a module and class name
"""
if not input_str:
return None
if six.PY3 and isinstance(input_str, six.binary_type):
input_str = to_str(input_str)
if not isinstance(input_str, six.string_types):
# gosh, we did... | [
"def",
"str_to_python_object",
"(",
"input_str",
")",
":",
"if",
"not",
"input_str",
":",
"return",
"None",
"if",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"input_str",
",",
"six",
".",
"binary_type",
")",
":",
"input_str",
"=",
"to_str",
"(",
"input_st... | 41.411765 | 15.764706 |
def has_none_of_selectors(self, selector, *locators, **kwargs):
"""
Checks if none of the provided selectors are present on the given page or descendants of the
current node. If options are provided, the assertion will check that each locator is present
with those options as well (other ... | [
"def",
"has_none_of_selectors",
"(",
"self",
",",
"selector",
",",
"*",
"locators",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"assert_none_of_selectors",
"(",
"selector",
",",
"*",
"locators",
",",
"*",
"*",
"kwargs",
")"
] | 51.56 | 35.24 |
def triplify(self, data, parent=None):
""" Recursively generate statements from the data supplied. """
if data is None:
return
if self.is_object:
for res in self._triplify_object(data, parent):
yield res
elif self.is_array:
for item in... | [
"def",
"triplify",
"(",
"self",
",",
"data",
",",
"parent",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"if",
"self",
".",
"is_object",
":",
"for",
"res",
"in",
"self",
".",
"_triplify_object",
"(",
"data",
",",
"parent",
")",
... | 37.368421 | 15.421053 |
def get_basket_items(request):
"""
Get all items in the basket
"""
bid = basket_id(request)
return BasketItem.objects.filter(basket_id=bid), bid | [
"def",
"get_basket_items",
"(",
"request",
")",
":",
"bid",
"=",
"basket_id",
"(",
"request",
")",
"return",
"BasketItem",
".",
"objects",
".",
"filter",
"(",
"basket_id",
"=",
"bid",
")",
",",
"bid"
] | 27.333333 | 7.333333 |
def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = []
if isinstance(self.output(), list):
log_output = os.path.split(self.output()[0].path)
else:
log_output = os.path.split(self.... | [
"def",
"_run_job",
"(",
"self",
")",
":",
"args",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"output",
"(",
")",
",",
"list",
")",
":",
"log_output",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"output",
"(",
")",
"[",
"0"... | 35.630769 | 19.323077 |
def set_resource_value(self, device_id, resource_path, resource_value,
fix_path=True, timeout=None):
"""Set resource value for given resource path, on device.
Will block and wait for response to come through. Usage:
.. code-block:: python
try:
... | [
"def",
"set_resource_value",
"(",
"self",
",",
"device_id",
",",
"resource_path",
",",
"resource_value",
",",
"fix_path",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"ensure_notifications_thread",
"(",
")",
"return",
"self",
".",
"set_reso... | 37.925926 | 17.925926 |
def kill_tasks(self, app_id, scale=False, wipe=False,
host=None, batch_size=0, batch_delay=0):
"""Kill all tasks belonging to app.
:param str app_id: application ID
:param bool scale: if true, scale down the app by the number of tasks killed
:param str host: if provid... | [
"def",
"kill_tasks",
"(",
"self",
",",
"app_id",
",",
"scale",
"=",
"False",
",",
"wipe",
"=",
"False",
",",
"host",
"=",
"None",
",",
"batch_size",
"=",
"0",
",",
"batch_delay",
"=",
"0",
")",
":",
"def",
"batch",
"(",
"iterable",
",",
"size",
")"... | 48.741935 | 23.032258 |
def wider_bn(layer, start_dim, total_dim, n_add, weighted=True):
'''wider batch norm layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_batch_norm_class(n_dim)(layer.num_features + n_add)
weights = layer.get_weights()
new_weights = [
add_noise(np.ones(n_add, dtype=... | [
"def",
"wider_bn",
"(",
"layer",
",",
"start_dim",
",",
"total_dim",
",",
"n_add",
",",
"weighted",
"=",
"True",
")",
":",
"n_dim",
"=",
"get_n_dim",
"(",
"layer",
")",
"if",
"not",
"weighted",
":",
"return",
"get_batch_norm_class",
"(",
"n_dim",
")",
"(... | 36.076923 | 23.615385 |
def dead(self):
"""Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false.
"""
if not self._weak:
return False
cb = self._callback()
... | [
"def",
"dead",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_weak",
":",
"return",
"False",
"cb",
"=",
"self",
".",
"_callback",
"(",
")",
"if",
"cb",
"is",
"None",
":",
"return",
"True",
"return",
"False"
] | 28.615385 | 17.230769 |
def get_status(self):
"""Get the details from the bulb."""
try:
request = requests.get(
'{}/{}/'.format(self.resource, URI), timeout=self.timeout)
raw_data = request.json()
# Doesn't always work !!!!!
#self._mac = next(iter(self.raw_data))
... | [
"def",
"get_status",
"(",
"self",
")",
":",
"try",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"'{}/{}/'",
".",
"format",
"(",
"self",
".",
"resource",
",",
"URI",
")",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"raw_data",
"=",
"request... | 41.75 | 12.75 |
def zero_dataset(train=False, dev=False, test=False, train_rows=256, dev_rows=64, test_rows=64):
"""
Load the Zero dataset.
The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for
integration testing. The extreme simplicity of the dataset allows for models to learn th... | [
"def",
"zero_dataset",
"(",
"train",
"=",
"False",
",",
"dev",
"=",
"False",
",",
"test",
"=",
"False",
",",
"train_rows",
"=",
"256",
",",
"dev_rows",
"=",
"64",
",",
"test_rows",
"=",
"64",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"is_requested",
"... | 42.578947 | 29.052632 |
def initialize_bars(self, sender=None, **kwargs):
"""Calls the initializers of all bound navigation bars."""
for bar in self.bars.values():
for initializer in bar.initializers:
initializer(self) | [
"def",
"initialize_bars",
"(",
"self",
",",
"sender",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"bar",
"in",
"self",
".",
"bars",
".",
"values",
"(",
")",
":",
"for",
"initializer",
"in",
"bar",
".",
"initializers",
":",
"initializer",
"... | 46.8 | 5.2 |
def getFileDialogFilter(self):
""" Returns a filter that can be used in open file dialogs,
for example: 'All files (*);;Txt (*.txt;*.text);;netCDF(*.nc;*.nc4)'
"""
filters = []
for regRti in self.items:
filters.append(regRti.getFileDialogFilter())
return '... | [
"def",
"getFileDialogFilter",
"(",
"self",
")",
":",
"filters",
"=",
"[",
"]",
"for",
"regRti",
"in",
"self",
".",
"items",
":",
"filters",
".",
"append",
"(",
"regRti",
".",
"getFileDialogFilter",
"(",
")",
")",
"return",
"';;'",
".",
"join",
"(",
"fi... | 41.25 | 12.5 |
def client_getname(self, encoding=_NOTSET):
"""Get the current connection name."""
return self.execute(b'CLIENT', b'GETNAME', encoding=encoding) | [
"def",
"client_getname",
"(",
"self",
",",
"encoding",
"=",
"_NOTSET",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'CLIENT'",
",",
"b'GETNAME'",
",",
"encoding",
"=",
"encoding",
")"
] | 52.666667 | 10.666667 |
def slow_highlight(img1, img2, opts):
"""Try to find similar areas between two images.
Produces two masks for img1 and img2.
The algorithm works by comparing every possible alignment of the images,
smoothing it a bit to reduce spurious matches in areas that are
perceptibly different (e.g. text), a... | [
"def",
"slow_highlight",
"(",
"img1",
",",
"img2",
",",
"opts",
")",
":",
"w1",
",",
"h1",
"=",
"img1",
".",
"size",
"w2",
",",
"h2",
"=",
"img2",
".",
"size",
"W",
",",
"H",
"=",
"max",
"(",
"w1",
",",
"w2",
")",
",",
"max",
"(",
"h1",
","... | 34.666667 | 21.347222 |
def get_url_for_service(service, region, endpoint_type):
if 'type' not in service:
return None
identity_version = get_version_from_service(service)
service_endpoints = service.get('endpoints', [])
available_endpoints = [endpoint for endpoint in service_endpoints
if re... | [
"def",
"get_url_for_service",
"(",
"service",
",",
"region",
",",
"endpoint_type",
")",
":",
"if",
"'type'",
"not",
"in",
"service",
":",
"return",
"None",
"identity_version",
"=",
"get_version_from_service",
"(",
"service",
")",
"service_endpoints",
"=",
"service... | 43.37931 | 19.103448 |
def write_to_stream(self, stream_id, data, sandbox=None):
"""
Write to the stream
:param stream_id: The stream identifier
:param data: The stream instances
:param sandbox: The sandbox for this stream
:type stream_id: StreamId
:return: None
:raises: NotImp... | [
"def",
"write_to_stream",
"(",
"self",
",",
"stream_id",
",",
"data",
",",
"sandbox",
"=",
"None",
")",
":",
"if",
"sandbox",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"if",
"stream_id",
"not",
"in",
"self",
".",
"streams",
":",
"raise",
... | 33.769231 | 18.538462 |
def command_dependents(options):
"""Command launched by CLI."""
dependents = dependencies(options.package, options.recursive, options.info)
if dependents:
print(*dependents, sep='\n') | [
"def",
"command_dependents",
"(",
"options",
")",
":",
"dependents",
"=",
"dependencies",
"(",
"options",
".",
"package",
",",
"options",
".",
"recursive",
",",
"options",
".",
"info",
")",
"if",
"dependents",
":",
"print",
"(",
"*",
"dependents",
",",
"se... | 33.166667 | 18.833333 |
def _columns_for_table(table_name):
"""
Return all of the columns registered for a given table.
Parameters
----------
table_name : str
Returns
-------
columns : dict of column wrappers
Keys will be column names.
"""
return {cname: col
for (tname, cname), co... | [
"def",
"_columns_for_table",
"(",
"table_name",
")",
":",
"return",
"{",
"cname",
":",
"col",
"for",
"(",
"tname",
",",
"cname",
")",
",",
"col",
"in",
"_COLUMNS",
".",
"items",
"(",
")",
"if",
"tname",
"==",
"table_name",
"}"
] | 21.235294 | 18.882353 |
def is_subdomain(self, other):
"""Is self a subdomain of other?
The notion of subdomain includes equality.
@rtype: bool
"""
(nr, o, nl) = self.fullcompare(other)
if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL:
return True
return False | [
"def",
"is_subdomain",
"(",
"self",
",",
"other",
")",
":",
"(",
"nr",
",",
"o",
",",
"nl",
")",
"=",
"self",
".",
"fullcompare",
"(",
"other",
")",
"if",
"nr",
"==",
"NAMERELN_SUBDOMAIN",
"or",
"nr",
"==",
"NAMERELN_EQUAL",
":",
"return",
"True",
"r... | 27.181818 | 16.545455 |
def adsSyncSetTimeoutEx(port, nMs):
# type: (int, int) -> None
"""Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms
"""
adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx
cms = ctypes.c_long(nMs)
err_code = adsSyncSetTimeoutFct(po... | [
"def",
"adsSyncSetTimeoutEx",
"(",
"port",
",",
"nMs",
")",
":",
"# type: (int, int) -> None",
"adsSyncSetTimeoutFct",
"=",
"_adsDLL",
".",
"AdsSyncSetTimeoutEx",
"cms",
"=",
"ctypes",
".",
"c_long",
"(",
"nMs",
")",
"err_code",
"=",
"adsSyncSetTimeoutFct",
"(",
"... | 28.153846 | 14.769231 |
def save_as(self, new_filename):
"""
Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing.
"""
xfile._save_file(
self._filename, self._workbookTree, new_filename) | [
"def",
"save_as",
"(",
"self",
",",
"new_filename",
")",
":",
"xfile",
".",
"_save_file",
"(",
"self",
".",
"_filename",
",",
"self",
".",
"_workbookTree",
",",
"new_filename",
")"
] | 23.076923 | 20.461538 |
def pack_into_dict(fmt, names, buf, offset, data, **kwargs):
"""Same as :func:`~bitstruct.pack_into()`, but data is read from a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
"""
return CompiledFormatDict(fmt, names).pack_into(buf,
... | [
"def",
"pack_into_dict",
"(",
"fmt",
",",
"names",
",",
"buf",
",",
"offset",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"CompiledFormatDict",
"(",
"fmt",
",",
"names",
")",
".",
"pack_into",
"(",
"buf",
",",
"offset",
",",
"data",
","... | 37.25 | 21.666667 |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Set CPC Power Capping (any CPC mode)."""
assert wait_for_completion is True # async not supported yet
cpc_oid = uri_parms[0]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid... | [
"def",
"post",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"body",
",",
"logon_required",
",",
"wait_for_completion",
")",
":",
"assert",
"wait_for_completion",
"is",
"True",
"# async not supported yet",
"cpc_oid",
"=",
"uri_parms",
"[",
"0",
... | 50.071429 | 25 |
async def _download_lsst_bibtex(bibtex_names):
"""Asynchronously download a set of lsst-texmf BibTeX bibliographies from
GitHub.
Parameters
----------
bibtex_names : sequence of `str`
Names of lsst-texmf BibTeX files to download. For example:
.. code-block:: python
['ls... | [
"async",
"def",
"_download_lsst_bibtex",
"(",
"bibtex_names",
")",
":",
"blob_url_template",
"=",
"(",
"'https://raw.githubusercontent.com/lsst/lsst-texmf/master/texmf/'",
"'bibtex/bib/{name}.bib'",
")",
"urls",
"=",
"[",
"blob_url_template",
".",
"format",
"(",
"name",
"="... | 29.548387 | 22.645161 |
def get_elemental_abunds(self,cycle,index=None):
"""
returns the elemental abundances for one cycle, either
for the whole star or a specific zone depending upon
the value of 'index'.
Parameters
----------
cycle : string or integer
Model to get the abu... | [
"def",
"get_elemental_abunds",
"(",
"self",
",",
"cycle",
",",
"index",
"=",
"None",
")",
":",
"isoabunds",
"=",
"self",
".",
"se",
".",
"get",
"(",
"cycle",
",",
"'iso_massf'",
")",
"A",
"=",
"array",
"(",
"self",
".",
"se",
".",
"A",
")",
"Z",
... | 34.4 | 19.6 |
def update_function(self, param_vals):
"""Updates the opt_obj, returns new error."""
self.opt_obj.update_function(param_vals)
return self.opt_obj.get_error() | [
"def",
"update_function",
"(",
"self",
",",
"param_vals",
")",
":",
"self",
".",
"opt_obj",
".",
"update_function",
"(",
"param_vals",
")",
"return",
"self",
".",
"opt_obj",
".",
"get_error",
"(",
")"
] | 44.5 | 2.75 |
def drop_indexes(self):
"""Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automaticall... | [
"def",
"drop_indexes",
"(",
"self",
")",
":",
"self",
".",
"__database",
".",
"client",
".",
"_purge_index",
"(",
"self",
".",
"__database",
".",
"name",
",",
"self",
".",
"__name",
")",
"self",
".",
"drop_index",
"(",
"\"*\"",
")"
] | 38.176471 | 24.352941 |
def _get_connection(self):
'''
_get_connection - Maybe get a new connection, or reuse if passed in.
Will share a connection with a model
internal
'''
if self._connection is None:
self._connection = self._get_new_connection()
return self._connection | [
"def",
"_get_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
"is",
"None",
":",
"self",
".",
"_connection",
"=",
"self",
".",
"_get_new_connection",
"(",
")",
"return",
"self",
".",
"_connection"
] | 29.111111 | 19.777778 |
def _is_iterable(item):
""" Checks if an item is iterable (list, tuple, generator), but not string """
return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types) | [
"def",
"_is_iterable",
"(",
"item",
")",
":",
"return",
"isinstance",
"(",
"item",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")"
] | 65.666667 | 23 |
def _vn_decode(self, msg):
"""VN: Version information."""
elkm1_version = "{}.{}.{}".format(int(msg[4:6], 16), int(msg[6:8], 16),
int(msg[8:10], 16))
xep_version = "{}.{}.{}".format(int(msg[10:12], 16), int(msg[12:14], 16),
... | [
"def",
"_vn_decode",
"(",
"self",
",",
"msg",
")",
":",
"elkm1_version",
"=",
"\"{}.{}.{}\"",
".",
"format",
"(",
"int",
"(",
"msg",
"[",
"4",
":",
"6",
"]",
",",
"16",
")",
",",
"int",
"(",
"msg",
"[",
"6",
":",
"8",
"]",
",",
"16",
")",
","... | 60 | 24.285714 |
def populate(self, priority, address, rtr, data):
"""
data bytes (high + low)
1 + 2 = current temp
3 + 4 = min temp
5 + 6 = max temp
:return: None
"""
assert isinstance(data, bytes)
self.needs_no_rtr(rtr)
self.needs_data(d... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
")",
"self",
".",
"needs_data",
"(",
"data",
",",
"6"... | 36.866667 | 10.6 |
def forwards(self, orm):
"Write your forwards methods here."
orm['avocado.DataField'].objects.get_or_create(
app_name='variants',
model_name='variantphenotype',
field_name='hgmd_id',
defaults={
'name': 'HGMD',
'published': T... | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"orm",
"[",
"'avocado.DataField'",
"]",
".",
"objects",
".",
"get_or_create",
"(",
"app_name",
"=",
"'variants'",
",",
"model_name",
"=",
"'variantphenotype'",
",",
"field_name",
"=",
"'hgmd_id'",
",",
"d... | 32.9 | 11.1 |
def cli(env, billing_id, datacenter):
"""Adds a load balancer given the id returned from create-options."""
mgr = SoftLayer.LoadBalancerManager(env.client)
if not formatting.confirm("This action will incur charges on your "
"account. Continue?"):
raise exceptions.CLIAb... | [
"def",
"cli",
"(",
"env",
",",
"billing_id",
",",
"datacenter",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"formatting",
".",
"confirm",
"(",
"\"This action will incur charges on your \"",
"\"accou... | 47.888889 | 13.777778 |
def dM(self, t, param, Mt, tips=None, gaps=None):
"""See docs for method in `Model` abstract base class."""
assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t)
assert (param == 't') or (param in self.freeparams), (
"Invalid param: {0}".format(param))
if Mt ... | [
"def",
"dM",
"(",
"self",
",",
"t",
",",
"param",
",",
"Mt",
",",
"tips",
"=",
"None",
",",
"gaps",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"t",
",",
"float",
")",
"and",
"t",
">",
"0",
",",
"\"Invalid t: {0}\"",
".",
"format",
"(",
... | 46.755556 | 18.677778 |
def intersect_one_round(candidates, intersections):
"""Perform one step of the intersection process.
.. note::
This is a helper for :func:`_all_intersections` and that function
has a Fortran equivalent.
Checks if the bounding boxes of each pair in ``candidates``
intersect. If the boundi... | [
"def",
"intersect_one_round",
"(",
"candidates",
",",
"intersections",
")",
":",
"next_candidates",
"=",
"[",
"]",
"# NOTE: In the below we replace ``isinstance(a, B)`` with",
"# ``a.__class__ is B``, which is a 3-3.5x speedup.",
"for",
"first",
",",
"second",
"in",
"cand... | 42.027027 | 21.905405 |
def _chk_type(recdef, rec):
"""Checks if type of `rec` matches `recdef`
:param recdef: instance of RecordDef
:param rec: instance of Record
:raises: `TypeError`
"""
if len(recdef) != len(rec):
raise TypeError("Number of columns (%d) is different from ... | [
"def",
"_chk_type",
"(",
"recdef",
",",
"rec",
")",
":",
"if",
"len",
"(",
"recdef",
")",
"!=",
"len",
"(",
"rec",
")",
":",
"raise",
"TypeError",
"(",
"\"Number of columns (%d) is different from RecordDef (%d)\"",
"%",
"(",
"len",
"(",
"rec",
")",
",",
"l... | 46.136364 | 17.136364 |
def postinit(
self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None
):
"""Do some setup after initialisation.
:param bases: What the class inherits from.
:type bases: list(NodeNG)
:param body: The contents of the class body.
:type body: list(No... | [
"def",
"postinit",
"(",
"self",
",",
"bases",
",",
"body",
",",
"decorators",
",",
"newstyle",
"=",
"None",
",",
"metaclass",
"=",
"None",
",",
"keywords",
"=",
"None",
")",
":",
"self",
".",
"keywords",
"=",
"keywords",
"self",
".",
"bases",
"=",
"b... | 32.612903 | 18 |
def data(self, column, role):
"""Return the data for the specified column and role
For DisplayRole the element in the list will be converted to a sting and returned.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDa... | [
"def",
"data",
"(",
"self",
",",
"column",
",",
"role",
")",
":",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
":",
"if",
"column",
">=",
"0",
"and",
"column",
"<",
"len",
"(",
"self",
".",
"_list",
")",
":",
"return",
"str",
"(",... | 38.8125 | 16 |
def to_type(self, dtype: type, *cols, **kwargs):
"""
Convert colums values to a given type in the
main dataframe
:param dtype: a type to convert to: ex: ``str``
:type dtype: type
:param \*cols: names of the colums
:type \*cols: str, at least one
:param \... | [
"def",
"to_type",
"(",
"self",
",",
"dtype",
":",
"type",
",",
"*",
"cols",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"allcols",
"=",
"self",
".",
"df",
".",
"columns",
".",
"values",
"for",
"col",
"in",
"cols",
":",
"if",
"col",
"not",
"i... | 34.913043 | 13.608696 |
def create(self):
"""
Executes ``ansible-playbook`` against the create playbook and returns
None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.create)
pb.execute() | [
"def",
"create",
"(",
"self",
")",
":",
"pb",
"=",
"self",
".",
"_get_ansible_playbook",
"(",
"self",
".",
"playbooks",
".",
"create",
")",
"pb",
".",
"execute",
"(",
")"
] | 25.777778 | 20.888889 |
def optional(e, default=Ignore):
"""
Create a PEG function to optionally match an expression.
"""
def match_optional(s, grm=None, pos=0):
try:
return e(s, grm, pos)
except PegreError:
return PegreResult(s, default, (pos, pos))
return match_optional | [
"def",
"optional",
"(",
"e",
",",
"default",
"=",
"Ignore",
")",
":",
"def",
"match_optional",
"(",
"s",
",",
"grm",
"=",
"None",
",",
"pos",
"=",
"0",
")",
":",
"try",
":",
"return",
"e",
"(",
"s",
",",
"grm",
",",
"pos",
")",
"except",
"Pegre... | 29.9 | 10.9 |
def plot_variability_thresholds(varthreshpkl,
xmin_lcmad_stdev=5.0,
xmin_stetj_stdev=2.0,
xmin_iqr_stdev=2.0,
xmin_inveta_stdev=2.0,
lcformat='hat-sql',
... | [
"def",
"plot_variability_thresholds",
"(",
"varthreshpkl",
",",
"xmin_lcmad_stdev",
"=",
"5.0",
",",
"xmin_stetj_stdev",
"=",
"2.0",
",",
"xmin_iqr_stdev",
"=",
"2.0",
",",
"xmin_inveta_stdev",
"=",
"2.0",
",",
"lcformat",
"=",
"'hat-sql'",
",",
"lcformatdir",
"="... | 36.224044 | 19.852459 |
def mute(self, mute):
"""Mute receiver via HTTP get command."""
try:
if mute:
if self.send_get_command(self._urls.command_mute_on):
self._mute = STATE_ON
return True
else:
return False
els... | [
"def",
"mute",
"(",
"self",
",",
"mute",
")",
":",
"try",
":",
"if",
"mute",
":",
"if",
"self",
".",
"send_get_command",
"(",
"self",
".",
"_urls",
".",
"command_mute_on",
")",
":",
"self",
".",
"_mute",
"=",
"STATE_ON",
"return",
"True",
"else",
":"... | 36.333333 | 15.611111 |
def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph):
"""
Looks for sub-isomorphisms of rhs into lhs
:param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph)
:param rhs_graph: The smaller graph
:return: The list of matching names
""... | [
"def",
"get_variables_substitution_dictionaries",
"(",
"self",
",",
"lhs_graph",
",",
"rhs_graph",
")",
":",
"if",
"not",
"rhs_graph",
":",
"return",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"self",
".",
"matching_code_container",
".",
"add_graph_to_namespace",
... | 45.076923 | 19.692308 |
def authenticate(self, code: str) -> 'Preston':
"""Authenticates using the code from the EVE SSO.
A new Preston object is returned; this object is not modified.
The intended usage is:
auth = preston.authenticate('some_code_here')
Args:
code: SSO code
... | [
"def",
"authenticate",
"(",
"self",
",",
"code",
":",
"str",
")",
"->",
"'Preston'",
":",
"headers",
"=",
"self",
".",
"_get_authorization_headers",
"(",
")",
"data",
"=",
"{",
"'grant_type'",
":",
"'authorization_code'",
",",
"'code'",
":",
"code",
"}",
"... | 35.896552 | 21.482759 |
def density_grid(*args, **kwargs):
"""
Estimates point density of the given linear orientation measurements
(Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes
based on the `measurement` keyword argument.). Returns a regular (in
lat-long space) grid of density estimates over a hem... | [
"def",
"density_grid",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"do_nothing",
"(",
"x",
",",
"y",
")",
":",
"return",
"x",
",",
"y",
"measurement",
"=",
"kwargs",
".",
"get",
"(",
"'measurement'",
",",
"'poles'",
")",
"gridsize",
... | 43.786885 | 22.704918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.