text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def draw_3d(self, width=300, height=500, style='stick', Hs=True): # pragma: no cover
r'''Interface for drawing an interactive 3D view of the molecule.
Requires an HTML5 browser, and the libraries RDKit, pymol3D, and
IPython. An exception is raised if all three of these libraries are
not ... | [
"def",
"draw_3d",
"(",
"self",
",",
"width",
"=",
"300",
",",
"height",
"=",
"500",
",",
"style",
"=",
"'stick'",
",",
"Hs",
"=",
"True",
")",
":",
"# pragma: no cover",
"try",
":",
"import",
"py3Dmol",
"from",
"IPython",
".",
"display",
"import",
"dis... | 34.078947 | 0.006006 |
def tax_ids(self):
'''
Return all tax_ids in node table
'''
fetch = select([self.nodes.c.tax_id]).execute().fetchall()
ids = [t[0] for t in fetch]
return ids | [
"def",
"tax_ids",
"(",
"self",
")",
":",
"fetch",
"=",
"select",
"(",
"[",
"self",
".",
"nodes",
".",
"c",
".",
"tax_id",
"]",
")",
".",
"execute",
"(",
")",
".",
"fetchall",
"(",
")",
"ids",
"=",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
... | 28.428571 | 0.009756 |
def process_line(self, dirname, line):
"""
Processes a line return a 3-element tuple representing (filename,
line_number, error_messages) or None to indicate no error.
:param: dirname - directory the code is running in
For default implementation, regex in `self.response_format`... | [
"def",
"process_line",
"(",
"self",
",",
"dirname",
",",
"line",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'response_format'",
")",
":",
"raise",
"NotImplementedError",
"(",
")",
"match",
"=",
"self",
".",
"response_format",
".",
"search",
"(",
... | 39.952381 | 0.002328 |
def cli(env, identifier, columns):
"""Reserved Capacity Group details. Will show which guests are assigned to a reservation."""
manager = CapacityManager(env.client)
mask = """mask[instances[id,createDate,guestId,billingItem[id, description, recurringFee, category[name]],
guest[modifyDate,id,... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"columns",
")",
":",
"manager",
"=",
"CapacityManager",
"(",
"env",
".",
"client",
")",
"mask",
"=",
"\"\"\"mask[instances[id,createDate,guestId,billingItem[id, description, recurringFee, category[name]],\n guest[... | 44.454545 | 0.006006 |
def reload(self):
"""Reloads the current model's data from the underlying
database record, updating it in-place."""
self.emit('will_reload')
self.populate(self.collection.find_one(type(self)._id_spec(self['_id'])))
self.emit('did_reload') | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"emit",
"(",
"'will_reload'",
")",
"self",
".",
"populate",
"(",
"self",
".",
"collection",
".",
"find_one",
"(",
"type",
"(",
"self",
")",
".",
"_id_spec",
"(",
"self",
"[",
"'_id'",
"]",
")",
"... | 45.5 | 0.010791 |
def plot_contours(self, grid, filled=True, ax=None, labels=None,
subplots_kw=dict(), **kwargs):
"""
Plot equipotentials contours. Computes the potential energy on a grid
(specified by the array `grid`).
.. warning:: Right now the grid input must be arrays and must ... | [
"def",
"plot_contours",
"(",
"self",
",",
"grid",
",",
"filled",
"=",
"True",
",",
"ax",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"subplots_kw",
"=",
"dict",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"... | 32.411765 | 0.002348 |
def _connect(self, address):
"""Connect to a device given its uuid
"""
latency = 0
conn_interval_min = 6
conn_interval_max = 100
timeout = 1.0
try:
#Allow passing either a binary address or a hex string
if isinstance(address, str) and len... | [
"def",
"_connect",
"(",
"self",
",",
"address",
")",
":",
"latency",
"=",
"0",
"conn_interval_min",
"=",
"6",
"conn_interval_max",
"=",
"100",
"timeout",
"=",
"1.0",
"try",
":",
"#Allow passing either a binary address or a hex string",
"if",
"isinstance",
"(",
"ad... | 38.230769 | 0.006376 |
def filter_with_schema(self, model=None, context=None):
""" Perform model filtering with schema """
if model is None or self.schema is None:
return
self._schema.filter(
model=model,
context=context if self.use_context else None
) | [
"def",
"filter_with_schema",
"(",
"self",
",",
"model",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"model",
"is",
"None",
"or",
"self",
".",
"schema",
"is",
"None",
":",
"return",
"self",
".",
"_schema",
".",
"filter",
"(",
"model",
"=... | 32.222222 | 0.006711 |
def is_fw_complete(self):
"""This API returns the completion status of FW.
This returns True if a FW is created with a active policy that has
more than one rule associated with it and if a driver init is done
successfully.
"""
LOG.info("In fw_complete needed %(fw_created... | [
"def",
"is_fw_complete",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"\"In fw_complete needed %(fw_created)s \"",
"\"%(active_policy_id)s %(is_fw_drvr_created)s \"",
"\"%(pol_present)s %(fw_type)s\"",
",",
"{",
"'fw_created'",
":",
"self",
".",
"fw_created",
",",
"'acti... | 51.307692 | 0.001472 |
def WritePathStatHistory(self, client_path, stat_entries):
"""Writes a collection of `StatEntry` observed for particular path.
Args:
client_path: A `ClientPath` instance.
stat_entries: A dictionary with timestamps as keys and `StatEntry`
instances as values.
"""
client_path_history ... | [
"def",
"WritePathStatHistory",
"(",
"self",
",",
"client_path",
",",
"stat_entries",
")",
":",
"client_path_history",
"=",
"ClientPathHistory",
"(",
")",
"for",
"timestamp",
",",
"stat_entry",
"in",
"iteritems",
"(",
"stat_entries",
")",
":",
"client_path_history",
... | 39.769231 | 0.003781 |
def _writeXput(self, session, directory, fileCards,
name=None, replaceParamFile=None):
"""
GSSHA Project Write Files to File Method
"""
for card in self.projectCards:
if (card.name in fileCards) and self._noneOrNumValue(card.value) \
and... | [
"def",
"_writeXput",
"(",
"self",
",",
"session",
",",
"directory",
",",
"fileCards",
",",
"name",
"=",
"None",
",",
"replaceParamFile",
"=",
"None",
")",
":",
"for",
"card",
"in",
"self",
".",
"projectCards",
":",
"if",
"(",
"card",
".",
"name",
"in",... | 45.964286 | 0.003044 |
def _monitor_pbc_status(self):
"""Monitor the PBC status."""
LOG.info('Starting to Monitor PBC status.')
inspect = celery.current_app.control.inspect()
workers = inspect.ping()
start_time = time.time()
while workers is None:
time.sleep(0.1)
elapsed... | [
"def",
"_monitor_pbc_status",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"'Starting to Monitor PBC status.'",
")",
"inspect",
"=",
"celery",
".",
"current_app",
".",
"control",
".",
"inspect",
"(",
")",
"workers",
"=",
"inspect",
".",
"ping",
"(",
")",
... | 42.228571 | 0.001323 |
def AddCommandLineArguments(
cls, argument_group, category=None, names=None):
"""Adds command line arguments to a configuration object.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse group.
category (Optional[str]): category of helpers to apply to
... | [
"def",
"AddCommandLineArguments",
"(",
"cls",
",",
"argument_group",
",",
"category",
"=",
"None",
",",
"names",
"=",
"None",
")",
":",
"# Process the helper classes in alphabetical order this is needed to",
"# keep the argument order consistent.",
"for",
"helper_name",
",",
... | 45.772727 | 0.003891 |
def p_pkg_cr_text_1(self, p):
"""pkg_cr_text : PKG_CPY_TEXT pkg_cr_text_value"""
try:
self.builder.set_pkg_cr_text(self.document, p[2])
except OrderError:
self.order_error('PackageCopyrightText', 'PackageFileName', p.lineno(1))
except CardinalityError:
... | [
"def",
"p_pkg_cr_text_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"self",
".",
"builder",
".",
"set_pkg_cr_text",
"(",
"self",
".",
"document",
",",
"p",
"[",
"2",
"]",
")",
"except",
"OrderError",
":",
"self",
".",
"order_error",
"(",
"'PackageCo... | 46.875 | 0.007853 |
def add_component(self, entity: int, component_instance: Any) -> None:
"""Add a new Component instance to an Entity.
Add a Component instance to an Entiy. If a Component of the same type
is already assigned to the Entity, it will be replaced.
:param entity: The Entity to associate the ... | [
"def",
"add_component",
"(",
"self",
",",
"entity",
":",
"int",
",",
"component_instance",
":",
"Any",
")",
"->",
"None",
":",
"component_type",
"=",
"type",
"(",
"component_instance",
")",
"if",
"component_type",
"not",
"in",
"self",
".",
"_components",
":"... | 36.714286 | 0.002528 |
def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str:
'''Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique stri... | [
"def",
"_unique_class_name",
"(",
"namespace",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"uuid",
":",
"uuid",
".",
"UUID",
")",
"->",
"str",
":",
"count",
"=",
"0",
"name",
"=",
"original_name",
"=",
"'f_'",
"+",
"uuid",
".",
"hex",
"while",
"... | 23.136364 | 0.001887 |
def ipfix():
"""Return a list of values from the list of IANA IP Flow Information Export
(IPFIX) Entities, or an empty list if the IANA website is unreachable.
Store it as a function attribute so that we only build the list once.
"""
if not hasattr(ipfix, 'ipflist'):
ilist = []
try:
... | [
"def",
"ipfix",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"ipfix",
",",
"'ipflist'",
")",
":",
"ilist",
"=",
"[",
"]",
"try",
":",
"data",
"=",
"requests",
".",
"get",
"(",
"'http://www.iana.org/assignments/ipfix/ipfix-'",
"'information-elements.csv'",
")",
... | 37.217391 | 0.001139 |
def send_media_file(self, filename):
"""
Function used to send media files from the media folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['MEDIA_FOLDER'], filename,
cache_tim... | [
"def",
"send_media_file",
"(",
"self",
",",
"filename",
")",
":",
"cache_timeout",
"=",
"self",
".",
"get_send_file_max_age",
"(",
"filename",
")",
"return",
"send_from_directory",
"(",
"self",
".",
"config",
"[",
"'MEDIA_FOLDER'",
"]",
",",
"filename",
",",
"... | 47.571429 | 0.0059 |
def calc_size_and_sha265(content: io.IOBase, chunk_size: int):
"""Calculates the size and the sha2566 value of the content."""
size = 0
sha256 = hashlib.sha256()
content.seek(0, io.SEEK_SET)
while True:
buf = content.read(chunk_size)
length = len(buf)
size += length
s... | [
"def",
"calc_size_and_sha265",
"(",
"content",
":",
"io",
".",
"IOBase",
",",
"chunk_size",
":",
"int",
")",
":",
"size",
"=",
"0",
"sha256",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"content",
".",
"seek",
"(",
"0",
",",
"io",
".",
"SEEK_SET",
")",
... | 31.692308 | 0.002358 |
def randomZ(maximum=None, bits=256):
"""
Retrieve a random BigInt.
@maximum: If specified, the value will be no larger than this modulus.
@bits: If no maximum is specified, the value will have @bits.
"""
result = BigInt()
# Select a random number smaller than the maximum.
if maximum:
... | [
"def",
"randomZ",
"(",
"maximum",
"=",
"None",
",",
"bits",
"=",
"256",
")",
":",
"result",
"=",
"BigInt",
"(",
")",
"# Select a random number smaller than the maximum.",
"if",
"maximum",
":",
"maximum",
"=",
"coerceBigInt",
"(",
"maximum",
")",
"librelic",
".... | 32.555556 | 0.003317 |
def attribute(path, name):
"""Returns the two numbers found behind --[A-Z] in path. If several matches
are found, the last one is returned.
Parameters
----------
path : string
String with path of file/folder to get attribute from.
name : string
Name of attribute to get. Should b... | [
"def",
"attribute",
"(",
"path",
",",
"name",
")",
":",
"matches",
"=",
"re",
".",
"findall",
"(",
"'--'",
"+",
"name",
".",
"upper",
"(",
")",
"+",
"'([0-9]{2})'",
",",
"path",
")",
"if",
"matches",
":",
"return",
"int",
"(",
"matches",
"[",
"-",
... | 27.727273 | 0.001585 |
def _get_mro(obj_class):
""" Get a reasonable method resolution order of a class and its superclasses
for both old-style and new-style classes.
"""
if not hasattr(obj_class, '__mro__'):
# Old-style class. Mix in object to make a fake new-style class.
try:
obj_class = type(obj... | [
"def",
"_get_mro",
"(",
"obj_class",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj_class",
",",
"'__mro__'",
")",
":",
"# Old-style class. Mix in object to make a fake new-style class.",
"try",
":",
"obj_class",
"=",
"type",
"(",
"obj_class",
".",
"__name__",
",",
"... | 38.058824 | 0.003017 |
def _parse_scram_response(response):
"""Split a scram response into key, value pairs."""
return dict(item.split(b"=", 1) for item in response.split(b",")) | [
"def",
"_parse_scram_response",
"(",
"response",
")",
":",
"return",
"dict",
"(",
"item",
".",
"split",
"(",
"b\"=\"",
",",
"1",
")",
"for",
"item",
"in",
"response",
".",
"split",
"(",
"b\",\"",
")",
")"
] | 53.333333 | 0.006173 |
def posterior_samples(self, X, size=10, Y_metadata=None, likelihood=None, **predict_kwargs):
"""
Samples the posterior GP at the points X.
:param X: the points at which to take the samples.
:type X: np.ndarray (Nnew x self.input_dim.)
:param size: the number of a posteriori samp... | [
"def",
"posterior_samples",
"(",
"self",
",",
"X",
",",
"size",
"=",
"10",
",",
"Y_metadata",
"=",
"None",
",",
"likelihood",
"=",
"None",
",",
"*",
"*",
"predict_kwargs",
")",
":",
"fsim",
"=",
"self",
".",
"posterior_samples_f",
"(",
"X",
",",
"size"... | 45.363636 | 0.005888 |
def update_collection(self, collection):
"""
Update a mongodb collection.
"""
node = self.node
flow = node if node.is_flow else node.flow
# Build the key used to store the entry in the document.
key = node.name
if node.is_task:
key = "w" + str... | [
"def",
"update_collection",
"(",
"self",
",",
"collection",
")",
":",
"node",
"=",
"self",
".",
"node",
"flow",
"=",
"node",
"if",
"node",
".",
"is_flow",
"else",
"node",
".",
"flow",
"# Build the key used to store the entry in the document.",
"key",
"=",
"node"... | 38.243902 | 0.002488 |
def check_time_extents(self, ds):
"""
Check that the values of time_coverage_start/time_coverage_end approximately match the data.
"""
if not (hasattr(ds, 'time_coverage_start') and hasattr(ds, 'time_coverage_end')):
return
# Parse the ISO 8601 formatted dates
... | [
"def",
"check_time_extents",
"(",
"self",
",",
"ds",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"ds",
",",
"'time_coverage_start'",
")",
"and",
"hasattr",
"(",
"ds",
",",
"'time_coverage_end'",
")",
")",
":",
"return",
"# Parse the ISO 8601 formatted dates",
... | 48.066667 | 0.005097 |
def add_deploy_key(self, auth, username, repo_name, title, key_content):
"""
Add a deploy key to the specified repo.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str repo_name: the name of the repo
:pa... | [
"def",
"add_deploy_key",
"(",
"self",
",",
"auth",
",",
"username",
",",
"repo_name",
",",
"title",
",",
"key_content",
")",
":",
"data",
"=",
"{",
"\"title\"",
":",
"title",
",",
"\"key\"",
":",
"key_content",
"}",
"response",
"=",
"self",
".",
"post",
... | 45 | 0.004353 |
def check(self, solution):
"""Check that a solution satisfies the constraint.
Args:
solution (container):
An assignment for the variables in the constraint.
Returns:
bool: True if the solution satisfies the constraint; otherwise False.
Examples:... | [
"def",
"check",
"(",
"self",
",",
"solution",
")",
":",
"return",
"self",
".",
"func",
"(",
"*",
"(",
"solution",
"[",
"v",
"]",
"for",
"v",
"in",
"self",
".",
"variables",
")",
")"
] | 36.037037 | 0.006006 |
def acos(x, context=None):
"""
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat ... | [
"def",
"acos",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_acos",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
... | 26.041667 | 0.001543 |
def _node_is_match(qualified_name, package_names, fqn):
"""Determine if a qualfied name matches an fqn, given the set of package
names in the graph.
:param List[str] qualified_name: The components of the selector or node
name, split on '.'.
:param Set[str] package_names: The set of pacakge name... | [
"def",
"_node_is_match",
"(",
"qualified_name",
",",
"package_names",
",",
"fqn",
")",
":",
"if",
"len",
"(",
"qualified_name",
")",
"==",
"1",
"and",
"fqn",
"[",
"-",
"1",
"]",
"==",
"qualified_name",
"[",
"0",
"]",
":",
"return",
"True",
"if",
"quali... | 36.772727 | 0.001205 |
def p_gate_op_4(self, program):
"""
gate_op : id '(' exp_list ')' id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[3], program[5]])
self.verify_as_gate(program[1], program[5], arglist=program[3])
self.verify_bit_list(program[5])
self.verify_exp... | [
"def",
"p_gate_op_4",
"(",
"self",
",",
"program",
")",
":",
"program",
"[",
"0",
"]",
"=",
"node",
".",
"CustomUnitary",
"(",
"[",
"program",
"[",
"1",
"]",
",",
"program",
"[",
"3",
"]",
",",
"program",
"[",
"5",
"]",
"]",
")",
"self",
".",
"... | 41.333333 | 0.005263 |
def fit(self):
"""Fit each distribution to `data` and calculate an SSE.
WARNING: significant runtime. (~1min)
"""
# Defaults/anchors
best_sse = np.inf
best_param = (0.0, 1.0)
best_dist = scs.norm
# Compute the histogram of `x`. density=True ... | [
"def",
"fit",
"(",
"self",
")",
":",
"# Defaults/anchors\r",
"best_sse",
"=",
"np",
".",
"inf",
"best_param",
"=",
"(",
"0.0",
",",
"1.0",
")",
"best_dist",
"=",
"scs",
".",
"norm",
"# Compute the histogram of `x`. density=True gives a probability\r",
"# density fu... | 33.428571 | 0.000923 |
def put(self, key, data, ttl_secs=None):
"""Like :meth:`~simplekv.KeyValueStore.put`, but with an additional
parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"data",
",",
"ttl_secs",
"=",
"None",
")",
":",
"self",
".",
"_check_valid_key",
"(",
"key",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"IOError",
"(",
"\"Provided data is n... | 43.333333 | 0.003012 |
def _set_axis_properties(self, axis):
"""Set AxisProperties and PropertySets"""
if not getattr(axis, 'properties'):
axis.properties = AxisProperties()
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks',
'title', 'labels']:
setattr(... | [
"def",
"_set_axis_properties",
"(",
"self",
",",
"axis",
")",
":",
"if",
"not",
"getattr",
"(",
"axis",
",",
"'properties'",
")",
":",
"axis",
".",
"properties",
"=",
"AxisProperties",
"(",
")",
"for",
"prop",
"in",
"[",
"'ticks'",
",",
"'axis'",
",",
... | 50.142857 | 0.005602 |
def parse_entry(self, entry):
"""This parses a VCF row and stores the relevant information"""
entry = entry.split('\t')
self.chrom, self.pos, self.id, self.ref, alt_, self.qual, filter_, info, self.format = entry[:9]
self.samples = entry[9:]
self.alt = alt_.split(',')
if ... | [
"def",
"parse_entry",
"(",
"self",
",",
"entry",
")",
":",
"entry",
"=",
"entry",
".",
"split",
"(",
"'\\t'",
")",
"self",
".",
"chrom",
",",
"self",
".",
"pos",
",",
"self",
".",
"id",
",",
"self",
".",
"ref",
",",
"alt_",
",",
"self",
".",
"q... | 40.583333 | 0.008024 |
def read_index(group, version='1.1'):
"""Return the index stored in a h5features group.
:param h5py.Group group: The group to read the index from.
:param str version: The h5features version of the `group`.
:return: a 1D numpy array of features indices.
"""
if version == '0.1':
return np... | [
"def",
"read_index",
"(",
"group",
",",
"version",
"=",
"'1.1'",
")",
":",
"if",
"version",
"==",
"'0.1'",
":",
"return",
"np",
".",
"int64",
"(",
"group",
"[",
"'index'",
"]",
"[",
"...",
"]",
")",
"elif",
"version",
"==",
"'1.0'",
":",
"return",
... | 34.384615 | 0.002179 |
def plot(self,**kwargs):
""" make a cheap plot of the GeoStruct
Parameters
----------
**kwargs : (dict)
keyword arguments to use for plotting.
Returns
-------
ax : matplotlib.pyplot.axis
the axis with the GeoStruct plot
Note
... | [
"def",
"plot",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"#",
"if",
"\"ax\"",
"in",
"kwargs",
":",
"ax",
"=",
"kwargs",
".",
"pop",
"(",
"\"ax\"",
")",
"else",
":",
"try",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"except",
"... | 29.395833 | 0.010288 |
def register_iq_request_coro(self, type_, payload_cls, coro):
"""
Alias of :meth:`register_iq_request_handler`.
.. deprecated:: 0.10
This alias will be removed in version 1.0.
"""
warnings.warn(
"register_iq_request_coro is a deprecated alias to "
... | [
"def",
"register_iq_request_coro",
"(",
"self",
",",
"type_",
",",
"payload_cls",
",",
"coro",
")",
":",
"warnings",
".",
"warn",
"(",
"\"register_iq_request_coro is a deprecated alias to \"",
"\"register_iq_request_handler and will be removed in aioxmpp 1.0\"",
",",
"Deprecati... | 36.428571 | 0.003824 |
def buildNewRootname(filename, extn=None, extlist=None):
"""
Build rootname for a new file.
Use 'extn' for new filename if given, does NOT append a suffix/extension at
all.
Does NOT check to see if it exists already. Will ALWAYS return a new
filename.
"""
# Search known suffixes to r... | [
"def",
"buildNewRootname",
"(",
"filename",
",",
"extn",
"=",
"None",
",",
"extlist",
"=",
"None",
")",
":",
"# Search known suffixes to replace ('_crj.fits',...)",
"_extlist",
"=",
"copy",
".",
"deepcopy",
"(",
"EXTLIST",
")",
"# Also, add a default where '_dth.fits' r... | 28.135135 | 0.0065 |
def unpack_di_block(di_block):
"""
This function unpacks a nested list of [dec,inc,mag_moment] into a list of
declination values, a list of inclination values and a list of magnetic
moment values. Mag_moment values are optional, while dec and inc values are
required.
Parameters
-----------
... | [
"def",
"unpack_di_block",
"(",
"di_block",
")",
":",
"dec_list",
"=",
"[",
"]",
"inc_list",
"=",
"[",
"]",
"moment_list",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"di_block",
")",
")",
":",
"dec",
"=",
"di_block",
"[",
... | 29.744186 | 0.001514 |
def dataset_download_files(self,
dataset,
path=None,
force=False,
quiet=True,
unzip=False):
""" download all files for a dataset
Parameters
... | [
"def",
"dataset_download_files",
"(",
"self",
",",
"dataset",
",",
"path",
"=",
"None",
",",
"force",
"=",
"False",
",",
"quiet",
"=",
"True",
",",
"unzip",
"=",
"False",
")",
":",
"if",
"dataset",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'A dat... | 38.580645 | 0.003261 |
def get_receptive_field(layers, img_size):
"""Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding ... | [
"def",
"get_receptive_field",
"(",
"layers",
",",
"img_size",
")",
":",
"receptive_field",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"layers",
")",
",",
"2",
")",
")",
"conv_mode",
"=",
"True",
"first_conv_layer",
"=",
"True",
"expon",
"=",
"np",
... | 35.055556 | 0.000771 |
def _send_int(self,value):
"""
Convert a numerical value into an integer, then to a bytes object Check
bounds for signed int.
"""
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_val... | [
"def",
"_send_int",
"(",
"self",
",",
"value",
")",
":",
"# Coerce to int. This will throw a ValueError if the value can't ",
"# actually be converted.",
"if",
"type",
"(",
"value",
")",
"!=",
"int",
":",
"new_value",
"=",
"int",
"(",
"value",
")",
"if",
"self",
"... | 35.090909 | 0.010088 |
def all(self, as_dict=False, as_ordereddict=False):
"""Returns a list of all rows for the RecordCollection. If they haven't
been fetched yet, consume the iterator and cache the results."""
# By calling list it calls the __iter__ method
rows = list(self)
if as_dict:
... | [
"def",
"all",
"(",
"self",
",",
"as_dict",
"=",
"False",
",",
"as_ordereddict",
"=",
"False",
")",
":",
"# By calling list it calls the __iter__ method",
"rows",
"=",
"list",
"(",
"self",
")",
"if",
"as_dict",
":",
"return",
"[",
"r",
".",
"as_dict",
"(",
... | 34.692308 | 0.00432 |
def make_aliased_type(cls, other_base):
"""
Factory for making Aliased{Filter,Factor,Classifier}.
"""
docstring = dedent(
"""
A {t} that names another {t}.
Parameters
----------
term : {t}
{{name}}
"""
... | [
"def",
"make_aliased_type",
"(",
"cls",
",",
"other_base",
")",
":",
"docstring",
"=",
"dedent",
"(",
"\"\"\"\n A {t} that names another {t}.\n\n Parameters\n ----------\n term : {t}\n {{name}}\n \"\"\"",
")",
".",
"form... | 25.851852 | 0.002762 |
def query_by_post(postid):
'''
Query records by post.
'''
return TabPost2Tag.select().where(
TabPost2Tag.post_id == postid
).order_by(TabPost2Tag.order) | [
"def",
"query_by_post",
"(",
"postid",
")",
":",
"return",
"TabPost2Tag",
".",
"select",
"(",
")",
".",
"where",
"(",
"TabPost2Tag",
".",
"post_id",
"==",
"postid",
")",
".",
"order_by",
"(",
"TabPost2Tag",
".",
"order",
")"
] | 28.285714 | 0.009804 |
def _update_recently_opened_state_machines(self):
"""Update the sub menu Open Recent in File menu
Method clean's first all menu items of the sub menu 'recent open', then insert the user menu item to clean
recent opened state machine paths and finally insert menu items for all elements in recent... | [
"def",
"_update_recently_opened_state_machines",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"registered_view",
":",
"return",
"for",
"item",
"in",
"self",
".",
"view",
".",
"sub_menu_open_recently",
".",
"get_children",
"(",
")",
":",
"self",
".",
"view"... | 53.108108 | 0.005997 |
def get_status(task, prefix, expnum, version, ccd, return_message=False):
"""
Report back status of the given program by looking up the associated VOSpace annotation.
@param task: name of the process or task that will be checked.
@param prefix: prefix of the file that was processed (often fk or None)
... | [
"def",
"get_status",
"(",
"task",
",",
"prefix",
",",
"expnum",
",",
"version",
",",
"ccd",
",",
"return_message",
"=",
"False",
")",
":",
"key",
"=",
"get_process_tag",
"(",
"prefix",
"+",
"task",
",",
"ccd",
",",
"version",
")",
"status",
"=",
"get_t... | 45.578947 | 0.003394 |
def _load_variants(self, variants, variant_type, case_obj, individual_positions, rank_threshold,
institute_id, build=None, rank_results_header=None, vep_header=None,
category='snv', sample_info = None):
"""Perform the loading of variants
This is the functio... | [
"def",
"_load_variants",
"(",
"self",
",",
"variants",
",",
"variant_type",
",",
"case_obj",
",",
"individual_positions",
",",
"rank_threshold",
",",
"institute_id",
",",
"build",
"=",
"None",
",",
"rank_results_header",
"=",
"None",
",",
"vep_header",
"=",
"Non... | 43.894737 | 0.00335 |
def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift *= 2
return max(4, n + 1) | [
"def",
"next_power_of_2",
"(",
"n",
")",
":",
"n",
"-=",
"1",
"# greater than OR EQUAL TO n",
"shift",
"=",
"1",
"while",
"(",
"n",
"+",
"1",
")",
"&",
"n",
":",
"# n+1 is not a power of 2 yet",
"n",
"|=",
"n",
">>",
"shift",
"shift",
"*=",
"2",
"return"... | 31.875 | 0.003817 |
def update(
ctx,
state,
bare=False,
dry_run=None,
outdated=False,
**kwargs
):
"""Runs lock, then sync."""
from ..core import (
ensure_project,
do_outdated,
do_lock,
do_sync,
project,
)
ensure_project(three=state.three, python=state.python,... | [
"def",
"update",
"(",
"ctx",
",",
"state",
",",
"bare",
"=",
"False",
",",
"dry_run",
"=",
"None",
",",
"outdated",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"(",
"ensure_project",
",",
"do_outdated",
",",
... | 28.727273 | 0.00102 |
def dcminfo(dcmvar, verbose=True):
''' Get basic info about the DICOM file/header.
'''
if isinstance(dcmvar, basestring):
if verbose:
print 'i> provided DICOM file:', dcmvar
dhdr = dcm.dcmread(dcmvar)
elif isinstance(dcmvar, dict):
dhdr = dcmvar
elif isinstance(d... | [
"def",
"dcminfo",
"(",
"dcmvar",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"dcmvar",
",",
"basestring",
")",
":",
"if",
"verbose",
":",
"print",
"'i> provided DICOM file:'",
",",
"dcmvar",
"dhdr",
"=",
"dcm",
".",
"dcmread",
"(",
"d... | 28.662921 | 0.014399 |
def main():
"""
Parse command line argument and
output appropriate file type (csv or JSON)
"""
parser = ArgumentParser()
parser.add_argument(
"-c", "--clinvarfile", dest="clinvarfile",
help="ClinVar VCF file (either this or -C must be specified)",
metavar="CLINVARFILE")
... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--clinvarfile\"",
",",
"dest",
"=",
"\"clinvarfile\"",
",",
"help",
"=",
"\"ClinVar VCF file (either this or -C must be specified)\"",
",",... | 41.371429 | 0.00045 |
def parse(self, datetimeString, sourceTime=None):
"""
Splits the given C{datetimeString} into tokens, finds the regex
patterns that match and then calculates a C{struct_time} value from
the chunks.
If C{sourceTime} is given then the C{struct_time} value will be
ca... | [
"def",
"parse",
"(",
"self",
",",
"datetimeString",
",",
"sourceTime",
"=",
"None",
")",
":",
"if",
"sourceTime",
":",
"if",
"isinstance",
"(",
"sourceTime",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"_debug",
":",
"print",
"'coercing datetime to tim... | 42.227848 | 0.005344 |
def last_date_in_output_for_sid(self, sid):
"""
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out : pd.Timestamp
The midnight of the last date written in to the output for the
given sid.
"""
... | [
"def",
"last_date_in_output_for_sid",
"(",
"self",
",",
"sid",
")",
":",
"sizes_path",
"=",
"\"{0}/close/meta/sizes\"",
".",
"format",
"(",
"self",
".",
"sidpath",
"(",
"sid",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"sizes_path",
")",... | 34.730769 | 0.002155 |
def add_sample(self, sample_id, features, label,
class_id=None,
overwrite=False,
feature_names=None):
"""Adds a new sample to the dataset with its features, label and class ID.
This is the preferred way to construct the dataset.
Paramete... | [
"def",
"add_sample",
"(",
"self",
",",
"sample_id",
",",
"features",
",",
"label",
",",
"class_id",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"feature_names",
"=",
"None",
")",
":",
"if",
"sample_id",
"in",
"self",
".",
"__data",
"and",
"not",
... | 44.949367 | 0.00496 |
def filepaths_in_dir(path):
"""Find all files in a directory, and return the relative paths to those files.
Args:
path (str): the directory path to walk
Returns:
list: the list of relative paths to all files inside of ``path`` or its
subdirectories.
"""
filepaths = []
... | [
"def",
"filepaths_in_dir",
"(",
"path",
")",
":",
"filepaths",
"=",
"[",
"]",
"for",
"root",
",",
"directories",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"filepath",
"=",
"os",
".",
... | 31.444444 | 0.003431 |
def md5sum( string ):
"""
Generate the md5 checksum for a string
Args:
string (Str): The string to be checksummed.
Returns:
(Str): The hex checksum.
"""
h = hashlib.new( 'md5' )
h.update( string.encode( 'utf-8' ) )
return h.hexdigest() | [
"def",
"md5sum",
"(",
"string",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"'md5'",
")",
"h",
".",
"update",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | 21 | 0.031579 |
def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional para... | [
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot use `generate_np` when no `sess` was\"",
"\" provided\"",
")",
"packed",
"=",
"self",
".",
... | 31.470588 | 0.006346 |
def get_archive_link(self, archive_format, ref=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/:archive_format/:ref <http://developer.github.com/v3/repos/contents>`_
:param archive_format: string
:param ref: string
:rtype: string
"""
assert isins... | [
"def",
"get_archive_link",
"(",
"self",
",",
"archive_format",
",",
"ref",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"isinstance",
"(",
"archive_format",
",",
"(",
"str",
",",
"unicode",
")",
")",
",",
"archive_format",
"assert",... | 41.882353 | 0.005495 |
def parse_binary(self, data, display, rawdict = 0):
"""values, remdata = s.parse_binary(data, display, rawdict = 0)
Convert a binary representation of the structure into Python values.
DATA is a string or a buffer containing the binary data.
DISPLAY should be a Xlib.protocol.display.D... | [
"def",
"parse_binary",
"(",
"self",
",",
"data",
",",
"display",
",",
"rawdict",
"=",
"0",
")",
":",
"ret",
"=",
"{",
"}",
"val",
"=",
"struct",
".",
"unpack",
"(",
"self",
".",
"static_codes",
",",
"data",
"[",
":",
"self",
".",
"static_size",
"]"... | 35.276316 | 0.001814 |
def compare_lists(old=None, new=None):
'''
Compare before and after results from various salt functions, returning a
dict describing the changes that were made
'''
ret = dict()
for item in new:
if item not in old:
ret['new'] = item
for item in old:
if item not in ... | [
"def",
"compare_lists",
"(",
"old",
"=",
"None",
",",
"new",
"=",
"None",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"for",
"item",
"in",
"new",
":",
"if",
"item",
"not",
"in",
"old",
":",
"ret",
"[",
"'new'",
"]",
"=",
"item",
"for",
"item",
"in"... | 27.461538 | 0.00271 |
def robust_single_linkage(X, cut, k=5, alpha=1.4142135623730951,
gamma=5, metric='euclidean', algorithm='best',
memory=Memory(cachedir=None, verbose=0), leaf_size=40,
core_dist_n_jobs=4, **kwargs):
"""Perform robust single linkage cluster... | [
"def",
"robust_single_linkage",
"(",
"X",
",",
"cut",
",",
"k",
"=",
"5",
",",
"alpha",
"=",
"1.4142135623730951",
",",
"gamma",
"=",
"5",
",",
"metric",
"=",
"'euclidean'",
",",
"algorithm",
"=",
"'best'",
",",
"memory",
"=",
"Memory",
"(",
"cachedir",
... | 43.223602 | 0.001264 |
def set_percentage(x: Iterable[X], y: Iterable[X]) -> float:
"""What percentage of x is contained within y?
:param set x: A set
:param set y: Another set
:return: The percentage of x contained within y
"""
a, b = set(x), set(y)
if not a:
return 0.0
return len(a & b) / len(a) | [
"def",
"set_percentage",
"(",
"x",
":",
"Iterable",
"[",
"X",
"]",
",",
"y",
":",
"Iterable",
"[",
"X",
"]",
")",
"->",
"float",
":",
"a",
",",
"b",
"=",
"set",
"(",
"x",
")",
",",
"set",
"(",
"y",
")",
"if",
"not",
"a",
":",
"return",
"0.0... | 23.538462 | 0.003145 |
def resolve(self, space_id=None, environment_id=None):
"""
Resolves link to a specific resource.
"""
proxy_method = getattr(
self._client,
base_path_for(self.link_type)
)
if self.link_type == 'Space':
return proxy_method().find(self.id... | [
"def",
"resolve",
"(",
"self",
",",
"space_id",
"=",
"None",
",",
"environment_id",
"=",
"None",
")",
":",
"proxy_method",
"=",
"getattr",
"(",
"self",
".",
"_client",
",",
"base_path_for",
"(",
"self",
".",
"link_type",
")",
")",
"if",
"self",
".",
"l... | 32.666667 | 0.003968 |
def __pull_combined_properties(self):
""" something here... """
query_params = {
"titles": self.title,
"prop": "extracts|redirects|links|coordinates|categories|extlinks",
"continue": dict(),
# summary
"explaintext": "",
"exintro": ... | [
"def",
"__pull_combined_properties",
"(",
"self",
")",
":",
"query_params",
"=",
"{",
"\"titles\"",
":",
"self",
".",
"title",
",",
"\"prop\"",
":",
"\"extracts|redirects|links|coordinates|categories|extlinks\"",
",",
"\"continue\"",
":",
"dict",
"(",
")",
",",
"# s... | 30.391753 | 0.000986 |
def messagesReceived(self, msg_list):
""" Handle incoming messages
@param msg_list: Message list to process
"""
self.stats.packReceived(len(msg_list))
for msg in msg_list:
self.conn.messageReceived(msg) | [
"def",
"messagesReceived",
"(",
"self",
",",
"msg_list",
")",
":",
"self",
".",
"stats",
".",
"packReceived",
"(",
"len",
"(",
"msg_list",
")",
")",
"for",
"msg",
"in",
"msg_list",
":",
"self",
".",
"conn",
".",
"messageReceived",
"(",
"msg",
")"
] | 27.555556 | 0.007813 |
def getImageByTag(tag):
'''Check if an image with a given tag exists. No side-effects. Idempotent.
Handles ImageNotFound and APIError exceptions, but only reraises APIError.
'''
require_str("tag", tag)
image = None
try:
image = client.images.get(tag)
print("Found image", tag, ".... | [
"def",
"getImageByTag",
"(",
"tag",
")",
":",
"require_str",
"(",
"\"tag\"",
",",
"tag",
")",
"image",
"=",
"None",
"try",
":",
"image",
"=",
"client",
".",
"images",
".",
"get",
"(",
"tag",
")",
"print",
"(",
"\"Found image\"",
",",
"tag",
",",
"\".... | 29.823529 | 0.001912 |
def _readoct(self, length, start):
"""Read bits and interpret as an octal string."""
if length % 3:
raise InterpretError("Cannot convert to octal unambiguously - "
"not multiple of 3 bits.")
if not length:
return ''
# Get main octa... | [
"def",
"_readoct",
"(",
"self",
",",
"length",
",",
"start",
")",
":",
"if",
"length",
"%",
"3",
":",
"raise",
"InterpretError",
"(",
"\"Cannot convert to octal unambiguously - \"",
"\"not multiple of 3 bits.\"",
")",
"if",
"not",
"length",
":",
"return",
"''",
... | 42.857143 | 0.003263 |
def compress_file(filepath, compression="gz"):
"""
Compresses a file with the correct extension. Functions like standard
Unix command line gzip and bzip2 in the sense that the original
uncompressed files are not retained.
Args:
filepath (str): Path to file.
compression (str): A comp... | [
"def",
"compress_file",
"(",
"filepath",
",",
"compression",
"=",
"\"gz\"",
")",
":",
"if",
"compression",
"not",
"in",
"[",
"\"gz\"",
",",
"\"bz2\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Supported compression formats are 'gz' and 'bz2'.\"",
")",
"from",
"mont... | 40.842105 | 0.001259 |
def parse_time(time):
"""
Parse a date/time string and return a corresponding datetime object.
Args:
time (str): A ``string` of one of the following formats: ``%H:%M``, ``%Y-%m-%d`` or
``%Y-%m-%d %H:%M``.
Returns:
datetime.datetime: Depending on input string either returns ... | [
"def",
"parse_time",
"(",
"time",
")",
":",
"length",
"=",
"len",
"(",
"time",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
"if",
"length",
"==",
"1",
":",
"try",
":",
"result",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"tim... | 33.657895 | 0.00304 |
def MultiReadClientSnapshot(self, client_ids, cursor=None):
"""Reads the latest client snapshots for a list of clients."""
int_ids = [db_utils.ClientIDToInt(cid) for cid in client_ids]
query = (
"SELECT h.client_id, h.client_snapshot, UNIX_TIMESTAMP(h.timestamp),"
" s.startup_info "
... | [
"def",
"MultiReadClientSnapshot",
"(",
"self",
",",
"client_ids",
",",
"cursor",
"=",
"None",
")",
":",
"int_ids",
"=",
"[",
"db_utils",
".",
"ClientIDToInt",
"(",
"cid",
")",
"for",
"cid",
"in",
"client_ids",
"]",
"query",
"=",
"(",
"\"SELECT h.client_id, h... | 45.931034 | 0.005882 |
def convergence_of_galaxies_from_grid(grid, galaxies):
"""Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence \
of each galaxy's mass profile.
If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the \
... | [
"def",
"convergence_of_galaxies_from_grid",
"(",
"grid",
",",
"galaxies",
")",
":",
"if",
"galaxies",
":",
"return",
"sum",
"(",
"map",
"(",
"lambda",
"g",
":",
"g",
".",
"convergence_from_grid",
"(",
"grid",
")",
",",
"galaxies",
")",
")",
"else",
":",
... | 44.47619 | 0.005241 |
def restrict_joins(self, q, bindings):
"""
Restrict the joins across all tables referenced in the database
query to those specified in the model for the relevant dimensions.
If a single table is used for the query, no unnecessary joins are
performed. If more than one table are re... | [
"def",
"restrict_joins",
"(",
"self",
",",
"q",
",",
"bindings",
")",
":",
"if",
"len",
"(",
"q",
".",
"froms",
")",
"==",
"1",
":",
"return",
"q",
"else",
":",
"for",
"binding",
"in",
"bindings",
":",
"if",
"binding",
".",
"table",
"==",
"self",
... | 52.854167 | 0.004644 |
def correl_model(self):
"""
Return a correlation object. See :mod:`openquake.hazardlib.correlation`
for more info.
"""
correl_name = self.ground_motion_correlation_model
if correl_name is None: # no correlation model
return
correl_model_cls = getattr(... | [
"def",
"correl_model",
"(",
"self",
")",
":",
"correl_name",
"=",
"self",
".",
"ground_motion_correlation_model",
"if",
"correl_name",
"is",
"None",
":",
"# no correlation model",
"return",
"correl_model_cls",
"=",
"getattr",
"(",
"correlation",
",",
"'%sCorrelationMo... | 40.363636 | 0.004405 |
def zlist(columns, items, print_columns=None,
text="", title="", width=DEFAULT_WIDTH,
height=ZLIST_HEIGHT, timeout=None):
"""
Display a list of values
:param columns: a list of columns name
:type columns: list of strings
:param items: a list of values
:type items: list of st... | [
"def",
"zlist",
"(",
"columns",
",",
"items",
",",
"print_columns",
"=",
"None",
",",
"text",
"=",
"\"\"",
",",
"title",
"=",
"\"\"",
",",
"width",
"=",
"DEFAULT_WIDTH",
",",
"height",
"=",
"ZLIST_HEIGHT",
",",
"timeout",
"=",
"None",
")",
":",
"dialog... | 33.068966 | 0.002026 |
def initialize_state(self):
""" Call this to initialize the state of the UI after everything has been connected. """
if self.__scan_hardware_source:
self.__profile_changed_event_listener = self.__scan_hardware_source.profile_changed_event.listen(self.__update_profile_index)
self.... | [
"def",
"initialize_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"__scan_hardware_source",
":",
"self",
".",
"__profile_changed_event_listener",
"=",
"self",
".",
"__scan_hardware_source",
".",
"profile_changed_event",
".",
"listen",
"(",
"self",
".",
"__update_... | 69.630435 | 0.004618 |
def sismember(self, name, value):
"""
Return a boolean indicating if ``value`` is a member of set ``name``
send raw (source) values here. Right functioning with other values
not guaranteed (and even worse).
"""
return self.storage.sismember(name, self.dump(value)) | [
"def",
"sismember",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"self",
".",
"storage",
".",
"sismember",
"(",
"name",
",",
"self",
".",
"dump",
"(",
"value",
")",
")"
] | 43.714286 | 0.00641 |
def execPath(self):
"""the executable application's path"""
vers = self.version.label if self.version else None # executables in Versions folder are stored by baseVersion (modified by game data patches)
return self.installedApp.exec_path(vers) | [
"def",
"execPath",
"(",
"self",
")",
":",
"vers",
"=",
"self",
".",
"version",
".",
"label",
"if",
"self",
".",
"version",
"else",
"None",
"# executables in Versions folder are stored by baseVersion (modified by game data patches)",
"return",
"self",
".",
"installedApp"... | 66 | 0.014981 |
def Unique(a, t):
"""
Unique op.
"""
_, idxs, inv = np.unique(a, return_index=True, return_inverse=True)
return np.copy(a)[np.sort(idxs)], idxs[inv].astype(dtype_map[t]) | [
"def",
"Unique",
"(",
"a",
",",
"t",
")",
":",
"_",
",",
"idxs",
",",
"inv",
"=",
"np",
".",
"unique",
"(",
"a",
",",
"return_index",
"=",
"True",
",",
"return_inverse",
"=",
"True",
")",
"return",
"np",
".",
"copy",
"(",
"a",
")",
"[",
"np",
... | 30.666667 | 0.005291 |
def use_isolated_objective_bank_view(self):
"""Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view"""
self._objective_bank_view = ISOLATED
# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked
for session in self._get_... | [
"def",
"use_isolated_objective_bank_view",
"(",
"self",
")",
":",
"self",
".",
"_objective_bank_view",
"=",
"ISOLATED",
"# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
... | 51.555556 | 0.008475 |
def _make_2d_array(self, data):
"""
Convert a 1D array of mesh values to a masked 2D mesh array
given the 1D mesh indices ``mesh_idx``.
Parameters
----------
data : 1D `~numpy.ndarray`
A 1D array of mesh values.
Returns
-------
result... | [
"def",
"_make_2d_array",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"shape",
"!=",
"self",
".",
"mesh_idx",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"'data and mesh_idx must have the same shape'",
")",
"if",
"np",
".",
"ma",
".",
"is_masked... | 31.314286 | 0.00177 |
def create_fpath_dir(self, fpath: str):
"""Creates directory for fpath."""
os.makedirs(os.path.dirname(fpath), exist_ok=True) | [
"def",
"create_fpath_dir",
"(",
"self",
",",
"fpath",
":",
"str",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fpath",
")",
",",
"exist_ok",
"=",
"True",
")"
] | 46.333333 | 0.014184 |
def _augment_book(self, uuid, event):
"""
Checks if the newly created object is a book and only has an ISBN.
If so, tries to fetch the book data off the internet.
:param uuid: uuid of book to augment
:param client: requesting client
"""
try:
if not is... | [
"def",
"_augment_book",
"(",
"self",
",",
"uuid",
",",
"event",
")",
":",
"try",
":",
"if",
"not",
"isbnmeta",
":",
"self",
".",
"log",
"(",
"\"No isbntools found! Install it to get full \"",
"\"functionality!\"",
",",
"lvl",
"=",
"warn",
")",
"return",
"new_b... | 40.506667 | 0.000964 |
def _matcher(self, other):
"""
CGRContainer < CGRContainer
"""
if isinstance(other, CGRContainer):
return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
raise TypeError('only cgr-cgr possible') | [
"def",
"_matcher",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"CGRContainer",
")",
":",
"return",
"GraphMatcher",
"(",
"other",
",",
"self",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"==",
"y",
",",
"lambda",
"x",
","... | 37.142857 | 0.011278 |
def set_flowcontrol_send(self, name, value=None, default=False,
disable=False):
"""Configures the interface flowcontrol send value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
... | [
"def",
"set_flowcontrol_send",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"return",
"self",
".",
"set_flowcontrol",
"(",
"name",
",",
"'send'",
",",
"value",
",",
"default",
... | 38.333333 | 0.003636 |
def connected_sites( self, site_labels=None ):
"""
Searches the lattice to find sets of sites that are contiguously neighbouring.
Mutually exclusive sets of contiguous sites are returned as Cluster objects.
Args:
site_labels (:obj:(List(Str)|Set(Str)|Str), optional): Labels ... | [
"def",
"connected_sites",
"(",
"self",
",",
"site_labels",
"=",
"None",
")",
":",
"if",
"site_labels",
":",
"selected_sites",
"=",
"self",
".",
"select_sites",
"(",
"site_labels",
")",
"else",
":",
"selected_sites",
"=",
"self",
".",
"sites",
"initial_clusters... | 38.658537 | 0.022769 |
def plot(self, ncols=2):
"""
:param ncols: Number of grid columns
:return: a bokeh figure image
"""
grid = gridplot(self.plots, ncols=ncols)
return grid | [
"def",
"plot",
"(",
"self",
",",
"ncols",
"=",
"2",
")",
":",
"grid",
"=",
"gridplot",
"(",
"self",
".",
"plots",
",",
"ncols",
"=",
"ncols",
")",
"return",
"grid"
] | 27.714286 | 0.01 |
def total_amount(qs) -> Total:
"""Sums the amounts of the objects in the queryset, keeping each currency separate.
:param qs: A querystring containing objects that have an amount field of type Money.
:return: A Total object.
"""
aggregate = qs.values('amount_currency').annotate(sum=Sum('amount'))
... | [
"def",
"total_amount",
"(",
"qs",
")",
"->",
"Total",
":",
"aggregate",
"=",
"qs",
".",
"values",
"(",
"'amount_currency'",
")",
".",
"annotate",
"(",
"sum",
"=",
"Sum",
"(",
"'amount'",
")",
")",
"return",
"Total",
"(",
"Money",
"(",
"amount",
"=",
... | 57.428571 | 0.009804 |
def calc_gamma_from_position_autocorrelation_fit(self, GammaGuess=None, FreqTrapGuess=None, silent=False, MakeFig=True, show_fig=True):
"""
Calculates the total damping, i.e. Gamma, by calculating the autocorrleation
of the position-time trace. The autocorrelation is fitted with an exponential ... | [
"def",
"calc_gamma_from_position_autocorrelation_fit",
"(",
"self",
",",
"GammaGuess",
"=",
"None",
",",
"FreqTrapGuess",
"=",
"None",
",",
"silent",
"=",
"False",
",",
"MakeFig",
"=",
"True",
",",
"show_fig",
"=",
"True",
")",
":",
"autocorrelation",
"=",
"ca... | 43.071429 | 0.008106 |
def set_simulate(self, status):
"""Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
"""
if type(status) != bool:
raise InvalidInput("Status value must be bool")
self.... | [
"def",
"set_simulate",
"(",
"self",
",",
"status",
")",
":",
"if",
"type",
"(",
"status",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Status value must be bool\"",
")",
"self",
".",
"_simulate",
"=",
"bool2int",
"(",
"status",
")"
] | 30.727273 | 0.005747 |
def _get_websocket(self, reuse=True):
"""
Reuse existing connection or create a new connection.
"""
# Check if still connected
if self.ws and reuse:
if self.ws.connected:
return self.ws
logging.debug("Stale connection, reconnecting.")
... | [
"def",
"_get_websocket",
"(",
"self",
",",
"reuse",
"=",
"True",
")",
":",
"# Check if still connected",
"if",
"self",
".",
"ws",
"and",
"reuse",
":",
"if",
"self",
".",
"ws",
".",
"connected",
":",
"return",
"self",
".",
"ws",
"logging",
".",
"debug",
... | 28.538462 | 0.005222 |
def put(self, request, id=None, **kwargs):
"""
Handles put requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_update_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to pe... | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
":",
"obj",
"=",
"get_object_or_404",
"(",
"self",
".",
"queryset",
"(",
"request",
")",
",",
"id",
"=",
"id",
")",
"if",
"not",
"... | 38.615385 | 0.005837 |
def to_xml(self):
'''
Returns an XMLi representation of the shipping details.
@return: Element
'''
for n, v in {"recipient": self.recipient}.items():
if is_empty_or_none(v):
raise ValueError("'%s' attribute cannot be empty or None." % n)
doc =... | [
"def",
"to_xml",
"(",
"self",
")",
":",
"for",
"n",
",",
"v",
"in",
"{",
"\"recipient\"",
":",
"self",
".",
"recipient",
"}",
".",
"items",
"(",
")",
":",
"if",
"is_empty_or_none",
"(",
"v",
")",
":",
"raise",
"ValueError",
"(",
"\"'%s' attribute canno... | 34.230769 | 0.004376 |
def has_children(self):
"returns False if children is empty or contains only empty lines else True."
return bool([x for x in self.children if not isinstance(x, EmptyLine)]) | [
"def",
"has_children",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"children",
"if",
"not",
"isinstance",
"(",
"x",
",",
"EmptyLine",
")",
"]",
")"
] | 62 | 0.015957 |
def escalatee(self, escalatee_id, action='ADD'):
"""
Adds a assignee to the task
Args:
escalatee_id: The id of the escalatee to be added
action:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
return self.tc_r... | [
"def",
"escalatee",
"(",
"self",
",",
"escalatee_id",
",",
"action",
"=",
"'ADD'",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"ret... | 28.266667 | 0.006849 |
def search_dependencies(self):
"""Returns a list of other modules that this module and its members and executables
depend on in order to run correctly. This differs from the self.dependencies attribute
that just hase explicit module names from the 'use' clauses.
"""
result = [sel... | [
"def",
"search_dependencies",
"(",
"self",
")",
":",
"result",
"=",
"[",
"self",
".",
"module",
".",
"name",
"]",
"#First we look at the explicit use references from this module and all",
"#its dependencies until the chain terminates.",
"stack",
"=",
"self",
".",
"needs",
... | 45.486486 | 0.007563 |
def moon_phases(ephemeris):
"""Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
... | [
"def",
"moon_phases",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"moon",
"=",
"ephemeris",
"[",
"'moon'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"moon_phase_at",
"(",
"t",
")",
":",
"\"\"\"Return the phase ... | 39.652174 | 0.001071 |
def finder_for_path(path):
"""
Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path.
"""
result = None
# calls any path hooks, gets importer into cache
pkgutil.get_importer(path)
load... | [
"def",
"finder_for_path",
"(",
"path",
")",
":",
"result",
"=",
"None",
"# calls any path hooks, gets importer into cache",
"pkgutil",
".",
"get_importer",
"(",
"path",
")",
"loader",
"=",
"sys",
".",
"path_importer_cache",
".",
"get",
"(",
"path",
")",
"finder",
... | 31.611111 | 0.001706 |
def send_to_tsdb(self, realm, host, service, metrics, ts, path):
"""Send performance data to time series database
Indeed this function stores metrics in the internal cache and checks if the flushing
is necessary and then flushes.
:param realm: concerned realm
:type: string
... | [
"def",
"send_to_tsdb",
"(",
"self",
",",
"realm",
",",
"host",
",",
"service",
",",
"metrics",
",",
"ts",
",",
"path",
")",
":",
"if",
"ts",
"is",
"None",
":",
"ts",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"data",
"=",
"{",
"\"meas... | 30.340426 | 0.002038 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.