text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
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 | 0.008678 |
def set_default_init_cli_cmds(self):
"""
Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name>
and set testcase <tc name>
:return: List of default cli initialization commands.
"""
init_cli_cmds = []
init_cli_cmds.append("set ... | [
"def",
"set_default_init_cli_cmds",
"(",
"self",
")",
":",
"init_cli_cmds",
"=",
"[",
"]",
"init_cli_cmds",
".",
"append",
"(",
"\"set --retcode true\"",
")",
"init_cli_cmds",
".",
"append",
"(",
"\"echo off\"",
")",
"init_cli_cmds",
".",
"append",
"(",
"\"set --v... | 37.9375 | 0.006431 |
def add_tag():
"""
Obtains the data from the pipe and appends the given tag.
"""
if len(sys.argv) > 1:
tag = sys.argv[1]
doc_mapper = DocMapper()
if doc_mapper.is_pipe:
count = 0
for obj in doc_mapper.get_pipe():
obj.add_tag(tag)
... | [
"def",
"add_tag",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"tag",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"doc_mapper",
"=",
"DocMapper",
"(",
")",
"if",
"doc_mapper",
".",
"is_pipe",
":",
"count",
"=",
"0",
"for... | 31.263158 | 0.001634 |
def clean_community_indexes(communityID):
"""
Takes input of community assignments. Returns reindexed community assignment by using smallest numbers possible.
Parameters
----------
communityID : array-like
list or array of integers. Output from community detection algorithems.
Returns... | [
"def",
"clean_community_indexes",
"(",
"communityID",
")",
":",
"communityID",
"=",
"np",
".",
"array",
"(",
"communityID",
")",
"cid_shape",
"=",
"communityID",
".",
"shape",
"if",
"len",
"(",
"cid_shape",
")",
">",
"1",
":",
"communityID",
"=",
"communityI... | 30.25 | 0.003003 |
def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) | [
"def",
"find_task_by_id",
"(",
"self",
",",
"id",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"return",
"session",
".",
"query",
"(",
"TaskRecord",
")",
".",
"get",
"(",
"id",
")"... | 34.666667 | 0.00939 |
def execute_policy(self, policy):
"""
Executes the specified policy for this scaling group.
"""
return self.manager.execute_policy(scaling_group=self, policy=policy) | [
"def",
"execute_policy",
"(",
"self",
",",
"policy",
")",
":",
"return",
"self",
".",
"manager",
".",
"execute_policy",
"(",
"scaling_group",
"=",
"self",
",",
"policy",
"=",
"policy",
")"
] | 38.6 | 0.010152 |
def get_function(self):
"""Gets the ``Function`` for this authorization.
return: (osid.authorization.Function) - the function
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template... | [
"def",
"get_function",
"(",
"self",
")",
":",
"# Implemented from template for osid.learning.Activity.get_objective",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'functionId'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'function empty'",... | 50.411765 | 0.004582 |
def get_containing_period(cls, *periods):
"""Given a bunch of TimePeriods, return a TimePeriod that most closely
contains them."""
if any(not isinstance(period, TimePeriod) for period in periods):
raise TypeError("periods must all be TimePeriods: {}".format(periods))
latest... | [
"def",
"get_containing_period",
"(",
"cls",
",",
"*",
"periods",
")",
":",
"if",
"any",
"(",
"not",
"isinstance",
"(",
"period",
",",
"TimePeriod",
")",
"for",
"period",
"in",
"periods",
")",
":",
"raise",
"TypeError",
"(",
"\"periods must all be TimePeriods: ... | 37.391304 | 0.003401 |
def asyncPipeLoop(context=None, _INPUT=None, conf=None, embed=None, **kwargs):
"""An operator that asynchronously loops over the input and performs the
embedded submodule. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred itera... | [
"def",
"asyncPipeLoop",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"embed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cust_func",
"=",
"get_cust_func",
"(",
"context",
",",
"conf",
",",
"embed",
","... | 38.935484 | 0.000808 |
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into JSON, returning a bytestring.
"""
if data is None:
return bytes()
renderer_context = renderer_context or {}
indent = self.get_indent(accepted_media_type, renderer_... | [
"def",
"render",
"(",
"self",
",",
"data",
",",
"accepted_media_type",
"=",
"None",
",",
"renderer_context",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"bytes",
"(",
")",
"renderer_context",
"=",
"renderer_context",
"or",
"{",
"}",
... | 41.878788 | 0.001414 |
def get_sources_by_name(self, name):
"""Return a list of sources in the ROI matching the given
name. The input name string can match any of the strings in
the names property of the source object. Case and whitespace
are ignored when matching name strings.
Parameters
--... | [
"def",
"get_sources_by_name",
"(",
"self",
",",
"name",
")",
":",
"index_name",
"=",
"name",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"index_name",
"in",
"self",
".",
"_src_dict",
":",
"return",
"list",
"(",
"self",
"... | 30.954545 | 0.005698 |
def _column_width(self, index=None, name=None, max_width=300, **kwargs):
"""
:param index: int of the column index
:param name: str of the name of the column
:param max_width: int of the max size of characters in the width
:return: int of the width of this column
"""
... | [
"def",
"_column_width",
"(",
"self",
",",
"index",
"=",
"None",
",",
"name",
"=",
"None",
",",
"max_width",
"=",
"300",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"name",
"is",
"not",
"None",
"or",
"index",
"is",
"not",
"None",
"if",
"name",
"and... | 38.192308 | 0.001965 |
def get_pointee_abi_size(self, ty):
"""
Get ABI size of pointee type of LLVM pointer type *ty*.
"""
size = ffi.lib.LLVMPY_ABISizeOfElementType(self, ty)
if size == -1:
raise RuntimeError("Not a pointer type: %s" % (ty,))
return size | [
"def",
"get_pointee_abi_size",
"(",
"self",
",",
"ty",
")",
":",
"size",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_ABISizeOfElementType",
"(",
"self",
",",
"ty",
")",
"if",
"size",
"==",
"-",
"1",
":",
"raise",
"RuntimeError",
"(",
"\"Not a pointer type: %s\"",
... | 35.625 | 0.006849 |
def get_save_info(path_runcontrol: str)->Tuple[int, Path, str]:
'''get necessary information for saving supy results, which are (freq_s, dir_save, site)
Parameters
----------
path_runcontrol : Path
Path to SUEWS :ref:`RunControl.nml <suews:RunControl.nml>`
Returns
-------
tuple
... | [
"def",
"get_save_info",
"(",
"path_runcontrol",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"Path",
",",
"str",
"]",
":",
"try",
":",
"path_runcontrol",
"=",
"Path",
"(",
"path_runcontrol",
")",
".",
"expanduser",
"(",
")",
".",
"resolve",
"(",
")... | 30.971429 | 0.002683 |
def create(self, asset_content, friendly_name, tags='', optimize=False):
"""
Create an asset on the server
You must provide the asset with a friendly name
for the server to generate a path from.
"""
return self._create_asset({
'asset': b64encode(asset_content... | [
"def",
"create",
"(",
"self",
",",
"asset_content",
",",
"friendly_name",
",",
"tags",
"=",
"''",
",",
"optimize",
"=",
"False",
")",
":",
"return",
"self",
".",
"_create_asset",
"(",
"{",
"'asset'",
":",
"b64encode",
"(",
"asset_content",
")",
",",
"'fr... | 32.357143 | 0.004292 |
def get_bounding_box_list_ghostscript(input_doc_fname, res_x, res_y, full_page_box):
"""Call Ghostscript to get the bounding box list. Cannot set a threshold
with this method."""
if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)
res = str(res_x) + "x" + str(res_y)
box_arg = "-dU... | [
"def",
"get_bounding_box_list_ghostscript",
"(",
"input_doc_fname",
",",
"res_x",
",",
"res_y",
",",
"full_page_box",
")",
":",
"if",
"not",
"gs_executable",
":",
"init_and_test_gs_executable",
"(",
"exit_on_fail",
"=",
"True",
")",
"res",
"=",
"str",
"(",
"res_x"... | 51.148936 | 0.009388 |
def cli_aliases(self):
r"""Developer script aliases.
"""
scripting_groups = []
aliases = {}
for cli_class in self.cli_classes:
instance = cli_class()
if getattr(instance, "alias", None):
scripting_group = getattr(instance, "scripting_group"... | [
"def",
"cli_aliases",
"(",
"self",
")",
":",
"scripting_groups",
"=",
"[",
"]",
"aliases",
"=",
"{",
"}",
"for",
"cli_class",
"in",
"self",
".",
"cli_classes",
":",
"instance",
"=",
"cli_class",
"(",
")",
"if",
"getattr",
"(",
"instance",
",",
"\"alias\"... | 47.37037 | 0.002298 |
def times(self, start, stop, callback=None, **kwargs):
'''The times between times *start* and *stop*.'''
s1 = self.pickler.dumps(start)
s2 = self.pickler.dumps(stop)
backend = self.read_backend
res = backend.structure(self).times(s1, s2, **kwargs)
return backend.exe... | [
"def",
"times",
"(",
"self",
",",
"start",
",",
"stop",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"s1",
"=",
"self",
".",
"pickler",
".",
"dumps",
"(",
"start",
")",
"s2",
"=",
"self",
".",
"pickler",
".",
"dumps",
"(",
"... | 50.142857 | 0.005602 |
def get_value_display(self):
"""Human friendly value output"""
if self.display_as == 'percentage':
return '{0}%'.format(self.latest_value)
if self.display_as == 'boolean':
return bool(self.latest_value)
if self.display_as == 'byte':
return defaultfilte... | [
"def",
"get_value_display",
"(",
"self",
")",
":",
"if",
"self",
".",
"display_as",
"==",
"'percentage'",
":",
"return",
"'{0}%'",
".",
"format",
"(",
"self",
".",
"latest_value",
")",
"if",
"self",
".",
"display_as",
"==",
"'boolean'",
":",
"return",
"boo... | 45.090909 | 0.003953 |
def evaluate(
loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir,
agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path,
num_debug_videos=1, random_starts_step_limit=None,
report_fn=None, report_metric=None
):
"""Evaluate."""
if eval_with_learner:
assert... | [
"def",
"evaluate",
"(",
"loop_hparams",
",",
"planner_hparams",
",",
"policy_dir",
",",
"model_dir",
",",
"eval_metrics_dir",
",",
"agent_type",
",",
"eval_mode",
",",
"eval_with_learner",
",",
"log_every_steps",
",",
"debug_video_path",
",",
"num_debug_videos",
"=",
... | 34.016949 | 0.010169 |
def validate_content(*objs):
"""Runs the correct validator for given `obj`ects. Assumes all same type"""
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) | [
"def",
"validate_content",
"(",
"*",
"objs",
")",
":",
"from",
".",
"main",
"import",
"Collection",
",",
"Module",
"validator",
"=",
"{",
"Collection",
":",
"cnxml",
".",
"validate_collxml",
",",
"Module",
":",
"cnxml",
".",
"validate_cnxml",
",",
"}",
"["... | 39.125 | 0.003125 |
def looks_like_python(name):
# type: (str) -> bool
"""
Determine whether the supplied filename looks like a possible name of python.
:param str name: The name of the provided file.
:return: Whether the provided name looks like python.
:rtype: bool
"""
if not any(name.lower().startswith... | [
"def",
"looks_like_python",
"(",
"name",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"any",
"(",
"name",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"py_name",
")",
"for",
"py_name",
"in",
"PYTHON_IMPLEMENTATIONS",
")",
":",
"return",
"False",
"match... | 31.5625 | 0.005769 |
def classify(self, term, **kwargs):
""" Returns the (most recently added) semantic type for the given term ("many" => "quantity").
If the term is not in the dictionary, try Taxonomy.classifiers.
"""
term = self._normalize(term)
if dict.__contains__(self, term):
re... | [
"def",
"classify",
"(",
"self",
",",
"term",
",",
"*",
"*",
"kwargs",
")",
":",
"term",
"=",
"self",
".",
"_normalize",
"(",
"term",
")",
"if",
"dict",
".",
"__contains__",
"(",
"self",
",",
"term",
")",
":",
"return",
"self",
"[",
"term",
"]",
"... | 49.866667 | 0.003937 |
def _validate_certificate_url(self, cert_url):
# type: (str) -> None
"""Validate the URL containing the certificate chain.
This method validates if the URL provided adheres to the format
mentioned here :
https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-we... | [
"def",
"_validate_certificate_url",
"(",
"self",
",",
"cert_url",
")",
":",
"# type: (str) -> None",
"parsed_url",
"=",
"urlparse",
"(",
"cert_url",
")",
"protocol",
"=",
"parsed_url",
".",
"scheme",
"if",
"protocol",
".",
"lower",
"(",
")",
"!=",
"CERT_CHAIN_UR... | 46.333333 | 0.001626 |
def dump_BSE_data_in_GW_run(self, BSE_dump=True):
"""
:param BSE_dump: boolean
:return: set the "do_bse" variable to one in cell.in
"""
if BSE_dump:
self.BSE_TDDFT_options.update(do_bse=1, do_tddft=0)
else:
self.BSE_TDDFT_options.update(do_bse=0, ... | [
"def",
"dump_BSE_data_in_GW_run",
"(",
"self",
",",
"BSE_dump",
"=",
"True",
")",
":",
"if",
"BSE_dump",
":",
"self",
".",
"BSE_TDDFT_options",
".",
"update",
"(",
"do_bse",
"=",
"1",
",",
"do_tddft",
"=",
"0",
")",
"else",
":",
"self",
".",
"BSE_TDDFT_o... | 32.2 | 0.006042 |
def recompute_missing_neighbors(self):
"""
Recomputes statistics for missing users of the current user's
network:
- ``User.percent_outofnetwork_calls``
- ``User.percent_outofnetwork_texts``
- ``User.percent_outofnetwork_contacts``
- ``User.percent_outofnetwork_ca... | [
"def",
"recompute_missing_neighbors",
"(",
"self",
")",
":",
"oon_records",
"=",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"records",
"if",
"self",
".",
"network",
".",
"get",
"(",
"r",
".",
"correspondent_id",
",",
"None",
")",
"is",
"None",
"]",
"num_... | 43.52381 | 0.001605 |
def set_account_username(self, account, old_username, new_username):
""" Account's username was changed. """
luser = self._get_account(old_username)
rename(luser, database=self._database, uid=new_username) | [
"def",
"set_account_username",
"(",
"self",
",",
"account",
",",
"old_username",
",",
"new_username",
")",
":",
"luser",
"=",
"self",
".",
"_get_account",
"(",
"old_username",
")",
"rename",
"(",
"luser",
",",
"database",
"=",
"self",
".",
"_database",
",",
... | 56.5 | 0.008734 |
def authorization(self, id_num):
"""Get information about authorization ``id``.
:param int id_num: (required), unique id of the authorization
:returns: :class:`Authorization <Authorization>`
"""
json = None
if int(id_num) > 0:
url = self._build_url('authoriza... | [
"def",
"authorization",
"(",
"self",
",",
"id_num",
")",
":",
"json",
"=",
"None",
"if",
"int",
"(",
"id_num",
")",
">",
"0",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'authorizations'",
",",
"str",
"(",
"id_num",
")",
")",
"json",
"=",
"se... | 40 | 0.004444 |
def load_model():
""" Load the model
Parameters
----------
direc: directory with all of the model files
Returns
-------
m: model object
"""
direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn"
m = model.CannonModel(2)
m.coeffs = np.load(direc + "/coeffs.npz")['arr_... | [
"def",
"load_model",
"(",
")",
":",
"direc",
"=",
"\"/home/annaho/TheCannon/code/lamost/mass_age/cn\"",
"m",
"=",
"model",
".",
"CannonModel",
"(",
"2",
")",
"m",
".",
"coeffs",
"=",
"np",
".",
"load",
"(",
"direc",
"+",
"\"/coeffs.npz\"",
")",
"[",
"'arr_0'... | 30.222222 | 0.012478 |
def parse_bind_address(address, default=('localhost', 8080)):
"""
>>> parse_bind_address('80')
('localhost', 80)
>>> parse_bind_address('0.0.0.0')
('0.0.0.0', 8080)
>>> parse_bind_address('0.0.0.0:8081')
('0.0.0.0', 8081)
"""
if ':' in address:
host, port = address.split(':',... | [
"def",
"parse_bind_address",
"(",
"address",
",",
"default",
"=",
"(",
"'localhost'",
",",
"8080",
")",
")",
":",
"if",
"':'",
"in",
"address",
":",
"host",
",",
"port",
"=",
"address",
".",
"split",
"(",
"':'",
",",
"1",
")",
"port",
"=",
"int",
"... | 26.421053 | 0.003846 |
def reset(self):
""" Re-initialises the environment.
"""
logger.info("Reseting environment.")
self._step = 0
# Reset the set-point of each generator to its original value.
gs = [g for g in self.case.online_generators if g.bus.type !=REFERENCE]
for i, g in enumer... | [
"def",
"reset",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Reseting environment.\"",
")",
"self",
".",
"_step",
"=",
"0",
"# Reset the set-point of each generator to its original value.",
"gs",
"=",
"[",
"g",
"for",
"g",
"in",
"self",
".",
"case",
"... | 33.826087 | 0.00375 |
def add_user(self, name, password=None, read_only=None, **kwargs):
"""Create user `name` with password `password`.
Add a new user with permissions for this :class:`Database`.
.. note:: Will change the password if user `name` already exists.
:Parameters:
- `name`: the name of... | [
"def",
"add_user",
"(",
"self",
",",
"name",
",",
"password",
"=",
"None",
",",
"read_only",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"string_type",
")",
":",
"raise",
"TypeError",
"(",
"\"name must b... | 45.186441 | 0.000734 |
def _parse_header_id(line):
"""
Pull the transcript or protein identifier from the header line
which starts with '>'
"""
if type(line) is not binary_type:
raise TypeError("Expected header line to be of type %s but got %s" % (
binary_type, type(line)))
if len(line) <= 1:
... | [
"def",
"_parse_header_id",
"(",
"line",
")",
":",
"if",
"type",
"(",
"line",
")",
"is",
"not",
"binary_type",
":",
"raise",
"TypeError",
"(",
"\"Expected header line to be of type %s but got %s\"",
"%",
"(",
"binary_type",
",",
"type",
"(",
"line",
")",
")",
"... | 31.566667 | 0.001025 |
def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False):
"""Checks whether targets are on silicon during a given campaign.
This function will write a csv table called targets_siliconFlag.csv,
which details the silicon status for each target listed in `infile`
(0 = not on silicon, 2 = on silion).
... | [
"def",
"K2onSilicon",
"(",
"infile",
",",
"fieldnum",
",",
"do_nearSiliconCheck",
"=",
"False",
")",
":",
"ra_sources_deg",
",",
"dec_sources_deg",
",",
"mag",
"=",
"parse_file",
"(",
"infile",
")",
"n_sources",
"=",
"np",
".",
"shape",
"(",
"ra_sources_deg",
... | 35.978723 | 0.000288 |
def _get_access_info(self, instance, db_key, db_name=None):
''' Convenience method to extract info from instance
'''
dsn = instance.get('dsn')
host = instance.get('host')
username = instance.get('username')
password = instance.get('password')
database = instance.g... | [
"def",
"_get_access_info",
"(",
"self",
",",
"instance",
",",
"db_key",
",",
"db_name",
"=",
"None",
")",
":",
"dsn",
"=",
"instance",
".",
"get",
"(",
"'dsn'",
")",
"host",
"=",
"instance",
".",
"get",
"(",
"'host'",
")",
"username",
"=",
"instance",
... | 40.235294 | 0.002857 |
def stop(self, measurementId, failureReason=None):
"""
informs the target the named measurement has completed
:param measurementId: the measurement that has completed.
:return:
"""
if failureReason is None:
self.endResponseCode = self._doPut(self.sendURL + "/c... | [
"def",
"stop",
"(",
"self",
",",
"measurementId",
",",
"failureReason",
"=",
"None",
")",
":",
"if",
"failureReason",
"is",
"None",
":",
"self",
".",
"endResponseCode",
"=",
"self",
".",
"_doPut",
"(",
"self",
".",
"sendURL",
"+",
"\"/complete\"",
")",
"... | 43 | 0.006211 |
def to_json(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True,
pretty=False):
"""Converts the response from to_dict to a JSON string. If pretty is True then newlines,
indentation and key sorting are used.
"""
return to_json(
self.to_dict(
include_keys=i... | [
"def",
"to_json",
"(",
"self",
",",
"*",
",",
"include_keys",
"=",
"None",
",",
"exclude_keys",
"=",
"None",
",",
"use_default_excludes",
"=",
"True",
",",
"pretty",
"=",
"False",
")",
":",
"return",
"to_json",
"(",
"self",
".",
"to_dict",
"(",
"include_... | 39.090909 | 0.009091 |
def get_agent_id(self):
"""Gets the agent ``Id`` who created this entry.
return: (osid.id.Id) - the agent ``Id``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.Resource.get_avatar_id_template
if not bool(sel... | [
"def",
"get_agent_id",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.Resource.get_avatar_id_template",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'agentId'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'this LogEnt... | 38.333333 | 0.006369 |
def docker_environment(env):
"""
Transform dictionary of environment variables into Docker -e parameters.
>>> result = docker_environment({'param1': 'val1', 'param2': 'val2'})
>>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"']
True
"""
return ' '.join(
... | [
"def",
"docker_environment",
"(",
"env",
")",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"\"-e \\\"%s=%s\\\"\"",
"%",
"(",
"key",
",",
"value",
".",
"replace",
"(",
"\"$\"",
",",
"\"\\\\$\"",
")",
".",
"replace",
"(",
"\"\\\"\"",
",",
"\"\\\\\\\"\"",
"... | 41 | 0.006508 |
def slugify(value):
''''
Slugify given value.
Credit to Djangoproject https://docs.djangoproject.com/en/2.0/_modules/django/utils/text/#slugify
'''
value = re.sub(r'[^\w\s-]', '', value).strip().lower()
return re.sub(r'[-\s]+', '-', value) | [
"def",
"slugify",
"(",
"value",
")",
":",
"value",
"=",
"re",
".",
"sub",
"(",
"r'[^\\w\\s-]'",
",",
"''",
",",
"value",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"return",
"re",
".",
"sub",
"(",
"r'[-\\s]+'",
",",
"'-'",
",",
"value",... | 36.714286 | 0.007605 |
def _run_concat_variant_files_gatk4(input_file_list, out_file, config):
"""Use GATK4 GatherVcfs for concatenation of scattered VCFs.
"""
if not utils.file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
params = ["-T", "GatherVcfs", "-I", input_file_list, "-O", ... | [
"def",
"_run_concat_variant_files_gatk4",
"(",
"input_file_list",
",",
"out_file",
",",
"config",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"config",
",",
"out_file",
")",
"as",
"tx_out_file",... | 57.388889 | 0.004762 |
def channels_twitter_monitored_twitter_handle_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/twitter_channel#getting-monitored-twitter-handle"
api_path = "/api/v2/channels/twitter/monitored_twitter_handles/{id}.json"
api_path = api_path.format(id=id)
return s... | [
"def",
"channels_twitter_monitored_twitter_handle_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/channels/twitter/monitored_twitter_handles/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
"... | 68.8 | 0.011494 |
def grok_vars(elements):
"""Returns a list of vars for which the value is being appropriately set
This currently includes the default filter, for-based iterators,
and the explicit use of set"""
default_vars = []
iterbody = None
if hasattr(elements, 'body'):
iterbody = elements.body
e... | [
"def",
"grok_vars",
"(",
"elements",
")",
":",
"default_vars",
"=",
"[",
"]",
"iterbody",
"=",
"None",
"if",
"hasattr",
"(",
"elements",
",",
"'body'",
")",
":",
"iterbody",
"=",
"elements",
".",
"body",
"elif",
"hasattr",
"(",
"elements",
",",
"'nodes'"... | 41.413793 | 0.000814 |
def pil_image(self):
"""A :class:`PIL.Image.Image` instance containing the image data."""
if not self._pil_image:
if self._format == "SVG":
raise VectorImageError("can't rasterise vector images")
self._pil_image = PIL.Image.open(StringIO(self.contents))
re... | [
"def",
"pil_image",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pil_image",
":",
"if",
"self",
".",
"_format",
"==",
"\"SVG\"",
":",
"raise",
"VectorImageError",
"(",
"\"can't rasterise vector images\"",
")",
"self",
".",
"_pil_image",
"=",
"PIL",
"."... | 47.714286 | 0.005882 |
def InsertMessage(self, message, timeout=None):
"""Inserts a message into the Fleetspeak server.
Sets message.source, if unset.
Args:
message: common_pb2.Message
The message to send.
timeout: How many seconds to try for.
Raises:
grpc.RpcError: if the RPC fails.
Invali... | [
"def",
"InsertMessage",
"(",
"self",
",",
"message",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"common_pb2",
".",
"Message",
")",
":",
"raise",
"InvalidArgument",
"(",
"\"Attempt to send unexpected message type: %s\"",
... | 32.793103 | 0.005107 |
def parse(self):
"""
Convert ACIS 'll' value into separate latitude and longitude.
"""
super(AcisIO, self).parse()
# This is more of a "mapping" step than a "parsing" step, but mappers
# only allow one-to-one mapping from input fields to output fields.
for row in... | [
"def",
"parse",
"(",
"self",
")",
":",
"super",
"(",
"AcisIO",
",",
"self",
")",
".",
"parse",
"(",
")",
"# This is more of a \"mapping\" step than a \"parsing\" step, but mappers",
"# only allow one-to-one mapping from input fields to output fields.",
"for",
"row",
"in",
"... | 35.857143 | 0.003883 |
def _add_variantcalls_to_output(out, data, items, is_somatic=False):
"""Call ploidy and convert into VCF and BED representations.
"""
call_file = "%s-call%s" % os.path.splitext(out["cns"])
if not utils.file_exists(call_file):
with file_transaction(data, call_file) as tx_call_file:
fi... | [
"def",
"_add_variantcalls_to_output",
"(",
"out",
",",
"data",
",",
"items",
",",
"is_somatic",
"=",
"False",
")",
":",
"call_file",
"=",
"\"%s-call%s\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"out",
"[",
"\"cns\"",
"]",
")",
"if",
"not",
"utils"... | 52.897436 | 0.002856 |
def reduce(self, op):
"""
Reduces average value over all workers.
:param op: 'sum' or 'mean', reduction operator
"""
if op not in ('sum', 'mean'):
raise NotImplementedError
distributed = (get_world_size() > 1)
if distributed:
# Backward/f... | [
"def",
"reduce",
"(",
"self",
",",
"op",
")",
":",
"if",
"op",
"not",
"in",
"(",
"'sum'",
",",
"'mean'",
")",
":",
"raise",
"NotImplementedError",
"distributed",
"=",
"(",
"get_world_size",
"(",
")",
">",
"1",
")",
"if",
"distributed",
":",
"# Backward... | 38.581395 | 0.002352 |
def client(self):
"""Return client for current application."""
if self._client is None:
self._client = self._client_builder()
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"self",
".",
"_client_builder",
"(",
")",
"return",
"self",
".",
"_client"
] | 35.4 | 0.01105 |
def execute_command(self):
"""
The genconfig command depends on predefined `Jinja2 <http://jinja.pocoo.org/>`_ \
templates for the skeleton configuration files. Taking the --type argument from the \
CLI input, the corresponding template file is used.
Settings for the configurat... | [
"def",
"execute_command",
"(",
"self",
")",
":",
"print",
"(",
"Back",
".",
"GREEN",
"+",
"Fore",
".",
"BLACK",
"+",
"\"Scrapple Genconfig\"",
")",
"print",
"(",
"Back",
".",
"RESET",
"+",
"Fore",
".",
"RESET",
")",
"directory",
"=",
"os",
".",
"path",... | 51.166667 | 0.007673 |
def delete_role(self, role_name):
"""Delete the given Role
:param role_name: the name of a role in the ab_role table
"""
session = self.get_session
role = session.query(sqla_models.Role)\
.filter(sqla_models.Role.name == role_name)\
.f... | [
"def",
"delete_role",
"(",
"self",
",",
"role_name",
")",
":",
"session",
"=",
"self",
".",
"get_session",
"role",
"=",
"session",
".",
"query",
"(",
"sqla_models",
".",
"Role",
")",
".",
"filter",
"(",
"sqla_models",
".",
"Role",
".",
"name",
"==",
"r... | 35.4375 | 0.003436 |
def _get_image_link_target_from_file(dir_path, image_file, force_no_processing=False):
"""
Get the value to be used as the href for links from thumbnail images. For
most image formats this will simply be the image file name itself. However,
some image formats (tif) are not natively displayable by many b... | [
"def",
"_get_image_link_target_from_file",
"(",
"dir_path",
",",
"image_file",
",",
"force_no_processing",
"=",
"False",
")",
":",
"# If we've specified to force no processing, just return the image filename",
"if",
"force_no_processing",
":",
"return",
"image_file",
"# First try... | 51.76 | 0.001517 |
def to_dict(cls, obj):
'''Serialises the object, by default serialises anything
that isn't prefixed with __, isn't in the blacklist, and isn't
callable.
'''
return {
k: getattr(obj, k)
for k in dir(obj)
if cls.serialisable(k, obj)
} | [
"def",
"to_dict",
"(",
"cls",
",",
"obj",
")",
":",
"return",
"{",
"k",
":",
"getattr",
"(",
"obj",
",",
"k",
")",
"for",
"k",
"in",
"dir",
"(",
"obj",
")",
"if",
"cls",
".",
"serialisable",
"(",
"k",
",",
"obj",
")",
"}"
] | 30.7 | 0.006329 |
def _process_organism_dbxref(self, limit):
"""
This is the mapping between the flybase organisms and
external identifier "FBsp". We will want to use the NCBITaxon as
the primary, if possible, but will default to a blank node/internal id
if that is all that is available
Bu... | [
"def",
"_process_organism_dbxref",
"(",
"self",
",",
"limit",
")",
":",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"else",
":",
"graph",
"=",
"self",
".",
"graph",
"model",
"=",
"Model",
"(",
"graph",
")",
"line_counter"... | 37.732143 | 0.001384 |
def delete(self, cascade=False):
"""
Deletes this playlist.
"""
if self.id:
self.connection.post('delete_playlist', playlist_id=self.id,
cascade=cascade)
self.id = None | [
"def",
"delete",
"(",
"self",
",",
"cascade",
"=",
"False",
")",
":",
"if",
"self",
".",
"id",
":",
"self",
".",
"connection",
".",
"post",
"(",
"'delete_playlist'",
",",
"playlist_id",
"=",
"self",
".",
"id",
",",
"cascade",
"=",
"cascade",
")",
"se... | 29.125 | 0.0125 |
def offsets(self):
"""A generator producing a (path, offset) tuple for all tailed files."""
for path, tailedfile in self._tailedfiles.iteritems():
yield path, tailedfile._offset | [
"def",
"offsets",
"(",
"self",
")",
":",
"for",
"path",
",",
"tailedfile",
"in",
"self",
".",
"_tailedfiles",
".",
"iteritems",
"(",
")",
":",
"yield",
"path",
",",
"tailedfile",
".",
"_offset"
] | 48.75 | 0.025253 |
def is_job_done(job_id, conn=None):
"""
is_job_done function checks to if Brain.Jobs Status is 'Done'
:param job_id: <str> id for the job
:param conn: (optional)<connection> to run on
:return: <dict> if job is done <false> if
"""
result = False
get_done = RBJ.get_all(DONE, index=STATUS_... | [
"def",
"is_job_done",
"(",
"job_id",
",",
"conn",
"=",
"None",
")",
":",
"result",
"=",
"False",
"get_done",
"=",
"RBJ",
".",
"get_all",
"(",
"DONE",
",",
"index",
"=",
"STATUS_FIELD",
")",
"for",
"item",
"in",
"get_done",
".",
"filter",
"(",
"{",
"I... | 32.076923 | 0.002331 |
def raise_error(self, message, *params, **key_params):
"""
Raise a parse error.
"""
s = 'Parser error in '
self.xml_node_stack.reverse()
if len(self.xml_node_stack) > 1:
node = self.xml_node_stack[0]
s += '<{0}'.format(node.tag)
... | [
"def",
"raise_error",
"(",
"self",
",",
"message",
",",
"*",
"params",
",",
"*",
"*",
"key_params",
")",
":",
"s",
"=",
"'Parser error in '",
"self",
".",
"xml_node_stack",
".",
"reverse",
"(",
")",
"if",
"len",
"(",
"self",
".",
"xml_node_stack",
")",
... | 31.4 | 0.00309 |
def _subtract_timedelta(self, delta):
"""
Remove timedelta duration from the instance.
:param delta: The timedelta instance
:type delta: pendulum.Duration or datetime.timedelta
:rtype: DateTime
"""
if isinstance(delta, pendulum.Duration):
return self... | [
"def",
"_subtract_timedelta",
"(",
"self",
",",
"delta",
")",
":",
"if",
"isinstance",
"(",
"delta",
",",
"pendulum",
".",
"Duration",
")",
":",
"return",
"self",
".",
"subtract",
"(",
"years",
"=",
"delta",
".",
"years",
",",
"months",
"=",
"delta",
"... | 32 | 0.003793 |
def ensure_dir(dirname):
""" Creates the directory dirname if it does not already exist,
taking into account concurrent 'creation' on the grid.
An exception is thrown if a file (rather than a directory) already
exists. """
try:
# Tries to create the directory
os.makedirs(dirname)
except ... | [
"def",
"ensure_dir",
"(",
"dirname",
")",
":",
"try",
":",
"# Tries to create the directory",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"except",
"OSError",
":",
"# Check that the directory exists",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
... | 33.916667 | 0.014354 |
def remove_stopped_threads (self):
"""Remove the stopped threads from the internal thread list."""
self.threads = [t for t in self.threads if t.is_alive()] | [
"def",
"remove_stopped_threads",
"(",
"self",
")",
":",
"self",
".",
"threads",
"=",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"threads",
"if",
"t",
".",
"is_alive",
"(",
")",
"]"
] | 56.333333 | 0.017544 |
def _get_metadata(self):
""" Get image metadata from filename.md: title, description, meta."""
self.description = ''
self.meta = {}
self.title = ''
descfile = splitext(self.src_path)[0] + '.md'
if isfile(descfile):
meta = read_markdown(descfile)
f... | [
"def",
"_get_metadata",
"(",
"self",
")",
":",
"self",
".",
"description",
"=",
"''",
"self",
".",
"meta",
"=",
"{",
"}",
"self",
".",
"title",
"=",
"''",
"descfile",
"=",
"splitext",
"(",
"self",
".",
"src_path",
")",
"[",
"0",
"]",
"+",
"'.md'",
... | 34.363636 | 0.005155 |
def rename_source_file(self, src, dst):
"""
Rename a file in the source directory.
"""
try:
os.rename(self.source_msgs_dir.joinpath(src), self.source_msgs_dir.joinpath(dst))
except OSError:
pass | [
"def",
"rename_source_file",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"try",
":",
"os",
".",
"rename",
"(",
"self",
".",
"source_msgs_dir",
".",
"joinpath",
"(",
"src",
")",
",",
"self",
".",
"source_msgs_dir",
".",
"joinpath",
"(",
"dst",
")",
... | 31.375 | 0.011628 |
def _add_global_counter(self):
"""Adds a global counter, called once for setup by @property global_step."""
assert self._global_step is None
# Force this into the top-level namescope. Instead of forcing top-level
# here, we could always call this in __init__() and then keep whatever
# namescopes ar... | [
"def",
"_add_global_counter",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_global_step",
"is",
"None",
"# Force this into the top-level namescope. Instead of forcing top-level",
"# here, we could always call this in __init__() and then keep whatever",
"# namescopes are around then.",
... | 46.916667 | 0.006969 |
def lock_instance(cls, instance_or_pk, read=False):
"""Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obt... | [
"def",
"lock_instance",
"(",
"cls",
",",
"instance_or_pk",
",",
"read",
"=",
"False",
")",
":",
"mapper",
"=",
"inspect",
"(",
"cls",
")",
"pk_attrs",
"=",
"[",
"mapper",
".",
"get_property_by_column",
"(",
"c",
")",
".",
"class_attribute",
"for",
"c",
"... | 41.588235 | 0.006916 |
def encode_document(document):
"""Encode a single document."""
tree = etree.Element('document')
etree.SubElement(tree, 'id').text = document.id
encode_infons(tree, document.infons)
for passage in document.passages:
tree.append(encode_passage(passage))
for ann in document.annotatio... | [
"def",
"encode_document",
"(",
"document",
")",
":",
"tree",
"=",
"etree",
".",
"Element",
"(",
"'document'",
")",
"etree",
".",
"SubElement",
"(",
"tree",
",",
"'id'",
")",
".",
"text",
"=",
"document",
".",
"id",
"encode_infons",
"(",
"tree",
",",
"d... | 37.75 | 0.002155 |
def by_id(self, region, encrypted_summoner_id):
"""
Get a summoner by summoner ID.
:param string region: The region to execute this request on
:param string encrypted_summoner_id: Summoner ID
:returns: SummonerDTO: represents a summoner
"""
... | [
"def",
"by_id",
"(",
"self",
",",
"region",
",",
"encrypted_summoner_id",
")",
":",
"url",
",",
"query",
"=",
"SummonerApiV4Urls",
".",
"by_id",
"(",
"region",
"=",
"region",
",",
"encrypted_summoner_id",
"=",
"encrypted_summoner_id",
")",
"return",
"self",
".... | 38.461538 | 0.005859 |
def loads(cls, str):
""" Loads a :class:`~pypot.primitive.move.Move` from a json string. """
d = json.loads(str)
return cls.create(d) | [
"def",
"loads",
"(",
"cls",
",",
"str",
")",
":",
"d",
"=",
"json",
".",
"loads",
"(",
"str",
")",
"return",
"cls",
".",
"create",
"(",
"d",
")"
] | 38.5 | 0.012739 |
def ispcr(args):
"""
%prog ispcr fastafile
Reformat paired primers into isPcr query format, which is three column
format: name, forward, reverse
"""
from jcvi.utils.iter import grouper
p = OptionParser(ispcr.__doc__)
p.add_option("-r", dest="rclip", default=1, type="int",
h... | [
"def",
"ispcr",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"iter",
"import",
"grouper",
"p",
"=",
"OptionParser",
"(",
"ispcr",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-r\"",
",",
"dest",
"=",
"\"rclip\"",
",",
"default",
... | 28.081081 | 0.003721 |
def get(self, label_sn):
"""
Get tags by a label's sn key
:param label_sn: A corresponding label's ``sn`` key.
:type label_sn: str or int
:return: A list of matching tags. An empty list is returned if there are
not any matches
:rtype: list of dict
:... | [
"def",
"get",
"(",
"self",
",",
"label_sn",
")",
":",
"tags",
"=",
"self",
".",
"list",
"(",
")",
"return",
"[",
"tag",
"for",
"tag",
"in",
"tags",
"if",
"str",
"(",
"label_sn",
")",
"in",
"tag",
".",
"get",
"(",
"'args'",
",",
"{",
"}",
")",
... | 28.909091 | 0.004566 |
def createEditor(self, parent, option, index):
"""
Creates a new editor for the given index parented to the inputed widget.
:param parent | <QWidget>
option | <QStyleOption>
index | <QModelIndex>
:return <QWidget... | [
"def",
"createEditor",
"(",
"self",
",",
"parent",
",",
"option",
",",
"index",
")",
":",
"if",
"index",
".",
"column",
"(",
")",
"in",
"self",
".",
"_disabledEditingColumns",
":",
"return",
"None",
"editor",
"=",
"super",
"(",
"XTreeWidgetDelegate",
",",
... | 36.714286 | 0.010114 |
def check_stripe_api_version(app_configs=None, **kwargs):
"""Check the user has configured API version correctly."""
from . import settings as djstripe_settings
messages = []
default_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION
version = djstripe_settings.get_stripe_api_version()
if not validate_strip... | [
"def",
"check_stripe_api_version",
"(",
"app_configs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"settings",
"as",
"djstripe_settings",
"messages",
"=",
"[",
"]",
"default_version",
"=",
"djstripe_settings",
".",
"DEFAULT_STRIPE_API_VE... | 39.695652 | 0.02139 |
def transform(self, X):
"""
Returns the transformed data points from the manifold embedding.
Parameters
----------
X : array-like of shape (n, m)
A matrix or data frame with n instances and m features
Returns
-------
Xprime : array-like of sh... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"try",
":",
"return",
"self",
".",
"manifold",
".",
"transform",
"(",
"X",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"AttributeError",
"(",
"str",
"(",
"e",
")",
"+",
"\" try using fi... | 31.388889 | 0.003436 |
def db_snapshot_append(cls, cur, block_id, consensus_hash, ops_hash, timestamp):
"""
Append hash info for the last block processed, and the time at which it was done.
Meant to be executed as part of a transaction.
Return True on success
Raise an exception on invalid block number... | [
"def",
"db_snapshot_append",
"(",
"cls",
",",
"cur",
",",
"block_id",
",",
"consensus_hash",
",",
"ops_hash",
",",
"timestamp",
")",
":",
"query",
"=",
"'INSERT INTO snapshots (block_id,consensus_hash,ops_hash,timestamp) VALUES (?,?,?,?);'",
"args",
"=",
"(",
"block_id",
... | 39.466667 | 0.016502 |
def show(self, item, variant):
"""
Show a variant.
:param item: Item object or id
:param variant: Variant object or id
:return:
"""
url = self._build_url(self.endpoint.show(item, variant))
return self._get(url) | [
"def",
"show",
"(",
"self",
",",
"item",
",",
"variant",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"self",
".",
"endpoint",
".",
"show",
"(",
"item",
",",
"variant",
")",
")",
"return",
"self",
".",
"_get",
"(",
"url",
")"
] | 26.6 | 0.007273 |
def _operation_status(self):
"""Returns the status of this operation.
Raises:
ValueError: if the operation status cannot be determined.
Returns:
A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE).
"""
if not google_v2_operations.is_done(self._op):
return 'RUNNING'
... | [
"def",
"_operation_status",
"(",
"self",
")",
":",
"if",
"not",
"google_v2_operations",
".",
"is_done",
"(",
"self",
".",
"_op",
")",
":",
"return",
"'RUNNING'",
"if",
"google_v2_operations",
".",
"is_success",
"(",
"self",
".",
"_op",
")",
":",
"return",
... | 31.35 | 0.00774 |
def make_inference_summary_table(workflow, inference_file, output_dir,
variable_args=None, name="inference_table",
analysis_seg=None, tags=None):
""" Sets up the corner plot of the posteriors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflo... | [
"def",
"make_inference_summary_table",
"(",
"workflow",
",",
"inference_file",
",",
"output_dir",
",",
"variable_args",
"=",
"None",
",",
"name",
"=",
"\"inference_table\"",
",",
"analysis_seg",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default values",
... | 34.372549 | 0.002773 |
def populate_instances(self, metamodel):
'''
Populate a *metamodel* with instances previously encountered from
input.
'''
for stmt in self.statements:
if not isinstance(stmt, CreateInstanceStmt):
continue
if stmt.names:
... | [
"def",
"populate_instances",
"(",
"self",
",",
"metamodel",
")",
":",
"for",
"stmt",
"in",
"self",
".",
"statements",
":",
"if",
"not",
"isinstance",
"(",
"stmt",
",",
"CreateInstanceStmt",
")",
":",
"continue",
"if",
"stmt",
".",
"names",
":",
"fn",
"="... | 33.2 | 0.007813 |
def upload_to_s3(file_path, config):
""" Upload html file to S3
"""
logging.info("Uploading file to S3 bucket: %s", config['s3_bucket_name'])
s3 = boto3.resource('s3')
s3_filename = config['s3_bucket_path'] + config['rendered_filename']
s3.Bucket(config['s3_bucket_name']).upload_file(
fi... | [
"def",
"upload_to_s3",
"(",
"file_path",
",",
"config",
")",
":",
"logging",
".",
"info",
"(",
"\"Uploading file to S3 bucket: %s\"",
",",
"config",
"[",
"'s3_bucket_name'",
"]",
")",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
"s3_filename",
"=",
... | 45.333333 | 0.002404 |
def custom_server_error(request, template_name='500.html', admin_template_name='500A.html'):
"""
500 error handler. Displays a full trackback for superusers and the first line of the
traceback for staff members.
Templates: `500.html` or `500A.html` (admin)
Context: trace
Holds the traceback... | [
"def",
"custom_server_error",
"(",
"request",
",",
"template_name",
"=",
"'500.html'",
",",
"admin_template_name",
"=",
"'500A.html'",
")",
":",
"trace",
"=",
"None",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"(",
"request",
".",
... | 41.423077 | 0.009074 |
def __file_hash_and_stat(self, load):
'''
Common code for hashing and stating files
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'path' not in load or 'saltenv' not in load:
return '', None
if not i... | [
"def",
"__file_hash_and_stat",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"'path'",
"not",
"in",
"load",
"or",
"'saltenv'",
"not",
"in",
"... | 35.954545 | 0.003695 |
def get_range_start_coord(self,rng):
"""
.. warning:: not implemented
"""
sys.stderr.write("error unimplemented get_range_start_coord\n")
sys.exit()
if rng.chr not in self._chrs: return None
for l in [self._lines[x-1] for x in self._chrs[rng.chr]]:
####
y = l['rng']
c = y.c... | [
"def",
"get_range_start_coord",
"(",
"self",
",",
"rng",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error unimplemented get_range_start_coord\\n\"",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"rng",
".",
"chr",
"not",
"in",
"self",
".",
"_chrs",
"... | 28.125 | 0.025806 |
def request_token(self):
"""Create an OAuth request token for a valid client request.
Defaults to /request_token. Invoked by client applications.
"""
client_key = request.oauth.client_key
realm = request.oauth.realm
# TODO: fallback on default realm?
callback = r... | [
"def",
"request_token",
"(",
"self",
")",
":",
"client_key",
"=",
"request",
".",
"oauth",
".",
"client_key",
"realm",
"=",
"request",
".",
"oauth",
".",
"realm",
"# TODO: fallback on default realm?",
"callback",
"=",
"request",
".",
"oauth",
".",
"callback_uri"... | 48.5625 | 0.003788 |
def get_command(self, version=2):
"""Return the SSH protocol specific command to connect."""
try:
options = _C['options']
options_str = " -o ".join(options)
if options_str:
options_str = "-o " + options_str + " "
except KeyError:
op... | [
"def",
"get_command",
"(",
"self",
",",
"version",
"=",
"2",
")",
":",
"try",
":",
"options",
"=",
"_C",
"[",
"'options'",
"]",
"options_str",
"=",
"\" -o \"",
".",
"join",
"(",
"options",
")",
"if",
"options_str",
":",
"options_str",
"=",
"\"-o \"",
"... | 36.857143 | 0.005038 |
def write_input_files(self, fh):
"""
Write as a comment into the DAG file the list of input files
for this DAG node.
@param fh: descriptor of open DAG file.
"""
for f in self.__input_files:
print >>fh, "## Job %s requires input file %s" % (self.__name, f) | [
"def",
"write_input_files",
"(",
"self",
",",
"fh",
")",
":",
"for",
"f",
"in",
"self",
".",
"__input_files",
":",
"print",
">>",
"fh",
",",
"\"## Job %s requires input file %s\"",
"%",
"(",
"self",
".",
"__name",
",",
"f",
")"
] | 31.111111 | 0.003472 |
def command(*args, **kwargs):
"""Decorator to define a command.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html\
#argumentparser-objects>`_
object constructor.
"""
def decorator(f):
if 'description' not in kwargs:
... | [
"def",
"command",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"'description'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"f",
".",
"__doc__",
"if",
"'parents'",
"in",
... | 34.566667 | 0.000938 |
def one(src, default=None, key=None):
"""Along the same lines as builtins, :func:`all` and :func:`any`, and
similar to :func:`first`, ``one()`` returns the single object in
the given iterable *src* that evaluates to ``True``, as determined
by callable *key*. If unset, *key* defaults to :class:`bool`. If... | [
"def",
"one",
"(",
"src",
",",
"default",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"ones",
"=",
"list",
"(",
"itertools",
".",
"islice",
"(",
"filter",
"(",
"key",
",",
"src",
")",
",",
"2",
")",
")",
"return",
"ones",
"[",
"0",
"]",
"... | 35.575758 | 0.000829 |
def temporarily_disabled(self):
"""
Temporarily disable the cache (useful for testing)
"""
old_setting = self.options.enabled
self.disable(clear_cache=False)
try:
yield
finally:
self.options.enabled = old_setting | [
"def",
"temporarily_disabled",
"(",
"self",
")",
":",
"old_setting",
"=",
"self",
".",
"options",
".",
"enabled",
"self",
".",
"disable",
"(",
"clear_cache",
"=",
"False",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"options",
".",
"enabled",
... | 28.3 | 0.006849 |
def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
... | [
"def",
"predict_expectation",
"(",
"self",
",",
"X",
")",
":",
"index",
"=",
"_get_index",
"(",
"X",
")",
"t",
"=",
"self",
".",
"_index",
"return",
"pd",
".",
"DataFrame",
"(",
"trapz",
"(",
"self",
".",
"predict_survival_function",
"(",
"X",
")",
"["... | 35.6875 | 0.005119 |
def p_iteration_statement_6(self, p):
"""
iteration_statement \
: FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement
"""
vardecl = self.asttypes.VarDeclNoIn(
identifier=p[4], initializer=p[5])
vardecl.setpos(p, 3)
p[0] = self.asttype... | [
"def",
"p_iteration_statement_6",
"(",
"self",
",",
"p",
")",
":",
"vardecl",
"=",
"self",
".",
"asttypes",
".",
"VarDeclNoIn",
"(",
"identifier",
"=",
"p",
"[",
"4",
"]",
",",
"initializer",
"=",
"p",
"[",
"5",
"]",
")",
"vardecl",
".",
"setpos",
"(... | 38.6 | 0.005063 |
def get_model(with_pipeline=False):
"""Get a multi-layer perceptron model.
Optionally, put it in a pipeline that scales the data.
"""
model = NeuralNetClassifier(MLPClassifier)
if with_pipeline:
model = Pipeline([
('scale', FeatureUnion([
('minmax', MinMaxScaler... | [
"def",
"get_model",
"(",
"with_pipeline",
"=",
"False",
")",
":",
"model",
"=",
"NeuralNetClassifier",
"(",
"MLPClassifier",
")",
"if",
"with_pipeline",
":",
"model",
"=",
"Pipeline",
"(",
"[",
"(",
"'scale'",
",",
"FeatureUnion",
"(",
"[",
"(",
"'minmax'",
... | 29.705882 | 0.001919 |
def check_policies(self, account, account_policies, aws_policies):
"""Iterate through the policies of a specific account and create or update the policy if its missing or
does not match the policy documents from Git. Returns a dict of all the policies added to the account
(does not include updat... | [
"def",
"check_policies",
"(",
"self",
",",
"account",
",",
"account_policies",
",",
"aws_policies",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Fetching policies for {}'",
".",
"format",
"(",
"account",
".",
"account_name",
")",
")",
"sess",
"=",
"get... | 44.534483 | 0.004545 |
def proximal_huber(space, gamma):
"""Proximal factory of the Huber norm.
Parameters
----------
space : `TensorSpace`
The domain of the functional
gamma : float
The smoothing parameter of the Huber norm functional.
Returns
-------
prox_factory : function
Factory ... | [
"def",
"proximal_huber",
"(",
"space",
",",
"gamma",
")",
":",
"gamma",
"=",
"float",
"(",
"gamma",
")",
"class",
"ProximalHuber",
"(",
"Operator",
")",
":",
"\"\"\"Proximal operator of Huber norm.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"sigma",
")",
":"... | 27.983333 | 0.000575 |
def attribute_result(cls, sprites):
"""Return mapping of attributes to if they were initialized or not."""
retval = dict((x, True) for x in cls.ATTRIBUTES)
for properties in sprites.values():
for attribute, state in properties.items():
retval[attribute] &= state != cl... | [
"def",
"attribute_result",
"(",
"cls",
",",
"sprites",
")",
":",
"retval",
"=",
"dict",
"(",
"(",
"x",
",",
"True",
")",
"for",
"x",
"in",
"cls",
".",
"ATTRIBUTES",
")",
"for",
"properties",
"in",
"sprites",
".",
"values",
"(",
")",
":",
"for",
"at... | 50.285714 | 0.005587 |
def predicate(self, *args, **kwargs):
"""the default predicate for Support Classifiers invokes any derivied
_predicate function, trapping any exceptions raised in the process. We
are obligated to catch these exceptions to give subsequent rules the
opportunity to act. An error during th... | [
"def",
"predicate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"_predicate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
",",
"x",
":",
"self",
".",
"config",
".... | 43.823529 | 0.002628 |
def _fillna(expr, value):
"""
Fill null with value.
:param expr: sequence or scalar
:param value: value to fill into
:return: sequence or scalar
"""
if isinstance(expr, SequenceExpr):
return FillNa(_input=expr, _fill_value=value, _data_type=expr.dtype)
elif isinstance(expr, Sca... | [
"def",
"_fillna",
"(",
"expr",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"SequenceExpr",
")",
":",
"return",
"FillNa",
"(",
"_input",
"=",
"expr",
",",
"_fill_value",
"=",
"value",
",",
"_data_type",
"=",
"expr",
".",
"dtype",
")",
... | 30.076923 | 0.002481 |
def search_record(datas, keyword):
"""Search target JSON -> dictionary
Arguments:
datas: dictionary of record datas
keyword: search keyword (default is null)
Key target is "name" or "content" or "type". default null.
Either key and type, or on the other hand.
When keyword has inc... | [
"def",
"search_record",
"(",
"datas",
",",
"keyword",
")",
":",
"key_name",
",",
"key_type",
",",
"key_content",
"=",
"False",
",",
"False",
",",
"False",
"if",
"keyword",
".",
"find",
"(",
"','",
")",
">",
"-",
"1",
":",
"if",
"len",
"(",
"keyword",... | 29.977273 | 0.000734 |
def _build_url_rewriter(cls, session: AppSession):
'''Build URL rewriter if needed.'''
if session.args.escaped_fragment or session.args.strip_session_id:
return session.factory.new(
'URLRewriter',
hash_fragment=session.args.escaped_fragment,
se... | [
"def",
"_build_url_rewriter",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"session",
".",
"args",
".",
"escaped_fragment",
"or",
"session",
".",
"args",
".",
"strip_session_id",
":",
"return",
"session",
".",
"factory",
".",
"new",
"(",
... | 45.625 | 0.005376 |
def cleanup(self, release):
"""Perform cleanup actions on the releasefile of the given release
This is inteded to be used in a action unit.
:param release: the release with the releasefile and cleanup actions
:type release: :class:`Release`
:returns: the action status of the cl... | [
"def",
"cleanup",
"(",
"self",
",",
"release",
")",
":",
"log",
".",
"info",
"(",
"\"Performing cleanup.\"",
")",
"return",
"execute_actioncollection",
"(",
"release",
".",
"_releasefile",
",",
"actioncollection",
"=",
"release",
".",
"_cleanup",
",",
"confirm",... | 41.846154 | 0.005396 |
def precision_recall_by_user(observed_user_items,
recommendations,
cutoffs=[10]):
"""
Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the... | [
"def",
"precision_recall_by_user",
"(",
"observed_user_items",
",",
"recommendations",
",",
"cutoffs",
"=",
"[",
"10",
"]",
")",
":",
"assert",
"type",
"(",
"observed_user_items",
")",
"==",
"_SFrame",
"assert",
"type",
"(",
"recommendations",
")",
"==",
"_SFram... | 39.958763 | 0.003021 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.