text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_mcmc_method_kernel_data_elements(self):
"""Get the mcmc method kernel data elements. Used by :meth:`_get_mcmc_method_kernel_data`."""
return {'proposal_stds': Array(self._proposal_stds, 'mot_float_type', mode='rw', ensure_zero_copy=True),
'x_tmp': LocalMemory('mot_float_type', n... | [
"def",
"_get_mcmc_method_kernel_data_elements",
"(",
"self",
")",
":",
"return",
"{",
"'proposal_stds'",
":",
"Array",
"(",
"self",
".",
"_proposal_stds",
",",
"'mot_float_type'",
",",
"mode",
"=",
"'rw'",
",",
"ensure_zero_copy",
"=",
"True",
")",
",",
"'x_tmp'... | 87 | 31.75 |
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes:
"""
Returns the binary contents of a file, or of a BLOB.
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
... | [
"def",
"get_file_contents",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
")",
"->",
"bytes",
":",
"if",
"not",
"filename",
"and",
"not",
"blob",
":",
"raise",
"ValueError",
"(",
"\"no filename and no blob\"",
")",
"if",... | 33.333333 | 14.333333 |
def run(input=sys.stdin, output=sys.stdout):
r"""CouchDB view function handler implementation for Python.
:param input: the readable file-like object to read input from
:param output: the writable file-like object to write output to
"""
functions = []
environments = dict()
def _writejson(o... | [
"def",
"run",
"(",
"input",
"=",
"sys",
".",
"stdin",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"functions",
"=",
"[",
"]",
"environments",
"=",
"dict",
"(",
")",
"def",
"_writejson",
"(",
"obj",
")",
":",
"obj",
"=",
"json",
".",
"enco... | 31.405941 | 17.420792 |
def add_molecule(self, mol, bond=None, base=None, target=None):
"""connect atom group (for SMILES parser)
May requires recalculation of 2D coordinate for drawing
Args:
mol: graphmol.Compound()
the original object will be copied.
bond: Bond object to be c... | [
"def",
"add_molecule",
"(",
"self",
",",
"mol",
",",
"bond",
"=",
"None",
",",
"base",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"ai",
"=",
"self",
".",
"available_idx",
"(",
")",
"mapping",
"=",
"{",
"n",
":",
"n",
"+",
"ai",
"-",
"1"... | 40.636364 | 18.454545 |
async def pick_up_tip(self,
mount,
tip_length: float,
presses: int = None,
increment: float = None):
"""
Pick up tip from current location.
If ``presses`` or ``increment`` is not specified (o... | [
"async",
"def",
"pick_up_tip",
"(",
"self",
",",
"mount",
",",
"tip_length",
":",
"float",
",",
"presses",
":",
"int",
"=",
"None",
",",
"increment",
":",
"float",
"=",
"None",
")",
":",
"instr",
"=",
"self",
".",
"_attached_instruments",
"[",
"mount",
... | 42.033898 | 15.389831 |
def add_signaling_arguments(parser):
"""
Add signaling method arguments to an argparse.ArgumentParser.
"""
parser.add_argument('--signaling', '-s', choices=[
'copy-and-paste', 'tcp-socket', 'unix-socket'])
parser.add_argument('--signaling-host', default='127.0.0.1',
h... | [
"def",
"add_signaling_arguments",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--signaling'",
",",
"'-s'",
",",
"choices",
"=",
"[",
"'copy-and-paste'",
",",
"'tcp-socket'",
",",
"'unix-socket'",
"]",
")",
"parser",
".",
"add_argument",
"(",
... | 51.083333 | 17.25 |
def trunk_origin_elevations(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin elevations of a neuron or population
The elevation is defined as the angle between x-axis and the
vector defined by (initial tree point - soma center)
on the x-y half-plane.
The range of the eleva... | [
"def",
"trunk_origin_elevations",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"nrns",
"=",
"neuron_population",
"(",
"nrn",
")",
"def",
"_elevation",
"(",
"section",
","... | 38.875 | 22.125 |
def get_methods_names(public_properties):
"""
Generates the names of the fields where to inject the getter and setter
methods
:param public_properties: If True, returns the names of public property
accessors, else of hidden property ones
:return... | [
"def",
"get_methods_names",
"(",
"public_properties",
")",
":",
"if",
"public_properties",
":",
"prefix",
"=",
"ipopo_constants",
".",
"IPOPO_PROPERTY_PREFIX",
"else",
":",
"prefix",
"=",
"ipopo_constants",
".",
"IPOPO_HIDDEN_PROPERTY_PREFIX",
"return",
"(",
"\"{0}{1}\"... | 38.5 | 23.722222 |
def add_header(self, header):
"""Add a custom HTTP header to the client's request headers"""
if type(header) is dict:
self._headers.update(header)
else:
raise ValueError(
"Dictionary expected, got '%s' instead" % type(header)
) | [
"def",
"add_header",
"(",
"self",
",",
"header",
")",
":",
"if",
"type",
"(",
"header",
")",
"is",
"dict",
":",
"self",
".",
"_headers",
".",
"update",
"(",
"header",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Dictionary expected, got '%s' instead\"",
... | 37 | 14.25 |
def assign(self, dst, req, src):
"""Helper function for assigning into dst depending on requirements."""
if req == 'null':
return
elif req in ('write', 'inplace'):
dst[:] = src
elif req == 'add':
dst[:] += src | [
"def",
"assign",
"(",
"self",
",",
"dst",
",",
"req",
",",
"src",
")",
":",
"if",
"req",
"==",
"'null'",
":",
"return",
"elif",
"req",
"in",
"(",
"'write'",
",",
"'inplace'",
")",
":",
"dst",
"[",
":",
"]",
"=",
"src",
"elif",
"req",
"==",
"'ad... | 33.75 | 11.375 |
def get_staking_leaderboard(self, round_num=0, tournament=1):
"""Retrieves the leaderboard of the staking competition for the given
round.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, option... | [
"def",
"get_staking_leaderboard",
"(",
"self",
",",
"round_num",
"=",
"0",
",",
"tournament",
"=",
"1",
")",
":",
"msg",
"=",
"\"getting stakes for tournament {} round {}\"",
"self",
".",
"logger",
".",
"info",
"(",
"msg",
".",
"format",
"(",
"tournament",
","... | 38.240964 | 16.53012 |
def LifoQueue(self, name, initial=None, maxsize=None):
"""The LIFO queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.LifoQueue`.
"""
return types.LifoQueue(name, self.api,
... | [
"def",
"LifoQueue",
"(",
"self",
",",
"name",
",",
"initial",
"=",
"None",
",",
"maxsize",
"=",
"None",
")",
":",
"return",
"types",
".",
"LifoQueue",
"(",
"name",
",",
"self",
".",
"api",
",",
"initial",
"=",
"initial",
",",
"maxsize",
"=",
"maxsize... | 31.818182 | 16.727273 |
def _get_defaults(func):
"""Internal helper to extract the default arguments, by name."""
try:
code = func.__code__
except AttributeError:
# Some built-in functions don't have __code__, __defaults__, etc.
return {}
pos_count = code.co_argcount
arg_names = code.co_varnames
... | [
"def",
"_get_defaults",
"(",
"func",
")",
":",
"try",
":",
"code",
"=",
"func",
".",
"__code__",
"except",
"AttributeError",
":",
"# Some built-in functions don't have __code__, __defaults__, etc.",
"return",
"{",
"}",
"pos_count",
"=",
"code",
".",
"co_argcount",
"... | 35.5 | 13.166667 |
def averageConvergencePoint(self, prefix, minOverlap, maxOverlap,
settlingTime=1, firstStat=0, lastStat=None):
"""
For each object, compute the convergence time - the first point when all
L2 columns have converged.
Return the average convergence time and accuracy across a... | [
"def",
"averageConvergencePoint",
"(",
"self",
",",
"prefix",
",",
"minOverlap",
",",
"maxOverlap",
",",
"settlingTime",
"=",
"1",
",",
"firstStat",
"=",
"0",
",",
"lastStat",
"=",
"None",
")",
":",
"convergenceSum",
"=",
"0.0",
"numCorrect",
"=",
"0.0",
"... | 37.106383 | 24.382979 |
def autoactivate(client, endpoint_id, if_expires_in=None):
"""
Attempts to auto-activate the given endpoint with the given client
If auto-activation fails, parses the returned activation requirements
to determine which methods of activation are supported, then tells
the user to use 'globus endpoint ... | [
"def",
"autoactivate",
"(",
"client",
",",
"endpoint_id",
",",
"if_expires_in",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"if_expires_in",
"is",
"not",
"None",
":",
"kwargs",
"[",
"\"if_expires_in\"",
"]",
"=",
"if_expires_in",
"res",
"=",
"cli... | 35.52 | 21.92 |
def _timing_char(message):
"""
>>> message = 'MORSE CODE'
>>> _timing_char(message)
'M------ O---------- R------ S---- E C---------- O---------- D------ E'
"""
s = ''
inter_symb = ' '
inter_char = ' ' * 3
inter_word = inter_symb * 7
for i, word in enumerate(_s... | [
"def",
"_timing_char",
"(",
"message",
")",
":",
"s",
"=",
"''",
"inter_symb",
"=",
"' '",
"inter_char",
"=",
"' '",
"*",
"3",
"inter_word",
"=",
"inter_symb",
"*",
"7",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"_split_message",
"(",
"message",
... | 29.944444 | 16.277778 |
def switch_off(self, *args):
"""
Sets the state of the switch to False if off_check() returns True,
given the arguments provided in kwargs.
:param kwargs: variable length dictionary of key-pair arguments
:return: Boolean. Returns True if the operation is successful
"""
... | [
"def",
"switch_off",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"off_check",
"(",
"*",
"args",
")",
":",
"return",
"self",
".",
"_switch",
".",
"switch",
"(",
"False",
")",
"else",
":",
"return",
"False"
] | 35.5 | 17.333333 |
def _metadata_is_invalid(cls, fact):
"""Determines if the fact is not well formed.
"""
return any(isinstance(token, URIRef) and ' ' in token
for token in fact) | [
"def",
"_metadata_is_invalid",
"(",
"cls",
",",
"fact",
")",
":",
"return",
"any",
"(",
"isinstance",
"(",
"token",
",",
"URIRef",
")",
"and",
"' '",
"in",
"token",
"for",
"token",
"in",
"fact",
")"
] | 33 | 11.333333 |
def clone(self) -> 'ImageBBox':
"Mimic the behavior of torch.clone for `Image` objects."
flow = FlowField(self.size, self.flow.flow.clone())
return self.__class__(flow, scale=False, y_first=False, labels=self.labels, pad_idx=self.pad_idx) | [
"def",
"clone",
"(",
"self",
")",
"->",
"'ImageBBox'",
":",
"flow",
"=",
"FlowField",
"(",
"self",
".",
"size",
",",
"self",
".",
"flow",
".",
"flow",
".",
"clone",
"(",
")",
")",
"return",
"self",
".",
"__class__",
"(",
"flow",
",",
"scale",
"=",
... | 64.75 | 29.25 |
def verify_tree_consistency(self, old_tree_size: int, new_tree_size: int,
old_root: bytes, new_root: bytes,
proof: Sequence[bytes]):
"""Verify the consistency between two root hashes.
old_tree_size must be <= new_tree_size.
Args:
... | [
"def",
"verify_tree_consistency",
"(",
"self",
",",
"old_tree_size",
":",
"int",
",",
"new_tree_size",
":",
"int",
",",
"old_root",
":",
"bytes",
",",
"new_root",
":",
"bytes",
",",
"proof",
":",
"Sequence",
"[",
"bytes",
"]",
")",
":",
"old_size",
"=",
... | 42.778626 | 22.480916 |
def visit_desc(self):
"""
Builds a citation boilerplate by visiting all workflows
appending their ``__desc__`` field
"""
desc = []
if self.__desc__:
desc += [self.__desc__]
for node in pe.utils.topological_sort(self._graph)[0]:
if isinsta... | [
"def",
"visit_desc",
"(",
"self",
")",
":",
"desc",
"=",
"[",
"]",
"if",
"self",
".",
"__desc__",
":",
"desc",
"+=",
"[",
"self",
".",
"__desc__",
"]",
"for",
"node",
"in",
"pe",
".",
"utils",
".",
"topological_sort",
"(",
"self",
".",
"_graph",
")... | 27.9 | 15.4 |
def space(self):
"""Combined Hilbert space of all matrix elements."""
arg_spaces = [o.space for o in self.matrix.ravel()
if hasattr(o, 'space')]
if len(arg_spaces) == 0:
return TrivialSpace
else:
return ProductSpace.create(*arg_spaces) | [
"def",
"space",
"(",
"self",
")",
":",
"arg_spaces",
"=",
"[",
"o",
".",
"space",
"for",
"o",
"in",
"self",
".",
"matrix",
".",
"ravel",
"(",
")",
"if",
"hasattr",
"(",
"o",
",",
"'space'",
")",
"]",
"if",
"len",
"(",
"arg_spaces",
")",
"==",
"... | 38.25 | 12.75 |
def load_remote_settings(self, remote_bucket, remote_file):
"""
Attempt to read a file from s3 containing a flat json object. Adds each
key->value pair as environment variables. Helpful for keeping
sensitiZve or stage-specific configuration variables in s3 instead of
version cont... | [
"def",
"load_remote_settings",
"(",
"self",
",",
"remote_bucket",
",",
"remote_file",
")",
":",
"if",
"not",
"self",
".",
"session",
":",
"boto_session",
"=",
"boto3",
".",
"Session",
"(",
")",
"else",
":",
"boto_session",
"=",
"self",
".",
"session",
"s3"... | 39.170213 | 19.723404 |
def skips(self, user):
"""
Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.
"""
return self._get(self._build_url(self.endpoint.skips(id=user))) | [
"def",
"skips",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"_get",
"(",
"self",
".",
"_build_url",
"(",
"self",
".",
"endpoint",
".",
"skips",
"(",
"id",
"=",
"user",
")",
")",
")"
] | 45.8 | 24.6 |
def create_alert(self, name=None, description=None, severity=None, for_atleast_s=None, condition=None,
segmentby=[], segment_condition='ANY', user_filter='', notify=None, enabled=True,
annotations={}, alert_obj=None):
'''**Description**
Create a threshold-ba... | [
"def",
"create_alert",
"(",
"self",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"severity",
"=",
"None",
",",
"for_atleast_s",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"segmentby",
"=",
"[",
"]",
",",
"segment_condition",
"=",... | 63.649351 | 44.298701 |
def _build(credentials, api_version, http_client=None):
"""Build the client object."""
if not http_client:
http_client = httplib2.Http()
authorised_client = credentials.authorize(http_client)
return build("analytics", api_version, http=authorised_client) | [
"def",
"_build",
"(",
"credentials",
",",
"api_version",
",",
"http_client",
"=",
"None",
")",
":",
"if",
"not",
"http_client",
":",
"http_client",
"=",
"httplib2",
".",
"Http",
"(",
")",
"authorised_client",
"=",
"credentials",
".",
"authorize",
"(",
"http_... | 34.125 | 19.875 |
def cy_bispev(tx, ty, c, kx, ky, x, y):
'''Possible optimization: Do not evaluate derivatives, ever.
'''
nx = len(tx)
ny = len(ty)
mx = len(x)
my = len(y)
kx1 = kx + 1
ky1 = ky + 1
nkx1 = nx - kx1
nky1 = ny - ky1
wx = [[0.0]*kx1]*mx
wy = [[0.0]*ky1]*my
lx = [0]... | [
"def",
"cy_bispev",
"(",
"tx",
",",
"ty",
",",
"c",
",",
"kx",
",",
"ky",
",",
"x",
",",
"y",
")",
":",
"nx",
"=",
"len",
"(",
"tx",
")",
"ny",
"=",
"len",
"(",
"ty",
")",
"mx",
"=",
"len",
"(",
"x",
")",
"my",
"=",
"len",
"(",
"y",
"... | 22.131579 | 20.868421 |
def _result(self): # type: () -> SolverResult
"""
Creates a #SolverResult from the decisions in _solution
"""
decisions = self._solution.decisions
return SolverResult(
self._root,
[p for p in decisions if not p.is_root()],
self._solution.atte... | [
"def",
"_result",
"(",
"self",
")",
":",
"# type: () -> SolverResult",
"decisions",
"=",
"self",
".",
"_solution",
".",
"decisions",
"return",
"SolverResult",
"(",
"self",
".",
"_root",
",",
"[",
"p",
"for",
"p",
"in",
"decisions",
"if",
"not",
"p",
".",
... | 30.545455 | 14 |
def get_prefetch_queryset(self, instances, queryset=None):
"""
Overrides the parent method to:
- force queryset to use the querytime of the parent objects
- ensure that the join is done on identity, not id
- make the cache key identity, not id.
"""
if queryse... | [
"def",
"get_prefetch_queryset",
"(",
"self",
",",
"instances",
",",
"queryset",
"=",
"None",
")",
":",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"queryset",
".",
"_add_hints",
"(",
"instance",
"=",
"instan... | 48.130435 | 20.434783 |
def set_metadata(self, loadbalancer, metadata, node=None):
"""
Sets the metadata for the load balancer to the supplied dictionary
of values. Any existing metadata is cleared. If 'node' is provided,
the metadata for that node is set instead of for the load balancer.
"""
# ... | [
"def",
"set_metadata",
"(",
"self",
",",
"loadbalancer",
",",
"metadata",
",",
"node",
"=",
"None",
")",
":",
"# Delete any existing metadata",
"self",
".",
"delete_metadata",
"(",
"loadbalancer",
",",
"node",
"=",
"node",
")",
"# Convert the metadata dict into the ... | 47.736842 | 18.578947 |
def _varscan_work(align_bams, ref_file, items, target_regions, out_file):
"""Perform SNP and indel genotyping with VarScan.
"""
config = items[0]["config"]
orig_out_file = out_file
out_file = orig_out_file.replace(".vcf.gz", ".vcf")
max_read_depth = "1000"
sample_list = _create_sample_list... | [
"def",
"_varscan_work",
"(",
"align_bams",
",",
"ref_file",
",",
"items",
",",
"target_regions",
",",
"out_file",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"orig_out_file",
"=",
"out_file",
"out_file",
"=",
"orig_out_file",
"."... | 52.97619 | 21.666667 |
def put(self, locator = None, component = None):
"""
Puts a new reference into this reference map.
:param locator: a component reference to be added.
:param component: a locator to find the reference by.
"""
if component == None:
raise Exception("Component c... | [
"def",
"put",
"(",
"self",
",",
"locator",
"=",
"None",
",",
"component",
"=",
"None",
")",
":",
"if",
"component",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Component cannot be null\"",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
... | 30 | 19 |
def new_add_public_key_transaction(self, ont_id: str, bytes_operator: bytes, new_pub_key: str or bytes,
b58_payer_address: str, gas_limit: int, gas_price: int,
is_recovery: bool = False):
"""
This interface is used to send a T... | [
"def",
"new_add_public_key_transaction",
"(",
"self",
",",
"ont_id",
":",
"str",
",",
"bytes_operator",
":",
"bytes",
",",
"new_pub_key",
":",
"str",
"or",
"bytes",
",",
"b58_payer_address",
":",
"str",
",",
"gas_limit",
":",
"int",
",",
"gas_price",
":",
"i... | 57.925926 | 30.814815 |
def setup_schedule(self):
"Called when schedule is intialized. Fetch schedules from DB etc here"
log.info("SQLAlchemyScheduler.setup_schedule called")
if 'celery.backend_cleanup' not in self._schedule:
self._schedule['celery.backend_cleanup'] = ScheduleEntry(
name='... | [
"def",
"setup_schedule",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"SQLAlchemyScheduler.setup_schedule called\"",
")",
"if",
"'celery.backend_cleanup'",
"not",
"in",
"self",
".",
"_schedule",
":",
"self",
".",
"_schedule",
"[",
"'celery.backend_cleanup'",
"]... | 40.916667 | 21.25 |
def count_objects_by_tags(self, metric, scraper_config):
""" Count objects by whitelisted tags and submit counts as gauges. """
config = self.object_count_params[metric.name]
metric_name = "{}.{}".format(scraper_config['namespace'], config['metric_name'])
object_counter = Counter()
... | [
"def",
"count_objects_by_tags",
"(",
"self",
",",
"metric",
",",
"scraper_config",
")",
":",
"config",
"=",
"self",
".",
"object_count_params",
"[",
"metric",
".",
"name",
"]",
"metric_name",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"scraper_config",
"[",
"'names... | 51.071429 | 23.928571 |
def main(args):
'''main entry point of app
Arguments:
args {namespace} -- arguments provided in cli
'''
print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n")
#########################
# #
... | [
"def",
"main",
"(",
"args",
")",
":",
"print",
"(",
"\"\\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\\n\"",
")",
"#########################",
"# #",
"# #",
"# prompt #",... | 34.574468 | 23.042553 |
def template(*args, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
'''
tpl = args[0] if args else None
temp... | [
"def",
"template",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tpl",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"None",
"template_adapter",
"=",
"kwargs",
".",
"pop",
"(",
"'template_adapter'",
",",
"SimpleTemplate",
")",
"if",
"tpl",
... | 46.73913 | 18.391304 |
def _queue_management_worker(self):
""" TODO: docstring """
logger.debug("[MTHREAD] queue management worker starting")
while True:
task_id, buf = self.incoming_q.get() # TODO: why does this hang?
msg = deserialize_object(buf)[0]
# TODO: handle exceptions
... | [
"def",
"_queue_management_worker",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"[MTHREAD] queue management worker starting\"",
")",
"while",
"True",
":",
"task_id",
",",
"buf",
"=",
"self",
".",
"incoming_q",
".",
"get",
"(",
")",
"# TODO: why does this ... | 39.861111 | 21.444444 |
def queryModelIDs(self):
"""Queuries DB for model IDs of all currently instantiated models
associated with this HyperSearch job.
See also: _iterModels()
Parameters:
----------------------------------------------------------------------
retval: A sequence of Nupic modelIDs
"""
j... | [
"def",
"queryModelIDs",
"(",
"self",
")",
":",
"jobID",
"=",
"self",
".",
"getJobID",
"(",
")",
"modelCounterPairs",
"=",
"_clientJobsDB",
"(",
")",
".",
"modelsGetUpdateCounters",
"(",
"jobID",
")",
"modelIDs",
"=",
"tuple",
"(",
"x",
"[",
"0",
"]",
"fo... | 31.6 | 19.6 |
def get_expected_tokens(self, parser, interval_set):
# type: (QuilParser, IntervalSet) -> Iterator
"""
Like the default getExpectedTokens method except that it will fallback to the rule name if the token isn't a
literal. For instance, instead of <INVALID> for integer it will return the ... | [
"def",
"get_expected_tokens",
"(",
"self",
",",
"parser",
",",
"interval_set",
")",
":",
"# type: (QuilParser, IntervalSet) -> Iterator",
"for",
"tok",
"in",
"interval_set",
":",
"literal_name",
"=",
"parser",
".",
"literalNames",
"[",
"tok",
"]",
"symbolic_name",
"... | 43.285714 | 19.142857 |
def is_convertible_with(self, other):
"""Returns True iff `self` is convertible with `other`.
Two possibly-partially-defined shapes are convertible if there
exists a fully-defined shape that both shapes can represent. Thus,
convertibility allows the shape inference code to reason about
... | [
"def",
"is_convertible_with",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"as_shape",
"(",
"other",
")",
"if",
"self",
".",
"_dims",
"is",
"not",
"None",
"and",
"other",
".",
"dims",
"is",
"not",
"None",
":",
"if",
"self",
".",
"ndims",
"!=",
... | 44.956522 | 25.913043 |
def get_pvc_manifest(self):
"""
Make a pvc manifest that will spawn current user's pvc.
"""
labels = self._build_common_labels(self._expand_all(self.storage_extra_labels))
labels.update({
'component': 'singleuser-storage'
})
annotations = self._build_... | [
"def",
"get_pvc_manifest",
"(",
"self",
")",
":",
"labels",
"=",
"self",
".",
"_build_common_labels",
"(",
"self",
".",
"_expand_all",
"(",
"self",
".",
"storage_extra_labels",
")",
")",
"labels",
".",
"update",
"(",
"{",
"'component'",
":",
"'singleuser-stora... | 31.368421 | 17.052632 |
def list_slack():
"""List channels & users in slack."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
# Get channel list
response = slack.channels.list()
channels = response.body['channels']
for channel in channels:
print(channel['id']... | [
"def",
"list_slack",
"(",
")",
":",
"try",
":",
"token",
"=",
"os",
".",
"environ",
"[",
"'SLACK_TOKEN'",
"]",
"slack",
"=",
"Slacker",
"(",
"token",
")",
"# Get channel list",
"response",
"=",
"slack",
".",
"channels",
".",
"list",
"(",
")",
"channels",... | 32.08 | 14.2 |
def get_strategy(name_or_cls):
"""Return the strategy identified by its name. If ``name_or_class`` is a class,
it will be simply returned.
"""
if isinstance(name_or_cls, six.string_types):
if name_or_cls not in STRATS:
raise MutationError("strat is not defined")
return STRATS... | [
"def",
"get_strategy",
"(",
"name_or_cls",
")",
":",
"if",
"isinstance",
"(",
"name_or_cls",
",",
"six",
".",
"string_types",
")",
":",
"if",
"name_or_cls",
"not",
"in",
"STRATS",
":",
"raise",
"MutationError",
"(",
"\"strat is not defined\"",
")",
"return",
"... | 35.2 | 10.6 |
def handleFailure(self, test, err):
"""
Baseclass override. Called when a test fails.
If the test isn't going to be rerun again, then report the failure
to the nose test result.
:param test:
The test that has raised an error
:type test:
:class:`n... | [
"def",
"handleFailure",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"# pylint:disable=invalid-name",
"want_failure",
"=",
"self",
".",
"_handle_test_error_or_failure",
"(",
"test",
",",
"err",
")",
"if",
"not",
"want_failure",
"and",
"id",
"(",
"test",
")"... | 35.48 | 18.68 |
def get_cost_per_mol(self, comp):
"""
Get best estimate of minimum cost/mol based on known data
Args:
comp:
Composition as a pymatgen.core.structure.Composition
Returns:
float of cost/mol
"""
comp = comp if isinstance(comp, Compos... | [
"def",
"get_cost_per_mol",
"(",
"self",
",",
"comp",
")",
":",
"comp",
"=",
"comp",
"if",
"isinstance",
"(",
"comp",
",",
"Composition",
")",
"else",
"Composition",
"(",
"comp",
")",
"decomp",
"=",
"self",
".",
"get_lowest_decomposition",
"(",
"comp",
")",... | 32.866667 | 20.466667 |
def dpt_timeseries(adata, color_map=None, show=None, save=None, as_heatmap=True):
"""Heatmap of pseudotime series.
Parameters
----------
as_heatmap : bool (default: False)
Plot the timeseries as heatmap.
"""
if adata.n_vars > 100:
logg.warn('Plotting more than 100 genes might ta... | [
"def",
"dpt_timeseries",
"(",
"adata",
",",
"color_map",
"=",
"None",
",",
"show",
"=",
"None",
",",
"save",
"=",
"None",
",",
"as_heatmap",
"=",
"True",
")",
":",
"if",
"adata",
".",
"n_vars",
">",
"100",
":",
"logg",
".",
"warn",
"(",
"'Plotting mo... | 45.230769 | 20.192308 |
def has_path(nodes, A, B):
r"""Test if nodes from a breadth_first_order search lead from A to
B.
Parameters
----------
nodes : array_like
Nodes from breadth_first_oder_seatch
A : array_like
The set of educt states
B : array_like
The set of product states
Returns... | [
"def",
"has_path",
"(",
"nodes",
",",
"A",
",",
"B",
")",
":",
"x1",
"=",
"np",
".",
"intersect1d",
"(",
"nodes",
",",
"A",
")",
".",
"size",
">",
"0",
"x2",
"=",
"np",
".",
"intersect1d",
"(",
"nodes",
",",
"B",
")",
".",
"size",
">",
"0",
... | 22.636364 | 18.590909 |
def _parse(self, comp_att):
"""
Check if the value of component is correct in the attribute "comp_att".
:param string comp_att: attribute associated with value of component
:returns: None
:exception: ValueError - incorrect value of component
"""
errmsg = "Invali... | [
"def",
"_parse",
"(",
"self",
",",
"comp_att",
")",
":",
"errmsg",
"=",
"\"Invalid attribute '{0}'\"",
".",
"format",
"(",
"comp_att",
")",
"if",
"not",
"CPEComponent",
".",
"is_valid_attribute",
"(",
"comp_att",
")",
":",
"raise",
"ValueError",
"(",
"errmsg",... | 32.594595 | 17.459459 |
def _fetch_pages(self,
item_type,
items_key,
request_path,
startAt=0,
maxResults=50,
params=None,
base=JIRA_BASE_URL,
):
"""Fetch pages.
... | [
"def",
"_fetch_pages",
"(",
"self",
",",
"item_type",
",",
"items_key",
",",
"request_path",
",",
"startAt",
"=",
"0",
",",
"maxResults",
"=",
"50",
",",
"params",
"=",
"None",
",",
"base",
"=",
"JIRA_BASE_URL",
",",
")",
":",
"async_class",
"=",
"None",... | 48.228571 | 21.409524 |
def mod(self):
""" Cached compiled binary of the Generic_Code class.
To clear cache invoke :meth:`clear_mod_cache`.
"""
if self._mod is None:
self._mod = self.compile_and_import_binary()
return self._mod | [
"def",
"mod",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mod",
"is",
"None",
":",
"self",
".",
"_mod",
"=",
"self",
".",
"compile_and_import_binary",
"(",
")",
"return",
"self",
".",
"_mod"
] | 31.125 | 15.375 |
def logged_delete(self, user):
"""Delete the document and log the event in the change log"""
self.delete()
# Log the change
entry = ChangeLogEntry({
'type': 'DELETED',
'documents': [self],
'user': user
})
entry.insert()
r... | [
"def",
"logged_delete",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"delete",
"(",
")",
"# Log the change",
"entry",
"=",
"ChangeLogEntry",
"(",
"{",
"'type'",
":",
"'DELETED'",
",",
"'documents'",
":",
"[",
"self",
"]",
",",
"'user'",
":",
"user",
... | 22.714286 | 19.357143 |
def _compute_follow(self):
"""Computes the FOLLOW set for every non-terminal in the grammar.
Tenatively based on _compute_follow in PLY.
"""
self._follow[self.start_symbol].add(END_OF_INPUT)
while True:
changed = False
for nonterminal, productions in se... | [
"def",
"_compute_follow",
"(",
"self",
")",
":",
"self",
".",
"_follow",
"[",
"self",
".",
"start_symbol",
"]",
".",
"add",
"(",
"END_OF_INPUT",
")",
"while",
"True",
":",
"changed",
"=",
"False",
"for",
"nonterminal",
",",
"productions",
"in",
"self",
"... | 37.814815 | 21.666667 |
def _get_callers(items, stage, special_cases=False):
"""Retrieve available callers for the provided stage.
Handles special cases like CNVkit that can be in initial or standard
depending on if fed into Lumpy analysis.
"""
callers = utils.deepish_copy(_CALLERS[stage])
if special_cases and "cnvkit... | [
"def",
"_get_callers",
"(",
"items",
",",
"stage",
",",
"special_cases",
"=",
"False",
")",
":",
"callers",
"=",
"utils",
".",
"deepish_copy",
"(",
"_CALLERS",
"[",
"stage",
"]",
")",
"if",
"special_cases",
"and",
"\"cnvkit\"",
"in",
"callers",
":",
"has_l... | 43.294118 | 16.823529 |
def nonlocal_packages_path(self):
"""Returns package search paths with local path removed."""
paths = self.packages_path[:]
if self.local_packages_path in paths:
paths.remove(self.local_packages_path)
return paths | [
"def",
"nonlocal_packages_path",
"(",
"self",
")",
":",
"paths",
"=",
"self",
".",
"packages_path",
"[",
":",
"]",
"if",
"self",
".",
"local_packages_path",
"in",
"paths",
":",
"paths",
".",
"remove",
"(",
"self",
".",
"local_packages_path",
")",
"return",
... | 42 | 7.5 |
def is_cpf(numero, estrito=False):
"""Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caract... | [
"def",
"is_cpf",
"(",
"numero",
",",
"estrito",
"=",
"False",
")",
":",
"try",
":",
"cpf",
"(",
"digitos",
"(",
"numero",
")",
"if",
"not",
"estrito",
"else",
"numero",
")",
"return",
"True",
"except",
"NumeroCPFError",
":",
"pass",
"return",
"False"
] | 36 | 23 |
def load_strain(self, strain_id, strain_genome_file):
"""Load a strain as a new GEM-PRO by its ID and associated genome file. Stored in the ``strains`` attribute.
Args:
strain_id (str): Strain ID
strain_genome_file (str): Path to strain genome file
"""
# logging... | [
"def",
"load_strain",
"(",
"self",
",",
"strain_id",
",",
"strain_genome_file",
")",
":",
"# logging.disable(logging.WARNING)",
"strain_gp",
"=",
"GEMPRO",
"(",
"gem_name",
"=",
"strain_id",
",",
"genome_path",
"=",
"strain_genome_file",
",",
"write_protein_fasta_files"... | 41.071429 | 19.285714 |
def cached(
cls,
release=MAX_ENSEMBL_RELEASE,
species=human,
server=ENSEMBL_FTP_SERVER):
"""
Construct EnsemblRelease if it's never been made before, otherwise
return an old instance.
"""
init_args_tuple = cls.normalize_init_values(... | [
"def",
"cached",
"(",
"cls",
",",
"release",
"=",
"MAX_ENSEMBL_RELEASE",
",",
"species",
"=",
"human",
",",
"server",
"=",
"ENSEMBL_FTP_SERVER",
")",
":",
"init_args_tuple",
"=",
"cls",
".",
"normalize_init_values",
"(",
"release",
",",
"species",
",",
"server... | 36.8 | 17.066667 |
def name_tree(tree):
"""
Names all the tree nodes that are not named or have non-unique names, with unique names.
:param tree: tree to be named
:type tree: ete3.Tree
:return: void, modifies the original tree
"""
existing_names = Counter((_.name for _ in tree.traverse() if _.name))
if s... | [
"def",
"name_tree",
"(",
"tree",
")",
":",
"existing_names",
"=",
"Counter",
"(",
"(",
"_",
".",
"name",
"for",
"_",
"in",
"tree",
".",
"traverse",
"(",
")",
"if",
"_",
".",
"name",
")",
")",
"if",
"sum",
"(",
"1",
"for",
"_",
"in",
"tree",
"."... | 35.142857 | 20.571429 |
def _is_compatible_with(self, other):
"""
Return True if names are not incompatible.
This checks that the gender of titles and compatibility of suffixes
"""
title = self._compare_title(other)
suffix = self._compare_suffix(other)
return title and suffix | [
"def",
"_is_compatible_with",
"(",
"self",
",",
"other",
")",
":",
"title",
"=",
"self",
".",
"_compare_title",
"(",
"other",
")",
"suffix",
"=",
"self",
".",
"_compare_suffix",
"(",
"other",
")",
"return",
"title",
"and",
"suffix"
] | 27.363636 | 16.636364 |
def remove_context(self, name):
"""Remove a context from kubeconfig.
"""
context = self.get_context(name)
contexts = self.get_contexts()
contexts.remove(context) | [
"def",
"remove_context",
"(",
"self",
",",
"name",
")",
":",
"context",
"=",
"self",
".",
"get_context",
"(",
"name",
")",
"contexts",
"=",
"self",
".",
"get_contexts",
"(",
")",
"contexts",
".",
"remove",
"(",
"context",
")"
] | 32.666667 | 3.166667 |
def congestion(self):
"""Retrieves the congestion information of the incident/incidents from
the output response
Returns:
congestion(namedtuple): List of named tuples of congestion info of
the incident/incidents
"""
resource_list = self.traffic_incident()... | [
"def",
"congestion",
"(",
"self",
")",
":",
"resource_list",
"=",
"self",
".",
"traffic_incident",
"(",
")",
"congestion",
"=",
"namedtuple",
"(",
"'congestion'",
",",
"'congestion'",
")",
"if",
"len",
"(",
"resource_list",
")",
"==",
"1",
"and",
"resource_l... | 38.5 | 16.909091 |
def _looks_like_lru_cache(node):
"""Check if the given function node is decorated with lru_cache."""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Call):
continue
if _looks_like_functools_member(decorator... | [
"def",
"_looks_like_lru_cache",
"(",
"node",
")",
":",
"if",
"not",
"node",
".",
"decorators",
":",
"return",
"False",
"for",
"decorator",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"not",
"isinstance",
"(",
"decorator",
",",
"astroid",
".",... | 36.7 | 14 |
def makeCNBaseURL(url):
"""Attempt to create a valid CN BaseURL when one or more sections of the URL are
missing."""
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_CN_PROTOCOL)
if o.netloc and o.path:
netloc = o.netloc
path = o.path
elif o.netloc:
netloc = o.ne... | [
"def",
"makeCNBaseURL",
"(",
"url",
")",
":",
"o",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
",",
"scheme",
"=",
"d1_common",
".",
"const",
".",
"DEFAULT_CN_PROTOCOL",
")",
"if",
"o",
".",
"netloc",
"and",
"o",
".",
"path",
":",
"netl... | 32.434783 | 16.304348 |
def get_bboxes(
img,
mask,
nb_boxes=100,
score_thresh=0.5,
iou_thresh=0.2,
prop_size=0.09,
prop_scale=1.2,
):
"""
Uses selective search to generate candidate bounding boxes and keeps the
ones that have the largest iou with the predicted mask.
:param img: original image
:... | [
"def",
"get_bboxes",
"(",
"img",
",",
"mask",
",",
"nb_boxes",
"=",
"100",
",",
"score_thresh",
"=",
"0.5",
",",
"iou_thresh",
"=",
"0.2",
",",
"prop_size",
"=",
"0.09",
",",
"prop_scale",
"=",
"1.2",
",",
")",
":",
"min_size",
"=",
"int",
"(",
"img"... | 37.470588 | 17.588235 |
def init():
"""Initiates a new website"""
print("Blended: Static Website Generator -\n")
checkConfig()
if (sys.version_info > (3, 0)):
wname = input("Website Name: ")
wdesc = input("Website Description: ")
wlan = input("Website Language: ")
wlic = input("Website Licens... | [
"def",
"init",
"(",
")",
":",
"print",
"(",
"\"Blended: Static Website Generator -\\n\"",
")",
"checkConfig",
"(",
")",
"if",
"(",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
")",
":",
"wname",
"=",
"input",
"(",
"\"Website Name: \"",
")",
... | 31.518519 | 17.407407 |
def new_max_pool(self, name:str, kernel_size: tuple, stride_size: tuple, padding='SAME',
input_layer_name: str=None):
"""
Creates a new max pooling layer.
:param name: name for the layer.
:param kernel_size: tuple containing the size of the kernel (Width, Height)
... | [
"def",
"new_max_pool",
"(",
"self",
",",
"name",
":",
"str",
",",
"kernel_size",
":",
"tuple",
",",
"stride_size",
":",
"tuple",
",",
"padding",
"=",
"'SAME'",
",",
"input_layer_name",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"__validate_padding",
... | 46.782609 | 24.956522 |
def run( self ):
"""Run the experiment, using the parameters set using :meth:`set`.
A "run" consists of calling :meth:`setUp`, :meth:`do`, and :meth:`tearDown`,
followed by collecting and storing (and returning) the
experiment's results. If running the experiment raises an
except... | [
"def",
"run",
"(",
"self",
")",
":",
"# perform the experiment protocol",
"params",
"=",
"self",
".",
"parameters",
"(",
")",
"self",
".",
"_metadata",
"=",
"dict",
"(",
")",
"self",
".",
"_results",
"=",
"None",
"res",
"=",
"None",
"doneSetupTime",
"=",
... | 43.730159 | 18.825397 |
def convert_to_jbig2(pike, jbig2_groups, root, log, options):
"""Convert images to JBIG2 and insert into PDF.
When the JBIG2 page group size is > 1 we do several JBIG2 images at once
and build a symbol dictionary that will span several pages. Each JBIG2
image must reference to its symbol dictionary. If... | [
"def",
"convert_to_jbig2",
"(",
"pike",
",",
"jbig2_groups",
",",
"root",
",",
"log",
",",
"options",
")",
":",
"_produce_jbig2_images",
"(",
"jbig2_groups",
",",
"root",
",",
"log",
",",
"options",
")",
"for",
"group",
",",
"xref_exts",
"in",
"jbig2_groups"... | 45.805556 | 22.638889 |
def get_front_page(self, *args, **kwargs):
"""Return a get_content generator for the front page submissions.
Corresponds to the submissions provided by ``https://www.reddit.com/``
for the session.
The additional parameters are passed directly into
:meth:`.get_content`. Note: th... | [
"def",
"get_front_page",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_content",
"(",
"self",
".",
"config",
"[",
"'reddit_url'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 39.545455 | 23.909091 |
def accept(self):
"""accept() -> (socket object, address info)
Wait for an incoming connection. Return a new socket
representing the connection, and the address of the client.
For IP sockets, the address info is a pair (hostaddr, port).
"""
fd, addr = self._accept()
... | [
"def",
"accept",
"(",
"self",
")",
":",
"fd",
",",
"addr",
"=",
"self",
".",
"_accept",
"(",
")",
"sock",
"=",
"socket",
"(",
"self",
".",
"family",
",",
"self",
".",
"type",
",",
"self",
".",
"proto",
",",
"fileno",
"=",
"fd",
")",
"# Issue #799... | 47.4 | 20.666667 |
def get_host_ip(self, env_with_dig='ingi/inginious-c-default'):
"""
Get the external IP of the host of the docker daemon. Uses OpenDNS internally.
:param env_with_dig: any container image that has dig
"""
try:
container = self._docker.containers.create(env_with_dig, c... | [
"def",
"get_host_ip",
"(",
"self",
",",
"env_with_dig",
"=",
"'ingi/inginious-c-default'",
")",
":",
"try",
":",
"container",
"=",
"self",
".",
"_docker",
".",
"containers",
".",
"create",
"(",
"env_with_dig",
",",
"command",
"=",
"\"dig +short myip.opendns.com @r... | 49.666667 | 26.466667 |
def get_parser_class():
"""
Returns the parser according to the system platform
"""
global distro
if distro == 'Linux':
Parser = parser.LinuxParser
if not os.path.exists(Parser.get_command()[0]):
Parser = parser.UnixIPParser
elif distro in ['Darwin', 'MacOSX']:
... | [
"def",
"get_parser_class",
"(",
")",
":",
"global",
"distro",
"if",
"distro",
"==",
"'Linux'",
":",
"Parser",
"=",
"parser",
".",
"LinuxParser",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"Parser",
".",
"get_command",
"(",
")",
"[",
"0",
"]",
... | 33.045455 | 12.590909 |
def register(self, metadata):
"""
Register a distribution on PyPI, using the provided metadata.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the distribution to be
registered.
:return: The... | [
"def",
"register",
"(",
"self",
",",
"metadata",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"metadata",
".",
"validate",
"(",
")",
"d",
"=",
"metadata",
".",
"todict",
"(",
")",
"d",
"[",
"':action'",
"]",
"=",
"'verify'",
"request",
"=",
... | 39.157895 | 14.947368 |
def get_s3_multipart_chunk_size(filesize):
"""Returns the chunk size of the S3 multipart object, given a file's size."""
if filesize <= AWS_MAX_MULTIPART_COUNT * AWS_MIN_CHUNK_SIZE:
return AWS_MIN_CHUNK_SIZE
else:
div = filesize // AWS_MAX_MULTIPART_COUNT
if div * AWS_MAX_MULTIPART_C... | [
"def",
"get_s3_multipart_chunk_size",
"(",
"filesize",
")",
":",
"if",
"filesize",
"<=",
"AWS_MAX_MULTIPART_COUNT",
"*",
"AWS_MIN_CHUNK_SIZE",
":",
"return",
"AWS_MIN_CHUNK_SIZE",
"else",
":",
"div",
"=",
"filesize",
"//",
"AWS_MAX_MULTIPART_COUNT",
"if",
"div",
"*",
... | 43.888889 | 12.222222 |
def validate(self):
"""
validates the feature configuration, and returns a list of errors (empty list if no error)
validate should:
* required variables
* warn on unused variables
errors should either be reported via self._log_error(), or raise an exception
"""... | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"self",
".",
"target",
":",
"for",
"k",
"in",
"self",
".",
"target",
".",
"keys",
"(",
")",
":",
"if",
"k",
"in",
"self",
".",
"deprecated_options",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"se... | 43.478261 | 23.304348 |
def get(self, timeout=None):
"""
Return value on success, or raise exception on failure.
"""
result = None
try:
result = self._result.get(True, timeout=timeout)
except Empty:
raise Timeout()
if isinstance(result, Failure):
six.... | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"self",
".",
"_result",
".",
"get",
"(",
"True",
",",
"timeout",
"=",
"timeout",
")",
"except",
"Empty",
":",
"raise",
"Timeout",
"(... | 26.571429 | 15.571429 |
def acquisition_function(self, x):
"""
Returns the value of the acquisition function at x.
"""
return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0) | [
"def",
"acquisition_function",
"(",
"self",
",",
"x",
")",
":",
"return",
"self",
".",
"_penalized_acquisition",
"(",
"x",
",",
"self",
".",
"model",
",",
"self",
".",
"X_batch",
",",
"self",
".",
"r_x0",
",",
"self",
".",
"s_x0",
")"
] | 34.666667 | 19.666667 |
def generate_lines_for_vocab(tmp_dir, sources, file_byte_budget=1e6):
"""Generate lines for vocabulary generation."""
tf.logging.info("Generating vocab from: %s", str(sources))
for source in sources:
url = source[0]
filename = os.path.basename(url)
compressed_file = maybe_download(tmp_dir, filename, u... | [
"def",
"generate_lines_for_vocab",
"(",
"tmp_dir",
",",
"sources",
",",
"file_byte_budget",
"=",
"1e6",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Generating vocab from: %s\"",
",",
"str",
"(",
"sources",
")",
")",
"for",
"source",
"in",
"sources",
... | 37.674419 | 16.72093 |
def prepare_package(err, path, expectation=0, for_appversions=None,
timeout=-1):
"""Prepares a file-based package for validation.
timeout is the number of seconds before validation is aborted.
If timeout is -1 then no timeout checking code will run.
"""
package = None
try:
... | [
"def",
"prepare_package",
"(",
"err",
",",
"path",
",",
"expectation",
"=",
"0",
",",
"for_appversions",
"=",
"None",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"package",
"=",
"None",
"try",
":",
"# Test that the package actually exists. I consider this Tier 0",
... | 37.742424 | 20.787879 |
def _real_re_compile(self, *args, **kwargs):
"""Thunk over to the original re.compile"""
try:
return re.compile(*args, **kwargs)
except re.error as e:
# raise ValueError instead of re.error as this gives a
# cleaner message to the user.
raise Value... | [
"def",
"_real_re_compile",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"re",
".",
"compile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"re",
".",
"error",
"as",
"e",
":",
"# raise ValueErr... | 43.625 | 12 |
def __set_lost_start_status(self, hgvs_string):
"""Sets the self.is_lost_start flag."""
# set is lost start status
mymatch = re.search('^([A-Z?])(\d+)([A-Z?])$', hgvs_string)
if mymatch:
grps = mymatch.groups()
if int(grps[1]) == 1 and grps[0] != grps[2]:
... | [
"def",
"__set_lost_start_status",
"(",
"self",
",",
"hgvs_string",
")",
":",
"# set is lost start status",
"mymatch",
"=",
"re",
".",
"search",
"(",
"'^([A-Z?])(\\d+)([A-Z?])$'",
",",
"hgvs_string",
")",
"if",
"mymatch",
":",
"grps",
"=",
"mymatch",
".",
"groups",... | 38.230769 | 10.615385 |
def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
java = SubprocessExecutor(self._distribution)
subproc = java.spawn(classpath=classpath,
main='com.martiansoftware.nailgun.NGServer',
... | [
"def",
"post_fork_child",
"(",
"self",
",",
"fingerprint",
",",
"jvm_options",
",",
"classpath",
",",
"stdout",
",",
"stderr",
")",
":",
"java",
"=",
"SubprocessExecutor",
"(",
"self",
".",
"_distribution",
")",
"subproc",
"=",
"java",
".",
"spawn",
"(",
"... | 46.928571 | 17.857143 |
def add_defaults(self, ctype: ContentType = None) -> "InstanceNode":
"""Return the receiver with defaults added recursively to its value.
Args:
ctype: Content type of the defaults to be added. If it is
``None``, the content type will be the same as receiver's.
"""
... | [
"def",
"add_defaults",
"(",
"self",
",",
"ctype",
":",
"ContentType",
"=",
"None",
")",
"->",
"\"InstanceNode\"",
":",
"val",
"=",
"self",
".",
"value",
"if",
"not",
"(",
"isinstance",
"(",
"val",
",",
"StructuredValue",
")",
"and",
"self",
".",
"is_inte... | 36.321429 | 17.785714 |
def page_context(request, site, **criterias):
'Returns the context dictionary for a page view.'
try: page = int(request.GET.get('page', 1))
except ValueError: page = 1
feed, tag = criterias.get('feed'), criterias.get('tag')
if feed:
try: feed = models.Feed.objects.get(pk=feed)
except ObjectDoesNotExist: raise... | [
"def",
"page_context",
"(",
"request",
",",
"site",
",",
"*",
"*",
"criterias",
")",
":",
"try",
":",
"page",
"=",
"int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'page'",
",",
"1",
")",
")",
"except",
"ValueError",
":",
"page",
"=",
"1",
"f... | 33.6 | 18.025 |
def clear_terminal(self):
"""Reimplement ShellBaseWidget method"""
self.clear()
self.new_prompt(self.interpreter.p2 if self.interpreter.more else self.interpreter.p1) | [
"def",
"clear_terminal",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"new_prompt",
"(",
"self",
".",
"interpreter",
".",
"p2",
"if",
"self",
".",
"interpreter",
".",
"more",
"else",
"self",
".",
"interpreter",
".",
"p1",
")"
] | 47.5 | 21.75 |
def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode='reservoir'):
"""Run the given statement a number of times and return the runtime stats
Args... | [
"def",
"timeit",
"(",
"hosts",
"=",
"None",
",",
"stmt",
"=",
"None",
",",
"warmup",
"=",
"30",
",",
"repeat",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"concurrency",
"=",
"1",
",",
"output_fmt",
"=",
"None",
",",
"fail_if",
"=",
"None",
","... | 34.372093 | 16.139535 |
def process(self, metric):
"""
Queue a metric. Flushing queue if batch size reached
"""
if self._match_metric(metric):
self.metrics.append(metric)
if self.should_flush():
self._send() | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"if",
"self",
".",
"_match_metric",
"(",
"metric",
")",
":",
"self",
".",
"metrics",
".",
"append",
"(",
"metric",
")",
"if",
"self",
".",
"should_flush",
"(",
")",
":",
"self",
".",
"_send",
... | 30.125 | 7.875 |
def get_main_chain_layers(self):
"""Return a list of layer IDs in the main chain."""
main_chain = self.get_main_chain()
ret = []
for u in main_chain:
for v, layer_id in self.adj_list[u]:
if v in main_chain and u in main_chain:
ret.append(la... | [
"def",
"get_main_chain_layers",
"(",
"self",
")",
":",
"main_chain",
"=",
"self",
".",
"get_main_chain",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"u",
"in",
"main_chain",
":",
"for",
"v",
",",
"layer_id",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]",
"... | 37.555556 | 10.111111 |
def vote_least_worst(candidates, votes, n_winners):
"""Select "least worst" artifact as the winner of the vote.
Least worst artifact is the artifact with the best worst evaluation, i.e.
its worst evaluation is the best among all of the artifacts.
Ties are resolved randomly.
:param candidates: All... | [
"def",
"vote_least_worst",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"worsts",
"=",
"{",
"str",
"(",
"c",
")",
":",
"100000000.0",
"for",
"c",
"in",
"candidates",
"}",
"for",
"v",
"in",
"votes",
":",
"for",
"e",
"in",
"v",
":",
"... | 33.92 | 16.64 |
def get_year(self):
"""
Return the year from the database in the format expected by the URL.
"""
year = super(BuildableDayArchiveView, self).get_year()
fmt = self.get_year_format()
dt = date(int(year), 1, 1)
return dt.strftime(fmt) | [
"def",
"get_year",
"(",
"self",
")",
":",
"year",
"=",
"super",
"(",
"BuildableDayArchiveView",
",",
"self",
")",
".",
"get_year",
"(",
")",
"fmt",
"=",
"self",
".",
"get_year_format",
"(",
")",
"dt",
"=",
"date",
"(",
"int",
"(",
"year",
")",
",",
... | 35 | 12.25 |
def load(self, loc):
'''Load a pickled model.'''
try:
w_td_c = pickle.load(open(loc, 'rb'))
except IOError:
msg = ("Missing trontagger.pickle file.")
raise MissingCorpusError(msg)
self.model.weights, self.tagdict, self.classes = w_td_c
self.mod... | [
"def",
"load",
"(",
"self",
",",
"loc",
")",
":",
"try",
":",
"w_td_c",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"loc",
",",
"'rb'",
")",
")",
"except",
"IOError",
":",
"msg",
"=",
"(",
"\"Missing trontagger.pickle file.\"",
")",
"raise",
"Missing... | 35.6 | 13.8 |
def deluser(name, username):
'''
Remove a user from the group.
CLI Example:
.. code-block:: bash
salt '*' group.deluser foo bar
Removes a member user 'bar' from a group 'foo'. If group is not present
then returns True.
'''
grp_info = __salt__['group.info'](name)
if user... | [
"def",
"deluser",
"(",
"name",
",",
"username",
")",
":",
"grp_info",
"=",
"__salt__",
"[",
"'group.info'",
"]",
"(",
"name",
")",
"if",
"username",
"not",
"in",
"grp_info",
"[",
"'members'",
"]",
":",
"return",
"True",
"# Note: pw exits with code 65 if group ... | 23.695652 | 23.956522 |
def alltoall_ring(xs, devices, split_axis, concat_axis):
"""MPI alltoall operation.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of n strings
split_axis: an integer
concat_axis: an integer
Returns:
a list of n Tensors
"""
n = len(xs)
... | [
"def",
"alltoall_ring",
"(",
"xs",
",",
"devices",
",",
"split_axis",
",",
"concat_axis",
")",
":",
"n",
"=",
"len",
"(",
"xs",
")",
"if",
"n",
"==",
"1",
":",
"return",
"xs",
"# set up",
"# [target, source]",
"parts",
"=",
"[",
"[",
"None",
"]",
"*"... | 35.932203 | 16.898305 |
def unicode_csv_reader(unicode_csv_data, **kwargs):
"""Since the standard csv library does not handle unicode in Python 2, we need a wrapper.
Borrowed and slightly modified from the Python docs:
https://docs.python.org/2/library/csv.html#csv-examples"""
if six.PY2:
# csv.py doesn't do Unicode; e... | [
"def",
"unicode_csv_reader",
"(",
"unicode_csv_data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# csv.py doesn't do Unicode; encode temporarily as UTF-8:",
"csv_reader",
"=",
"csv",
".",
"reader",
"(",
"utf_8_encoder",
"(",
"unicode_csv_data",
... | 49.923077 | 17.076923 |
def tcl_add_fileset_file(filename: str):
"""
:param filename: relative filename with .vhdl or .v
:return: add_fileset_file command string
"""
if filename.endswith(".vhd"):
t = "VHDL"
elif filename.endswith(".v") or filename.endswith(".sv"):
t = "VERILOG"
else:
raise ... | [
"def",
"tcl_add_fileset_file",
"(",
"filename",
":",
"str",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"\".vhd\"",
")",
":",
"t",
"=",
"\"VHDL\"",
"elif",
"filename",
".",
"endswith",
"(",
"\".v\"",
")",
"or",
"filename",
".",
"endswith",
"(",
"\"... | 30.5625 | 16.6875 |
def set_hparam(self, name, value):
"""Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError:... | [
"def",
"set_hparam",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"param_type",
",",
"is_list",
"=",
"self",
".",
"_hparam_types",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"not",
"is_list",
":",
"raise",
"... | 34.692308 | 20.461538 |
def get_all_conversion_chains_from_type(self, from_type: Type[Any]) \
-> Tuple[List[Converter], List[Converter], List[Converter]]:
"""
Utility method to find all converters from a given type.
:param from_type:
:return:
"""
return self.get_all_conversion_chain... | [
"def",
"get_all_conversion_chains_from_type",
"(",
"self",
",",
"from_type",
":",
"Type",
"[",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Converter",
"]",
",",
"List",
"[",
"Converter",
"]",
",",
"List",
"[",
"Converter",
"]",
"]",
":",
"return",... | 37.111111 | 21.111111 |
def read(path, saltenv='base'):
'''
Read the contents of a text file, if the file is binary then
'''
# Return a dict of paths + content
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
... | [
"def",
"read",
"(",
"path",
",",
"saltenv",
"=",
"'base'",
")",
":",
"# Return a dict of paths + content",
"ret",
"=",
"[",
"]",
"files",
"=",
"find",
"(",
"path",
",",
"saltenv",
")",
"for",
"fn_",
"in",
"files",
":",
"full",
"=",
"next",
"(",
"six",
... | 30.5 | 19 |
def _alert_malformed(self, msg, row_num):
"""
Alert a user about a malformed row.
If `self.error_bad_lines` is True, the alert will be `ParserError`.
If `self.warn_bad_lines` is True, the alert will be printed out.
Parameters
----------
msg : The error message t... | [
"def",
"_alert_malformed",
"(",
"self",
",",
"msg",
",",
"row_num",
")",
":",
"if",
"self",
".",
"error_bad_lines",
":",
"raise",
"ParserError",
"(",
"msg",
")",
"elif",
"self",
".",
"warn_bad_lines",
":",
"base",
"=",
"'Skipping line {row_num}: '",
".",
"fo... | 36.65 | 18.05 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.