text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def print_warning_results(results, level=0):
"""Print warning messages found during validation.
"""
marker = _YELLOW + "[!] "
for warning in results.warnings:
print_level(logger.warning, marker + "Warning: %s", level, warning) | [
"def",
"print_warning_results",
"(",
"results",
",",
"level",
"=",
"0",
")",
":",
"marker",
"=",
"_YELLOW",
"+",
"\"[!] \"",
"for",
"warning",
"in",
"results",
".",
"warnings",
":",
"print_level",
"(",
"logger",
".",
"warning",
",",
"marker",
"+",
"\"Warni... | 35 | 13.428571 |
def resolve_domains(domains, disable_zone=False):
"""
Resolves the list of domains and returns the ips.
"""
dnsresolver = dns.resolver.Resolver()
ips = []
for domain in domains:
print_notification("Resolving {}".format(domain))
try:
result = dnsresolver.query(do... | [
"def",
"resolve_domains",
"(",
"domains",
",",
"disable_zone",
"=",
"False",
")",
":",
"dnsresolver",
"=",
"dns",
".",
"resolver",
".",
"Resolver",
"(",
")",
"ips",
"=",
"[",
"]",
"for",
"domain",
"in",
"domains",
":",
"print_notification",
"(",
"\"Resolvi... | 30.473684 | 15 |
def validate(self, model, checks=[]):
"""Use a defined schema to validate the medium table format."""
custom = [
check_partial(reaction_id_check,
frozenset(r.id for r in model.reactions))
]
super(Medium, self).validate(model=model, checks=checks + cu... | [
"def",
"validate",
"(",
"self",
",",
"model",
",",
"checks",
"=",
"[",
"]",
")",
":",
"custom",
"=",
"[",
"check_partial",
"(",
"reaction_id_check",
",",
"frozenset",
"(",
"r",
".",
"id",
"for",
"r",
"in",
"model",
".",
"reactions",
")",
")",
"]",
... | 45.571429 | 17.142857 |
def _set_address(self, v, load=False):
"""
Setter method for address, mapped from YANG variable /interface/management/ip/address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_address is considered as a private
method. Backends looking to populate this v... | [
"def",
"_set_address",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 69.36 | 34 |
def construct_request_uri(local_dir, base_path, **kwargs):
"""
Constructs a special redirect_uri to be used when communicating with
one OP. Each OP should get their own redirect_uris.
:param local_dir: Local directory in which to place the file
:param base_path: Base URL to start with
:para... | [
"def",
"construct_request_uri",
"(",
"local_dir",
",",
"base_path",
",",
"*",
"*",
"kwargs",
")",
":",
"_filedir",
"=",
"local_dir",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"_filedir",
")",
":",
"os",
".",
"makedirs",
"(",
"_filedir",
")",
"... | 35.142857 | 12 |
def rmarkdown_draft(filename, template, package):
"""
create a draft rmarkdown file from an installed template
"""
if file_exists(filename):
return filename
draft_template = Template(
'rmarkdown::draft("$filename", template="$template", package="$package", edit=FALSE)'
)
draf... | [
"def",
"rmarkdown_draft",
"(",
"filename",
",",
"template",
",",
"package",
")",
":",
"if",
"file_exists",
"(",
"filename",
")",
":",
"return",
"filename",
"draft_template",
"=",
"Template",
"(",
"'rmarkdown::draft(\"$filename\", template=\"$template\", package=\"$package... | 43.470588 | 21.823529 |
def add_catalogue(self, catalogue, overlay=False):
'''
:param catalogue:
Earthquake catalogue as instance of
:class:`openquake.hmtk.seismicity.catalogue.Catalogue`
:param dict config:
Configuration parameters of the algorithm, containing the
follo... | [
"def",
"add_catalogue",
"(",
"self",
",",
"catalogue",
",",
"overlay",
"=",
"False",
")",
":",
"# Magnitudes bins and minimum marrker size",
"# min_mag = np.min(catalogue.data['magnitude'])",
"# max_mag = np.max(catalogue.data['magnitude'])",
"con_min",
"=",
"np",
".",
"where",... | 46 | 21.220339 |
def pull_request(self, number):
"""Get the pull request indicated by ``number``.
:param int number: (required), number of the pull request.
:returns: :class:`PullRequest <github3.pulls.PullRequest>`
"""
json = None
if int(number) > 0:
url = self._build_url('p... | [
"def",
"pull_request",
"(",
"self",
",",
"number",
")",
":",
"json",
"=",
"None",
"if",
"int",
"(",
"number",
")",
">",
"0",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'pulls'",
",",
"str",
"(",
"number",
")",
",",
"base_url",
"=",
"self",
... | 41.545455 | 17.818182 |
def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(p... | [
"def",
"target",
"(",
"self",
",",
"project_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"if",
"project_module",
"not",
"in",
"self",
".",
"module2target",
":",
"self",
".",
"module2target",
"[",
"project_module",
"... | 52.333333 | 18.444444 |
def add_contributor(self, project_id, name, email, language_code):
"""
Adds a contributor to a project language
"""
self._run(
url_path="contributors/add",
id=project_id,
name=name,
email=email,
language=language_code
)
... | [
"def",
"add_contributor",
"(",
"self",
",",
"project_id",
",",
"name",
",",
"email",
",",
"language_code",
")",
":",
"self",
".",
"_run",
"(",
"url_path",
"=",
"\"contributors/add\"",
",",
"id",
"=",
"project_id",
",",
"name",
"=",
"name",
",",
"email",
... | 27.333333 | 13.5 |
def do_diff(self, subcmd, opts, *args):
"""Display the differences between two paths.
usage:
1. diff [-r N[:M]] [TARGET[@REV]...]
2. diff [-r N[:M]] --old=OLD-TGT[@OLDREV] [--new=NEW-TGT[@NEWREV]] \
[PATH...]
3. diff OLD-URL[@OLDREV] NEW-URL[@NEWR... | [
"def",
"do_diff",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"*",
"args",
")",
":",
"print",
"\"'svn %s' opts: %s\"",
"%",
"(",
"subcmd",
",",
"opts",
")",
"print",
"\"'svn %s' args: %s\"",
"%",
"(",
"subcmd",
",",
"args",
")"
] | 48.419355 | 27.774194 |
def assemble(self,roboset=None,color=None,format=None,bgset=None,sizex=300,sizey=300):
"""
Build our Robot!
Returns the robot image itself.
"""
# Allow users to manually specify a robot 'set' that they like.
# Ensure that this is one of the allowed choices, or allow all
... | [
"def",
"assemble",
"(",
"self",
",",
"roboset",
"=",
"None",
",",
"color",
"=",
"None",
",",
"format",
"=",
"None",
",",
"bgset",
"=",
"None",
",",
"sizex",
"=",
"300",
",",
"sizey",
"=",
"300",
")",
":",
"# Allow users to manually specify a robot 'set' th... | 41.261905 | 24.785714 |
def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):
"""Returns a (dense) column of a Tensor or SparseTensor.
Args:
sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.
col_index: scalar, `int` `Tensor` representing the index of the desired
column.
Returns:
... | [
"def",
"_sparse_or_dense_matmul_onehot",
"(",
"sparse_or_dense_matrix",
",",
"col_index",
")",
":",
"if",
"isinstance",
"(",
"sparse_or_dense_matrix",
",",
"(",
"tf",
".",
"SparseTensor",
",",
"tf",
".",
"compat",
".",
"v1",
".",
"SparseTensorValue",
")",
")",
"... | 47.375 | 24.03125 |
def uifile(self):
"""
Returns the uifile for this scaffold.
:return <str>
"""
output = ''
# build from a zip file
if zipfile.is_zipfile(self.source()):
zfile = zipfile.ZipFile(self.source(), 'r')
if 'properties.ui' in zfile.na... | [
"def",
"uifile",
"(",
"self",
")",
":",
"output",
"=",
"''",
"# build from a zip file",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"self",
".",
"source",
"(",
")",
")",
":",
"zfile",
"=",
"zipfile",
".",
"ZipFile",
"(",
"self",
".",
"source",
"(",
")",
... | 30.214286 | 17.285714 |
def assert_equal(self, v1, v2, **kwargs):#, desc=None, screenshot=False, safe=False):
""" Check v1 is equals v2, and take screenshot if not equals
Args:
- desc (str): some description
- safe (bool): will omit AssertionError if set to True
- screenshot: can be type <No... | [
"def",
"assert_equal",
"(",
"self",
",",
"v1",
",",
"v2",
",",
"*",
"*",
"kwargs",
")",
":",
"#, desc=None, screenshot=False, safe=False):",
"is_success",
"=",
"v1",
"==",
"v2",
"if",
"is_success",
":",
"message",
"=",
"\"assert equal success, %s == %s\"",
"%",
... | 38.823529 | 16.647059 |
def forward(self, data_batch, is_train=None):
"""Forward computation.
Parameters
----------
data_batch : DataBatch
is_train : bool
Defaults to ``None``, in which case `is_train` is take as ``self.for_training``.
"""
assert self.binded and self.params_... | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
")",
":",
"assert",
"self",
".",
"binded",
"and",
"self",
".",
"params_initialized",
"self",
".",
"switch_bucket",
"(",
"data_batch",
".",
"bucket_key",
",",
"data_batch",
".",
... | 39.384615 | 19.384615 |
def pin_variant(institute_id, case_name, variant_id):
"""Pin and unpin variants to/from the list of suspects."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
variant_obj = store.variant(variant_id)
user_obj = store.user(current_user.email)
link = url_for('variants.var... | [
"def",
"pin_variant",
"(",
"institute_id",
",",
"case_name",
",",
"variant_id",
")",
":",
"institute_obj",
",",
"case_obj",
"=",
"institute_and_case",
"(",
"store",
",",
"institute_id",
",",
"case_name",
")",
"variant_obj",
"=",
"store",
".",
"variant",
"(",
"... | 58.166667 | 16.5 |
def add_filter(self, filter_or_string, *args, **kwargs):
"""
Appends a filter.
"""
self.filters.append(build_filter(filter_or_string, *args, **kwargs))
return self | [
"def",
"add_filter",
"(",
"self",
",",
"filter_or_string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"filters",
".",
"append",
"(",
"build_filter",
"(",
"filter_or_string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
... | 28.285714 | 18.285714 |
def hbas(self):
"""
:class:`~zhmcclient.HbaManager`: Access to the :term:`HBAs <HBA>` in
this Partition.
If the "dpm-storage-management" feature is enabled, this property is
`None`.
"""
# We do here some lazy loading.
if not self._hbas:
try:
... | [
"def",
"hbas",
"(",
"self",
")",
":",
"# We do here some lazy loading.",
"if",
"not",
"self",
".",
"_hbas",
":",
"try",
":",
"dpm_sm",
"=",
"self",
".",
"feature_enabled",
"(",
"'dpm-storage-management'",
")",
"except",
"ValueError",
":",
"dpm_sm",
"=",
"False... | 31.470588 | 17.823529 |
def add_view(
self,
baseview,
name,
href="",
icon="",
label="",
category="",
category_icon="",
category_label="",
):
"""
Add your views associated with menus using this method.
:param baseview:
A BaseView ty... | [
"def",
"add_view",
"(",
"self",
",",
"baseview",
",",
"name",
",",
"href",
"=",
"\"\"",
",",
"icon",
"=",
"\"\"",
",",
"label",
"=",
"\"\"",
",",
"category",
"=",
"\"\"",
",",
"category_icon",
"=",
"\"\"",
",",
"category_label",
"=",
"\"\"",
",",
")"... | 34.858824 | 16.858824 |
def Hsub(T=298.15, P=101325, MW=None, AvailableMethods=False, Method=None, CASRN=''): # pragma: no cover
'''This function handles the calculation of a chemical's enthalpy of sublimation.
Generally this, is used by the chemical class, as all parameters are passed.
This API is considered experimental, and ... | [
"def",
"Hsub",
"(",
"T",
"=",
"298.15",
",",
"P",
"=",
"101325",
",",
"MW",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
",",
"CASRN",
"=",
"''",
")",
":",
"# pragma: no cover",
"def",
"list_methods",
"(",
")",
":",... | 39.5 | 21.055556 |
def prev_position(self, pos):
"""returns the previous position in depth-first order"""
candidate = None
if pos is not None:
prevsib = self.prev_sibling_position(pos) # is None if first
if prevsib is not None:
candidate = self.last_decendant(prevsib)
... | [
"def",
"prev_position",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"prevsib",
"=",
"self",
".",
"prev_sibling_position",
"(",
"pos",
")",
"# is None if first",
"if",
"prevsib",
"is",
"not",
"None",
... | 39.583333 | 12.25 |
def discover() -> List[Tuple[str, str]]:
""" Scan for connected modules and instantiate handler classes
"""
if IS_ROBOT and os.path.isdir('/dev/modules'):
devices = os.listdir('/dev/modules')
else:
devices = []
discovered_modules = []
module_port_regex = re.compile('|'.join(MOD... | [
"def",
"discover",
"(",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"if",
"IS_ROBOT",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"'/dev/modules'",
")",
":",
"devices",
"=",
"os",
".",
"listdir",
"(",
"'/dev/modules'",
... | 35.5 | 16.625 |
def data_mod(self, *args, **kwargs):
"""
Register a function to modify data of member Instruments.
The function is not partially applied to modify member data.
When the Constellation receives a function call to register a function for data modification,
it passes the call to ea... | [
"def",
"data_mod",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"instrument",
"in",
"self",
".",
"instruments",
":",
"instrument",
".",
"custom",
".",
"add",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 35.265306 | 23.877551 |
def get_reference_section_beginning(fulltext):
"""Get start of reference section."""
sect_start = {
'start_line': None,
'end_line': None,
'title_string': None,
'marker_pattern': None,
'marker': None,
'how_found_start': None,
}
# Find start of refs section... | [
"def",
"get_reference_section_beginning",
"(",
"fulltext",
")",
":",
"sect_start",
"=",
"{",
"'start_line'",
":",
"None",
",",
"'end_line'",
":",
"None",
",",
"'title_string'",
":",
"None",
",",
"'marker_pattern'",
":",
"None",
",",
"'marker'",
":",
"None",
",... | 40.116279 | 17.953488 |
def add_listener(self, listener):
"""Add the given listener to the wrapped client.
The listener will be wrapped, so that it will be called in the reactor
thread. This way, it can safely use Twisted APIs.
"""
internal_listener = partial(self._call_in_reactor_thread, listener)
... | [
"def",
"add_listener",
"(",
"self",
",",
"listener",
")",
":",
"internal_listener",
"=",
"partial",
"(",
"self",
".",
"_call_in_reactor_thread",
",",
"listener",
")",
"self",
".",
"_internal_listeners",
"[",
"listener",
"]",
"=",
"internal_listener",
"return",
"... | 47.888889 | 19.777778 |
def create_resource_object(self, type, id):
"""Create a resource object of type for the integer id. type
should be one of the following strings:
resource
drawable
window
pixmap
fontable
font
gc
colormap
cursor
This functio... | [
"def",
"create_resource_object",
"(",
"self",
",",
"type",
",",
"id",
")",
":",
"return",
"self",
".",
"display",
".",
"resource_classes",
"[",
"type",
"]",
"(",
"self",
".",
"display",
",",
"id",
")"
] | 32.428571 | 22.380952 |
def create_roc_plots(pwmfile, fgfa, background, outdir):
"""Make ROC plots for all motifs."""
motifs = read_motifs(pwmfile, fmt="pwm", as_dict=True)
ncpus = int(MotifConfig().get_default_params()['ncpus'])
pool = Pool(processes=ncpus)
jobs = {}
for bg,fname in background.items():
for m_i... | [
"def",
"create_roc_plots",
"(",
"pwmfile",
",",
"fgfa",
",",
"background",
",",
"outdir",
")",
":",
"motifs",
"=",
"read_motifs",
"(",
"pwmfile",
",",
"fmt",
"=",
"\"pwm\"",
",",
"as_dict",
"=",
"True",
")",
"ncpus",
"=",
"int",
"(",
"MotifConfig",
"(",
... | 38.827586 | 14.551724 |
def create(self, mention, max_message_length):
"""
Create a message
:param mention: JSON object containing mention details from Twitter (or an empty dict {})
:param max_message_length: Maximum allowable length for created message
:return: A random message created using a Markov c... | [
"def",
"create",
"(",
"self",
",",
"mention",
",",
"max_message_length",
")",
":",
"message",
"=",
"[",
"]",
"def",
"message_len",
"(",
")",
":",
"return",
"sum",
"(",
"[",
"len",
"(",
"w",
")",
"+",
"1",
"for",
"w",
"in",
"message",
"]",
")",
"w... | 37.8125 | 23.0625 |
def v_type_extension(ctx, stmt):
"""verify that the extension matches the extension definition"""
(modulename, identifier) = stmt.keyword
revision = stmt.i_extension_revision
module = modulename_to_module(stmt.i_module, modulename, revision)
if module is None:
return
if identifier not in... | [
"def",
"v_type_extension",
"(",
"ctx",
",",
"stmt",
")",
":",
"(",
"modulename",
",",
"identifier",
")",
"=",
"stmt",
".",
"keyword",
"revision",
"=",
"stmt",
".",
"i_extension_revision",
"module",
"=",
"modulename_to_module",
"(",
"stmt",
".",
"i_module",
"... | 44.965517 | 17.724138 |
def provide_session(self, start_new=False):
""" Makes sure that session is still valid and provides session info
:param start_new: If `True` it will always create a new session. Otherwise it will create a new
session only if no session exists or the previous session timed out.
:type... | [
"def",
"provide_session",
"(",
"self",
",",
"start_new",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_global",
":",
"self",
".",
"_session_info",
"=",
"self",
".",
"_global_session_info",
"self",
".",
"_session_start",
"=",
"self",
".",
"_global_session_star... | 41.888889 | 21.277778 |
def main():
"""
This is a Toil pipeline for the UNC best practice RNA-Seq analysis.
RNA-seq fastqs are combined, aligned, sorted, filtered, and quantified.
Please read the README.md located in the same directory.
"""
# Define Parser object and add to toil
parser = build_parser()
Job.Run... | [
"def",
"main",
"(",
")",
":",
"# Define Parser object and add to toil",
"parser",
"=",
"build_parser",
"(",
")",
"Job",
".",
"Runner",
".",
"addToilOptions",
"(",
"parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# Store inputs from argparse",
... | 37.441176 | 13.147059 |
def _append_distances(self, v, distance, candidates):
""" Apply distance implementation if specified """
if distance:
# Normalize vector (stored vectors are normalized)
nv = unitvec(v)
candidates = [(x[0], x[1], self.distance.distance(x[0], nv)) for x
... | [
"def",
"_append_distances",
"(",
"self",
",",
"v",
",",
"distance",
",",
"candidates",
")",
":",
"if",
"distance",
":",
"# Normalize vector (stored vectors are normalized)",
"nv",
"=",
"unitvec",
"(",
"v",
")",
"candidates",
"=",
"[",
"(",
"x",
"[",
"0",
"]"... | 40.555556 | 18.111111 |
def to_dict(self):
"""Return a dictionary representation of the error.
:return: A dict with the keys:
- attr: Attribute which contains the error, or "<root>" if it refers to the schema root.
- errors: A list of dictionary representations of the errors.
"""
def ex... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"def",
"exception_to_dict",
"(",
"e",
")",
":",
"try",
":",
"return",
"e",
".",
"to_dict",
"(",
")",
"except",
"AttributeError",
":",
"return",
"{",
"\"type\"",
":",
"e",
".",
"__class__",
".",
"__name__",
",",
... | 34.125 | 19.125 |
def _ReadLabels(self, artifact_definition_values, artifact_definition, name):
"""Reads the optional artifact definition labels.
Args:
artifact_definition_values (dict[str, object]): artifact definition
values.
artifact_definition (ArtifactDefinition): an artifact definition.
name (s... | [
"def",
"_ReadLabels",
"(",
"self",
",",
"artifact_definition_values",
",",
"artifact_definition",
",",
"name",
")",
":",
"labels",
"=",
"artifact_definition_values",
".",
"get",
"(",
"'labels'",
",",
"[",
"]",
")",
"undefined_labels",
"=",
"set",
"(",
"labels",
... | 35.809524 | 22.380952 |
def sms(self, message, to=None, from_=None, action=None, method=None,
status_callback=None, **kwargs):
"""
Create a <Sms> element
:param message: Message body
:param to: Number to send message to
:param from: Number to send message from
:param action: Action ... | [
"def",
"sms",
"(",
"self",
",",
"message",
",",
"to",
"=",
"None",
",",
"from_",
"=",
"None",
",",
"action",
"=",
"None",
",",
"method",
"=",
"None",
",",
"status_callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"... | 29.541667 | 13.375 |
def coordinate_reproject(x, y, s_crs, t_crs):
"""
reproject a coordinate from one CRS to another
Parameters
----------
x: int or float
the X coordinate component
y: int or float
the Y coordinate component
s_crs: int, str or :osgeo:class:`osr.SpatialReference`
the... | [
"def",
"coordinate_reproject",
"(",
"x",
",",
"y",
",",
"s_crs",
",",
"t_crs",
")",
":",
"source",
"=",
"crsConvert",
"(",
"s_crs",
",",
"'osr'",
")",
"target",
"=",
"crsConvert",
"(",
"t_crs",
",",
"'osr'",
")",
"transform",
"=",
"osr",
".",
"Coordina... | 30.625 | 19.208333 |
def check_lazy_load_terreinobject(f):
'''
Decorator function to lazy load a :class:`Terreinobject`.
'''
def wrapper(*args):
terreinobject = args[0]
if (
terreinobject._centroid is None or
terreinobject._bounding_box is None or
terreinobject._metadata i... | [
"def",
"check_lazy_load_terreinobject",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"terreinobject",
"=",
"args",
"[",
"0",
"]",
"if",
"(",
"terreinobject",
".",
"_centroid",
"is",
"None",
"or",
"terreinobject",
".",
"_bounding_box",
... | 37.631579 | 17.842105 |
def feature_burstness(corpus, featureset_name, feature, k=5, normalize=True,
s=1.1, gamma=1., **slice_kwargs):
"""
Estimate burstness profile for a feature over the ``'date'`` axis.
Parameters
----------
corpus : :class:`.Corpus`
feature : str
Name of featureset in... | [
"def",
"feature_burstness",
"(",
"corpus",
",",
"featureset_name",
",",
"feature",
",",
"k",
"=",
"5",
",",
"normalize",
"=",
"True",
",",
"s",
"=",
"1.1",
",",
"gamma",
"=",
"1.",
",",
"*",
"*",
"slice_kwargs",
")",
":",
"if",
"featureset_name",
"not"... | 30.147059 | 19.470588 |
def dispatch(self, *args, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Get if this class is working as only a base render and List funcionality shouldn't be enabled
onlybase = getattr(self, "onlybase", False)
# REST not available when only... | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get if this class is working as only a base render and List funcionality shouldn't be enabled",
"onlybase",
"=",
"getattr",
"(",
"self",
",",
"\"onlybase\"",
",",
"False",
")",
"# ... | 58.509259 | 39.861111 |
def print(*args, **kwargs):
"""
Normally print function in python prints values to a stream / stdout
>> print(value1, value2, sep='', end='\n', file=sys.stdout)
Current package usage:
======================
print(value1, value2, sep='', end='\n', file=sys.stdout, color=None,
bg_color=None, ... | [
"def",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Pop out color and background values from kwargs",
"color_name",
"=",
"kwargs",
".",
"pop",
"(",
"'color'",
",",
"None",
")",
"bg_color",
"=",
"kwargs",
".",
"pop",
"(",
"'bg_color'",
","... | 43.583333 | 22.654762 |
def is_answer_available(self, assessment_section_id, item_id):
"""Tests if an answer is available for the given item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return: (boolean) - ... | [
"def",
"is_answer_available",
"(",
"self",
",",
"assessment_section_id",
",",
"item_id",
")",
":",
"# Note: we need more settings elsewhere to indicate answer available conditions",
"# This makes the simple assumption that answers are available only when",
"# a response has been submitted fo... | 46.448276 | 21.034483 |
def extract_ast_species(ast):
"""Extract species from ast.species set of tuples (id, label)"""
species_id = "None"
species_label = "None"
species = [
(species_id, species_label) for (species_id, species_label) in ast.species if species_id
]
if len(species) == 1:
(species_id, sp... | [
"def",
"extract_ast_species",
"(",
"ast",
")",
":",
"species_id",
"=",
"\"None\"",
"species_label",
"=",
"\"None\"",
"species",
"=",
"[",
"(",
"species_id",
",",
"species_label",
")",
"for",
"(",
"species_id",
",",
"species_label",
")",
"in",
"ast",
".",
"sp... | 28.473684 | 24.894737 |
def get_books_containing_page(cursor, uuid, version,
context_uuid=None, context_version=None):
"""Return a list of book names and UUIDs
that contain a given module UUID."""
with db_connect() as db_connection:
# Uses a RealDictCursor instead of the regular cursor
... | [
"def",
"get_books_containing_page",
"(",
"cursor",
",",
"uuid",
",",
"version",
",",
"context_uuid",
"=",
"None",
",",
"context_version",
"=",
"None",
")",
":",
"with",
"db_connect",
"(",
")",
"as",
"db_connection",
":",
"# Uses a RealDictCursor instead of the regul... | 54.083333 | 19.083333 |
def push(remote='origin', branch='master'):
"""git push commit"""
print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch)))
local("git push %s %s" % (remote, branch)) | [
"def",
"push",
"(",
"remote",
"=",
"'origin'",
",",
"branch",
"=",
"'master'",
")",
":",
"print",
"(",
"cyan",
"(",
"\"Pulling changes from repo ( %s / %s)...\"",
"%",
"(",
"remote",
",",
"branch",
")",
")",
")",
"local",
"(",
"\"git push %s %s\"",
"%",
"(",... | 47.75 | 11.5 |
def quaternion_about_axis(angle, axis):
"""Return quaternion for rotation about axis.
>>> q = quaternion_about_axis(0.123, [1, 0, 0])
>>> np.allclose(q, [0.99810947, 0.06146124, 0, 0])
True
"""
q = np.array([0.0, axis[0], axis[1], axis[2]])
qlen = vector_norm(q)
if qlen > _EPS:
... | [
"def",
"quaternion_about_axis",
"(",
"angle",
",",
"axis",
")",
":",
"q",
"=",
"np",
".",
"array",
"(",
"[",
"0.0",
",",
"axis",
"[",
"0",
"]",
",",
"axis",
"[",
"1",
"]",
",",
"axis",
"[",
"2",
"]",
"]",
")",
"qlen",
"=",
"vector_norm",
"(",
... | 27.642857 | 15.785714 |
def get_backlog_configurations(self, team_context):
"""GetBacklogConfigurations.
Gets backlog configuration for a team
:param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context for the operation
:rtype: :class:`<BacklogConfiguration> <azure.... | [
"def",
"get_backlog_configurations",
"(",
"self",
",",
"team_context",
")",
":",
"project",
"=",
"None",
"team",
"=",
"None",
"if",
"team_context",
"is",
"not",
"None",
":",
"if",
"team_context",
".",
"project_id",
":",
"project",
"=",
"team_context",
".",
"... | 45.75 | 19.071429 |
def form_valid(self, form):
# lb = SalesLines.objects.filter(pk=self.__line_pk).first()
# product_old = lb.product_final
product_pk = self.request.POST.get("product_final", None)
quantity = self.request.POST.get("quantity", None)
product_final = ProductFinal.objects.filter(pk=pr... | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"# lb = SalesLines.objects.filter(pk=self.__line_pk).first()",
"# product_old = lb.product_final",
"product_pk",
"=",
"self",
".",
"request",
".",
"POST",
".",
"get",
"(",
"\"product_final\"",
",",
"None",
")",
... | 47.025 | 20.825 |
def _isub(self, other):
"""Discard the elements of other from self.
if isinstance(it, _basebag):
This runs in O(it.num_unique_elements())
else:
This runs in O(len(it))
"""
if isinstance(other, _basebag):
for elem, other_count in other.counts():
try:
self._increment_count(elem, -other_count)... | [
"def",
"_isub",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"_basebag",
")",
":",
"for",
"elem",
",",
"other_count",
"in",
"other",
".",
"counts",
"(",
")",
":",
"try",
":",
"self",
".",
"_increment_count",
"(",
"elem"... | 22.666667 | 17.047619 |
def stats(self, name, value):
"""
Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics
"""
counter = self.get(name, CounterType.Statistics)
self.... | [
"def",
"stats",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"Statistics",
")",
"self",
".",
"_calculate_stats",
"(",
"counter",
",",
"value",
")",
"self",
".",
"_update",
... | 33.181818 | 18.272727 |
def hashes_above(path, line_number):
"""Yield hashes from contiguous comment lines before line ``line_number``.
"""
def hash_lists(path):
"""Yield lists of hashes appearing between non-comment lines.
The lists will be in order of appearance and, for each non-empty
list, their place... | [
"def",
"hashes_above",
"(",
"path",
",",
"line_number",
")",
":",
"def",
"hash_lists",
"(",
"path",
")",
":",
"\"\"\"Yield lists of hashes appearing between non-comment lines.\n\n The lists will be in order of appearance and, for each non-empty\n list, their place in the re... | 41.074074 | 17.851852 |
def _ExtractGoogleDocsSearchQuery(self, url):
"""Extracts a search query from a Google docs URL.
Google Docs: https://docs.google.com/.*/u/0/?q=query
Args:
url (str): URL.
Returns:
str: search query or None if no query was found.
"""
if 'q=' not in url:
return None
lin... | [
"def",
"_ExtractGoogleDocsSearchQuery",
"(",
"self",
",",
"url",
")",
":",
"if",
"'q='",
"not",
"in",
"url",
":",
"return",
"None",
"line",
"=",
"self",
".",
"_GetBetweenQEqualsAndAmpersand",
"(",
"url",
")",
"if",
"not",
"line",
":",
"return",
"None",
"re... | 21.894737 | 22.052632 |
def magic_api(word):
"""
This is our magic API that we're simulating.
It'll return a random number and a cache timer.
"""
result = sum(ord(x)-65 + randint(1,50) for x in word)
delta = timedelta(seconds=result)
cached_until = datetime.now() + delta
return result, cached_until | [
"def",
"magic_api",
"(",
"word",
")",
":",
"result",
"=",
"sum",
"(",
"ord",
"(",
"x",
")",
"-",
"65",
"+",
"randint",
"(",
"1",
",",
"50",
")",
"for",
"x",
"in",
"word",
")",
"delta",
"=",
"timedelta",
"(",
"seconds",
"=",
"result",
")",
"cach... | 30.8 | 11 |
def _make_stream_transport(self):
"""Create an AdbStreamTransport with a newly allocated local_id."""
msg_queue = queue.Queue()
with self._stream_transport_map_lock:
# Start one past the last id we used, and grab the first available one.
# This mimics the ADB behavior of 'increment an unsigned a... | [
"def",
"_make_stream_transport",
"(",
"self",
")",
":",
"msg_queue",
"=",
"queue",
".",
"Queue",
"(",
")",
"with",
"self",
".",
"_stream_transport_map_lock",
":",
"# Start one past the last id we used, and grab the first available one.",
"# This mimics the ADB behavior of 'incr... | 54.814815 | 21.148148 |
def inject(self, inst, **renames):
"""Injects dependencies and propagates dependency injector"""
if renames:
di = self.clone(**renames)
else:
di = self
pro = di._provides
inst.__injections_source__ = di
deps = getattr(inst, '__injections__', None)
... | [
"def",
"inject",
"(",
"self",
",",
"inst",
",",
"*",
"*",
"renames",
")",
":",
"if",
"renames",
":",
"di",
"=",
"self",
".",
"clone",
"(",
"*",
"*",
"renames",
")",
"else",
":",
"di",
"=",
"self",
"pro",
"=",
"di",
".",
"_provides",
"inst",
"."... | 35.227273 | 13.818182 |
def transform_regex_replace(source, pattern, rewrite, name=None):
"""Replace all substrings from `needle` to corresponding strings in `haystack` with source.
Args:
source: `Tensor` or `SparseTensor` of any shape, source strings for replacing.
pattern: List of RE2 patterns to search in source
... | [
"def",
"transform_regex_replace",
"(",
"source",
",",
"pattern",
",",
"rewrite",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"TransformRegexReplace\"",
",",
"[",
"source",
"]",
")",
":",
"source",
"=",
"convert... | 44.291667 | 24.708333 |
def f1_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None):
r"""
Compute f-1 score of a predicted DataFrame. f-1 is defined as
.. math::
\frac{2 \cdot precision \cdot recall}{precision + recall}
:Parameters:
- **df** - predicted data frame
- **col... | [
"def",
"f1_score",
"(",
"df",
",",
"col_true",
"=",
"None",
",",
"col_pred",
"=",
"'precision_result'",
",",
"pos_label",
"=",
"1",
",",
"average",
"=",
"None",
")",
":",
"if",
"not",
"col_pred",
":",
"col_pred",
"=",
"get_field_name_by_role",
"(",
"df",
... | 32.53125 | 29.765625 |
def sliding_window(image, step_size, window_size, mask=None, only_whole=True):
"""
Creates generator of sliding windows.
:param image: input image
:param step_size: number of pixels we are going to skip in both the (x, y) direction
:param window_size: the width and height of the window we are going ... | [
"def",
"sliding_window",
"(",
"image",
",",
"step_size",
",",
"window_size",
",",
"mask",
"=",
"None",
",",
"only_whole",
"=",
"True",
")",
":",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"np",
".",
"ones",
"(",
"image",
".",
"shape",
",",
"dtype"... | 51.703704 | 20.074074 |
def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True):
"""
Function creates a text view with wrap_mode
and justification
"""
text_view = Gtk.TextView()
text_view.set_wrap_mode(wrap_mode)
text_view.... | [
"def",
"create_textview",
"(",
"self",
",",
"wrap_mode",
"=",
"Gtk",
".",
"WrapMode",
".",
"WORD_CHAR",
",",
"justify",
"=",
"Gtk",
".",
"Justification",
".",
"LEFT",
",",
"visible",
"=",
"True",
",",
"editable",
"=",
"True",
")",
":",
"text_view",
"=",
... | 38.285714 | 13.857143 |
def json_worker(self, mask, cache_id=None, cache_method="string",
cache_section="www"):
"""A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread a... | [
"def",
"json_worker",
"(",
"self",
",",
"mask",
",",
"cache_id",
"=",
"None",
",",
"cache_method",
"=",
"\"string\"",
",",
"cache_section",
"=",
"\"www\"",
")",
":",
"use_cache",
"=",
"cache_id",
"is",
"not",
"None",
"def",
"wrapper",
"(",
"fun",
")",
":... | 43.334405 | 14.434084 |
def kill_all(self, bIgnoreExceptions = False):
"""
Kills from all processes currently being debugged.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when killing each process. C{False} to stop and raise an
... | [
"def",
"kill_all",
"(",
"self",
",",
"bIgnoreExceptions",
"=",
"False",
")",
":",
"for",
"pid",
"in",
"self",
".",
"get_debugee_pids",
"(",
")",
":",
"self",
".",
"kill",
"(",
"pid",
",",
"bIgnoreExceptions",
"=",
"bIgnoreExceptions",
")"
] | 41.642857 | 17.5 |
def _fetch_langs():
"""Fetch (scrape) languages from Google Translate.
Google Translate loads a JavaScript Array of 'languages codes' that can
be spoken. We intersect this list with all the languages Google Translate
provides to get the ones that support text-to-speech.
Returns:
dict: A di... | [
"def",
"_fetch_langs",
"(",
")",
":",
"# Load HTML",
"page",
"=",
"requests",
".",
"get",
"(",
"URL_BASE",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"page",
".",
"content",
",",
"'html.parser'",
")",
"# JavaScript URL",
"# The <script src=''> path can change, but not ... | 42.875 | 23.5 |
def clear(self):
"""
Clear the cache.
"""
not_removed = []
for fn in os.listdir(self.base):
fn = os.path.join(self.base, fn)
try:
if os.path.islink(fn) or os.path.isfile(fn):
os.remove(fn)
elif os.path.is... | [
"def",
"clear",
"(",
"self",
")",
":",
"not_removed",
"=",
"[",
"]",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"base",
")",
":",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base",
",",
"fn",
")",
"try",
":",... | 29.866667 | 9.466667 |
def _compose_range(pattern, rule, fill=2):
"""oc._compose_range('Week', 'Week04-Week09', fill=2) - hash a range.
This takes apart a range of times and returns a dictionary of
all intervening values appropriately set. The fill value is
used to format the time numbers.
"""
keys = []
mask = l... | [
"def",
"_compose_range",
"(",
"pattern",
",",
"rule",
",",
"fill",
"=",
"2",
")",
":",
"keys",
"=",
"[",
"]",
"mask",
"=",
"len",
"(",
"pattern",
")",
"for",
"rule",
"in",
"str",
".",
"split",
"(",
"rule",
",",
"\",\"",
")",
":",
"if",
"not",
"... | 31.882353 | 13.823529 |
def get_new_driver(self, browser=None, headless=None,
servername=None, port=None, proxy=None, agent=None,
switch_to=True, cap_file=None, disable_csp=None):
""" This method spins up an extra browser for tests that require
more than one. The first browser ... | [
"def",
"get_new_driver",
"(",
"self",
",",
"browser",
"=",
"None",
",",
"headless",
"=",
"None",
",",
"servername",
"=",
"None",
",",
"port",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"agent",
"=",
"None",
",",
"switch_to",
"=",
"True",
",",
"cap_... | 51.708738 | 19.757282 |
def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
allow_redirects=False):
"""
Make an HTTP Request with parameters provided.
:param str method: The HTTP method to use
:param str url: The URL to request
:param dict param... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"allow_redirects",
"=",
"False",
")",
":",
"kwa... | 38.037037 | 23.074074 |
def extract_objects(self, fname, type_filter=None):
'''Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
'''
objects = []
if fname in se... | [
"def",
"extract_objects",
"(",
"self",
",",
"fname",
",",
"type_filter",
"=",
"None",
")",
":",
"objects",
"=",
"[",
"]",
"if",
"fname",
"in",
"self",
".",
"object_cache",
":",
"objects",
"=",
"self",
".",
"object_cache",
"[",
"fname",
"]",
"else",
":"... | 28.954545 | 19.409091 |
def renegotiate(self):
"""
Renegotiate the session.
:return: True if the renegotiation can be started, False otherwise
:rtype: bool
"""
if not self.renegotiate_pending():
_openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
return True
re... | [
"def",
"renegotiate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"renegotiate_pending",
"(",
")",
":",
"_openssl_assert",
"(",
"_lib",
".",
"SSL_renegotiate",
"(",
"self",
".",
"_ssl",
")",
"==",
"1",
")",
"return",
"True",
"return",
"False"
] | 29.090909 | 16.727273 |
def changelist_view(self, request, extra_context=None):
""" Redirect to the changelist view for subclasses. """
if self.model is not self.concrete_model:
return HttpResponseRedirect(
admin_url(self.concrete_model, "changelist"))
extra_context = extra_context or {}
... | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"if",
"self",
".",
"model",
"is",
"not",
"self",
".",
"concrete_model",
":",
"return",
"HttpResponseRedirect",
"(",
"admin_url",
"(",
"self",
".",
"concrete_m... | 43.181818 | 16.545455 |
def get_chunk_hash(file,
seed,
filesz=None,
chunksz=DEFAULT_CHUNK_SIZE,
bufsz=DEFAULT_BUFFER_SIZE):
"""returns a hash of a chunk of the file provided. the position of
the chunk is determined by the seed. additi... | [
"def",
"get_chunk_hash",
"(",
"file",
",",
"seed",
",",
"filesz",
"=",
"None",
",",
"chunksz",
"=",
"DEFAULT_CHUNK_SIZE",
",",
"bufsz",
"=",
"DEFAULT_BUFFER_SIZE",
")",
":",
"if",
"(",
"filesz",
"is",
"None",
")",
":",
"file",
".",
"seek",
"(",
"0",
",... | 37.485714 | 14.171429 |
def _get_column_type(self,column):
""" Return 'numeric' if the column is of type integer or
real, otherwise return 'string'. """
ctype = column.GetType()
if ctype in [ogr.OFTInteger, ogr.OFTReal]:
return 'numeric'
else:
return 'string' | [
"def",
"_get_column_type",
"(",
"self",
",",
"column",
")",
":",
"ctype",
"=",
"column",
".",
"GetType",
"(",
")",
"if",
"ctype",
"in",
"[",
"ogr",
".",
"OFTInteger",
",",
"ogr",
".",
"OFTReal",
"]",
":",
"return",
"'numeric'",
"else",
":",
"return",
... | 36.5 | 9.5 |
def accumulate(iterable):
" Return series of accumulated sums. "
iterator = iter(iterable)
sum_data = next(iterator)
yield sum_data
for el in iterator:
sum_data += el
yield sum_data | [
"def",
"accumulate",
"(",
"iterable",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"sum_data",
"=",
"next",
"(",
"iterator",
")",
"yield",
"sum_data",
"for",
"el",
"in",
"iterator",
":",
"sum_data",
"+=",
"el",
"yield",
"sum_data"
] | 24 | 16 |
def from_string(cls, string, *, default_func=None):
'''Construct a Service from a string.
If default_func is provided and any ServicePart is missing, it is called with
default_func(protocol, part) to obtain the missing part.
'''
if not isinstance(string, str):
raise ... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
",",
"*",
",",
"default_func",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"f'service must be a string: {string}'",
")",
"parts",
"=",
"s... | 41.037037 | 22.148148 |
def qos_queue_scheduler_strict_priority_dwrr_traffic_class6(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement... | [
"def",
"qos_queue_scheduler_strict_priority_dwrr_traffic_class6",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"qos",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"qos\"",
",",
"xmlns",
"... | 49.384615 | 20.384615 |
def post(self, url, data=None, **kwargs):
"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
:param **kwargs: Optional arguments that ``r... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'post'",
",",
"url",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 44.666667 | 22.777778 |
def normalize_value(value, snake_case=True):
"""
:param value:
:return value:
"""
if not isinstance(value, six.string_types):
raise TypeError("the value passed to value must be a string")
if snake_case:
s1 = first_cap_re.sub(r'\1_\2', value)
new_value = all_cap_re.sub(r'... | [
"def",
"normalize_value",
"(",
"value",
",",
"snake_case",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"the value passed to value must be a string\"",
")",
"if",
"snake_c... | 27.533333 | 19.266667 |
def render_widget(self, request, widget_id):
'''Returns rendered widget in JSON response'''
widget = get_widget_from_id(widget_id)
response = widget.render(**{'request': request})
return JsonResponse({'result': response, 'id': widget_id}) | [
"def",
"render_widget",
"(",
"self",
",",
"request",
",",
"widget_id",
")",
":",
"widget",
"=",
"get_widget_from_id",
"(",
"widget_id",
")",
"response",
"=",
"widget",
".",
"render",
"(",
"*",
"*",
"{",
"'request'",
":",
"request",
"}",
")",
"return",
"J... | 33.25 | 23.25 |
def write_config(configuration):
"""Helper to write the JSON configuration to a file"""
with open(CONFIG_PATH, 'w') as f:
json.dump(configuration, f, indent=2, sort_keys=True) | [
"def",
"write_config",
"(",
"configuration",
")",
":",
"with",
"open",
"(",
"CONFIG_PATH",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"configuration",
",",
"f",
",",
"indent",
"=",
"2",
",",
"sort_keys",
"=",
"True",
")"
] | 47 | 8 |
def connection_lost(self, reason):
"""Protocols connection lost handler.
"""
LOG.info(
'Connection to peer %s lost, reason: %s Resetting '
'retry connect loop: %s' %
(self._neigh_conf.ip_address, reason,
self._connect_retry_event.is_set()),
... | [
"def",
"connection_lost",
"(",
"self",
",",
"reason",
")",
":",
"LOG",
".",
"info",
"(",
"'Connection to peer %s lost, reason: %s Resetting '",
"'retry connect loop: %s'",
"%",
"(",
"self",
".",
"_neigh_conf",
".",
"ip_address",
",",
"reason",
",",
"self",
".",
"_... | 37.529412 | 13.588235 |
def partial_derivative(self, X, y=0):
"""Compute partial derivative :math:`C(u|v)` of cumulative density.
Args:
X: `np.ndarray`
y: `float`
Returns:
"""
self.check_fit()
U, V = self.split_matrix(X)
if self.theta == 1:
return... | [
"def",
"partial_derivative",
"(",
"self",
",",
"X",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"U",
",",
"V",
"=",
"self",
".",
"split_matrix",
"(",
"X",
")",
"if",
"self",
".",
"theta",
"==",
"1",
":",
"return",
"V",
"el... | 27.041667 | 20.625 |
def free(**kwargs):
''' Stop synchronization of directory. '''
output, err = cli_syncthing_adapter.free(kwargs['path'])
click.echo("%s" % output, err=err) | [
"def",
"free",
"(",
"*",
"*",
"kwargs",
")",
":",
"output",
",",
"err",
"=",
"cli_syncthing_adapter",
".",
"free",
"(",
"kwargs",
"[",
"'path'",
"]",
")",
"click",
".",
"echo",
"(",
"\"%s\"",
"%",
"output",
",",
"err",
"=",
"err",
")"
] | 31.4 | 17.4 |
def authenticate(username, password):
"""
Returns:
a dict with:
pk: the pk of the user
token: dict containing all the data from the api
(access_token, refresh_token, expires_at etc.)
user_data: dict containing user data such as
first_na... | [
"def",
"authenticate",
"(",
"username",
",",
"password",
")",
":",
"session",
"=",
"MoJOAuth2Session",
"(",
"client",
"=",
"LegacyApplicationClient",
"(",
"client_id",
"=",
"settings",
".",
"API_CLIENT_ID",
")",
")",
"token",
"=",
"session",
".",
"fetch_token",
... | 29.323529 | 18.264706 |
def marshal_with(self, schema, envelope=None):
"""
A decorator that apply marshalling to the return values of your methods.
:param schema: The schema class to be used to serialize the values.
:param envelope: The key used to envelope the data.
:return: A function.
"""
... | [
"def",
"marshal_with",
"(",
"self",
",",
"schema",
",",
"envelope",
"=",
"None",
")",
":",
"# schema is pre instantiated to avoid instantiate it",
"# on every request",
"schema_is_class",
"=",
"isclass",
"(",
"schema",
")",
"schema_cache",
"=",
"schema",
"(",
")",
"... | 37.314286 | 18.685714 |
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
See parent class :meth:`execute` docstring for full details.
"""
msg_id = self.kernel_manager.shell_channel.execute(source, hidden)
self._request_info['execute'][msg_id] = self._Execut... | [
"def",
"_execute",
"(",
"self",
",",
"source",
",",
"hidden",
")",
":",
"msg_id",
"=",
"self",
".",
"kernel_manager",
".",
"shell_channel",
".",
"execute",
"(",
"source",
",",
"hidden",
")",
"self",
".",
"_request_info",
"[",
"'execute'",
"]",
"[",
"msg_... | 43 | 18.3 |
def unionIntoArray(self, inputVector, outputVector, forceOutput=False):
"""
Create a union of the inputVector and copy the result into the outputVector
Parameters:
----------------------------
@param inputVector: The inputVector can be either a full numpy array
containing 0's... | [
"def",
"unionIntoArray",
"(",
"self",
",",
"inputVector",
",",
"outputVector",
",",
"forceOutput",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"inputVector",
",",
"numpy",
".",
"ndarray",
")",
":",
"if",
"inputVector",
".",
"size",
"==",
"self",
".",
... | 40.275 | 20.725 |
def exons(self, contig=None, strand=None):
"""
Create exon object for all exons in the database, optionally
restrict to a particular chromosome using the `contig` argument.
"""
# DataFrame with single column called "exon_id"
exon_ids = self.exon_ids(contig=contig, strand=... | [
"def",
"exons",
"(",
"self",
",",
"contig",
"=",
"None",
",",
"strand",
"=",
"None",
")",
":",
"# DataFrame with single column called \"exon_id\"",
"exon_ids",
"=",
"self",
".",
"exon_ids",
"(",
"contig",
"=",
"contig",
",",
"strand",
"=",
"strand",
")",
"re... | 37.909091 | 14.818182 |
def disable_logger(logger_name: str, propagate: bool = False):
"""Disable output for the logger of the specified name."""
log = logging.getLogger(logger_name)
log.propagate = propagate
for handler in log.handlers:
log.removeHandler(handler) | [
"def",
"disable_logger",
"(",
"logger_name",
":",
"str",
",",
"propagate",
":",
"bool",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"log",
".",
"propagate",
"=",
"propagate",
"for",
"handler",
"in",
"log",
".... | 43.166667 | 7.833333 |
def get_all_values_of_all_params(self):
"""
Return a dictionary containing all values that are taken by all
available parameters.
Always returns the parameter list in alphabetical order.
"""
values = collections.OrderedDict([[p, []] for p in
... | [
"def",
"get_all_values_of_all_params",
"(",
"self",
")",
":",
"values",
"=",
"collections",
".",
"OrderedDict",
"(",
"[",
"[",
"p",
",",
"[",
"]",
"]",
"for",
"p",
"in",
"sorted",
"(",
"self",
".",
"get_params",
"(",
")",
")",
"]",
")",
"for",
"resul... | 35 | 19.833333 |
def birthdays_subcommand(vcard_list, parsable):
"""Print birthday contact table.
:param vcard_list: the vcards to search for matching entries which should
be printed
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t... | [
"def",
"birthdays_subcommand",
"(",
"vcard_list",
",",
"parsable",
")",
":",
"# filter out contacts without a birthday date",
"vcard_list",
"=",
"[",
"vcard",
"for",
"vcard",
"in",
"vcard_list",
"if",
"vcard",
".",
"get_birthday",
"(",
")",
"is",
"not",
"None",
"]... | 40.981132 | 20.283019 |
def start_blocking(self):
""" Start the advertiser in the background, but wait until it is ready """
self._cav_started.clear()
self.start()
self._cav_started.wait() | [
"def",
"start_blocking",
"(",
"self",
")",
":",
"self",
".",
"_cav_started",
".",
"clear",
"(",
")",
"self",
".",
"start",
"(",
")",
"self",
".",
"_cav_started",
".",
"wait",
"(",
")"
] | 32 | 15 |
def parse_unit(expression):
"""Evaluate a python expression string containing constants
Argument:
| ``expression`` -- A string containing a numerical expressions
including unit conversions.
In addition to the variables in this module, also the following
... | [
"def",
"parse_unit",
"(",
"expression",
")",
":",
"try",
":",
"g",
"=",
"globals",
"(",
")",
"g",
".",
"update",
"(",
"shorthands",
")",
"return",
"float",
"(",
"eval",
"(",
"str",
"(",
"expression",
")",
",",
"g",
")",
")",
"except",
":",
"raise",... | 32.235294 | 23.058824 |
def acknowledge_svc_problem(self, service, sticky, notify, author, comment):
"""Acknowledge a service problem
Format of the line that triggers function call::
ACKNOWLEDGE_SVC_PROBLEM;<host_name>;<service_description>;<sticky>;<notify>;
<persistent:obsolete>;<author>;<comment>
:... | [
"def",
"acknowledge_svc_problem",
"(",
"self",
",",
"service",
",",
"sticky",
",",
"notify",
",",
"author",
",",
"comment",
")",
":",
"notification_period",
"=",
"None",
"if",
"getattr",
"(",
"service",
",",
"'notification_period'",
",",
"None",
")",
"is",
"... | 51.291667 | 24.583333 |
def final_spin_from_f0_tau(f0, tau, l=2, m=2):
"""Returns the final spin based on the given frequency and damping time.
.. note::
Currently, only l = m = 2 is supported. Any other indices will raise
a ``KeyError``.
Parameters
----------
f0 : float or array
Frequency of the ... | [
"def",
"final_spin_from_f0_tau",
"(",
"f0",
",",
"tau",
",",
"l",
"=",
"2",
",",
"m",
"=",
"2",
")",
":",
"f0",
",",
"tau",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"f0",
",",
"tau",
")",
"# from Berti et al. 2006",
"a",
",",
"b",
",",
"c",
... | 30.119048 | 16.714286 |
def addSubparser(subparsers, subcommand, description):
"""
Add a subparser with subcommand to the subparsers object
"""
parser = subparsers.add_parser(
subcommand, description=description, help=description)
return parser | [
"def",
"addSubparser",
"(",
"subparsers",
",",
"subcommand",
",",
"description",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"subcommand",
",",
"description",
"=",
"description",
",",
"help",
"=",
"description",
")",
"return",
"parser"
] | 34.571429 | 12 |
def create_namespaced_cron_job(self, namespace, body, **kwargs):
"""
create a CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_cron_job(namespace, body, async_req=T... | [
"def",
"create_namespaced_cron_job",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
"."... | 66.25 | 39.583333 |
def make_qemu_dirs(max_qemu_id, output_dir, topology_name):
"""
Create Qemu VM working directories if required
:param int max_qemu_id: Number of directories to create
:param str output_dir: Output directory
:param str topology_name: Topology name
"""
if max_qemu_id is not None:
for ... | [
"def",
"make_qemu_dirs",
"(",
"max_qemu_id",
",",
"output_dir",
",",
"topology_name",
")",
":",
"if",
"max_qemu_id",
"is",
"not",
"None",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"max_qemu_id",
"+",
"1",
")",
":",
"qemu_dir",
"=",
"os",
".",
"pat... | 38.769231 | 12.461538 |
def section(self, section, skip=['type', 'order']):
""" Return section items, skip selected (type/order by default) """
return [(key, val) for key, val in self.parser.items(section)
if key not in skip] | [
"def",
"section",
"(",
"self",
",",
"section",
",",
"skip",
"=",
"[",
"'type'",
",",
"'order'",
"]",
")",
":",
"return",
"[",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"self",
".",
"parser",
".",
"items",
"(",
"section",
")",
... | 57.5 | 11.25 |
def parse_info(wininfo_name, egginfo_name):
"""Extract metadata from filenames.
Extracts the 4 metadataitems needed (name, version, pyversion, arch) from
the installer filename and the name of the egg-info directory embedded in
the zipfile (if any).
The egginfo filename has the format::
... | [
"def",
"parse_info",
"(",
"wininfo_name",
",",
"egginfo_name",
")",
":",
"egginfo",
"=",
"None",
"if",
"egginfo_name",
":",
"egginfo",
"=",
"egg_info_re",
".",
"search",
"(",
"egginfo_name",
")",
"if",
"not",
"egginfo",
":",
"raise",
"ValueError",
"(",
"\"Eg... | 39.957746 | 22.098592 |
def connect_cloudformation(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.cloud... | [
"def",
"connect_cloudformation",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"boto",
".",
"cloudformation",
"import",
"CloudFormationConnection",
"return",
"CloudFormationConnection",
"("... | 43.153846 | 21.461538 |
def _auth_headers(self):
"""Headers required to authenticate a request.
Assumes your ``Context`` already has a authentication token,
either provided explicitly or obtained by logging into the
Splunk instance.
:returns: A list of 2-tuples containing key and value
"""
... | [
"def",
"_auth_headers",
"(",
"self",
")",
":",
"if",
"self",
".",
"token",
"is",
"_NoAuthenticationToken",
":",
"return",
"[",
"]",
"else",
":",
"# Ensure the token is properly formatted",
"if",
"self",
".",
"token",
".",
"startswith",
"(",
"'Splunk '",
")",
"... | 35.222222 | 16.833333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.