text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _format_select(formatter, name):
"""Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applie... | [
"def",
"_format_select",
"(",
"formatter",
",",
"name",
")",
":",
"for",
"caster",
"in",
"formatter",
".",
"split",
"(",
"'-'",
")",
":",
"if",
"caster",
"==",
"'SEC_TO_MICRO'",
":",
"name",
"=",
"\"%s*1000000\"",
"%",
"name",
"elif",
"':'",
"in",
"caste... | 28.896552 | 0.001155 |
def create_ui(self):
'''
.. versionchanged:: 0.9
Update device registration in real-time while dragging video
control point to new position.
.. versionchanged:: 0.12
Add ``dynamic_electrode_state_shapes`` layer to show dynamic
electrode actuations... | [
"def",
"create_ui",
"(",
"self",
")",
":",
"super",
"(",
"DmfDeviceCanvas",
",",
"self",
")",
".",
"create_ui",
"(",
")",
"self",
".",
"video_sink",
"=",
"VideoSink",
"(",
"*",
"[",
"self",
".",
"socket_info",
"[",
"k",
"]",
"for",
"k",
"in",
"[",
... | 48.218182 | 0.000739 |
def generate_seviri_file(seviri, platform_name):
"""Generate the pyspectral internal common format relative response
function file for one SEVIRI
"""
import h5py
filename = os.path.join(seviri.output_dir,
"rsr_seviri_{0}.h5".format(platform_name))
sat_name = platfor... | [
"def",
"generate_seviri_file",
"(",
"seviri",
",",
"platform_name",
")",
":",
"import",
"h5py",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"seviri",
".",
"output_dir",
",",
"\"rsr_seviri_{0}.h5\"",
".",
"format",
"(",
"platform_name",
")",
")",
"s... | 38.263158 | 0.000671 |
def create_table_index(self):
"""Create the QTableView that will hold the index model."""
self.table_index = QTableView()
self.table_index.horizontalHeader().hide()
self.table_index.setEditTriggers(QTableWidget.NoEditTriggers)
self.table_index.setHorizontalScrollBarPolicy(Qt... | [
"def",
"create_table_index",
"(",
"self",
")",
":",
"self",
".",
"table_index",
"=",
"QTableView",
"(",
")",
"self",
".",
"table_index",
".",
"horizontalHeader",
"(",
")",
".",
"hide",
"(",
")",
"self",
".",
"table_index",
".",
"setEditTriggers",
"(",
"QTa... | 60.666667 | 0.002165 |
def create_dataset(self, name, **kwargs):
"""Create an array.
Parameters
----------
name : string
Array name.
data : array_like, optional
Initial data.
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, op... | [
"def",
"create_dataset",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_create_dataset_nosync",
",",
"name",
",",
"*",
"*",
"kwargs",
")"
] | 36.745455 | 0.000964 |
def handle_device_json(self, data):
"""Manage the device json list."""
self._device_json.insert(0, data)
self._device_json.pop() | [
"def",
"handle_device_json",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_device_json",
".",
"insert",
"(",
"0",
",",
"data",
")",
"self",
".",
"_device_json",
".",
"pop",
"(",
")"
] | 37.25 | 0.013158 |
def random_forest_error(forest, X_train, X_test, inbag=None,
calibrate=True, memory_constrained=False,
memory_limit=None):
"""
Calculate error bars from scikit-learn RandomForest estimators.
RandomForest is a regressor or classifier object
this variance c... | [
"def",
"random_forest_error",
"(",
"forest",
",",
"X_train",
",",
"X_test",
",",
"inbag",
"=",
"None",
",",
"calibrate",
"=",
"True",
",",
"memory_constrained",
"=",
"False",
",",
"memory_limit",
"=",
"None",
")",
":",
"if",
"inbag",
"is",
"None",
":",
"... | 38.990826 | 0.000229 |
def configure_doc_job(
config_url, rosdistro_name, doc_build_name,
repo_name, os_name, os_code_name, arch,
config=None, build_file=None,
index=None, dist_file=None, dist_cache=None,
jenkins=None, views=None,
is_disabled=False,
groovy_script=None,
doc_repos... | [
"def",
"configure_doc_job",
"(",
"config_url",
",",
"rosdistro_name",
",",
"doc_build_name",
",",
"repo_name",
",",
"os_name",
",",
"os_code_name",
",",
"arch",
",",
"config",
"=",
"None",
",",
"build_file",
"=",
"None",
",",
"index",
"=",
"None",
",",
"dist... | 39.505495 | 0.000271 |
def read_json(self):
"""
read metadata from json and set all the found properties.
when overriding remember to wrap your calls in reading_ancillary_files
:return: the read metadata
:rtype: dict
"""
with reading_ancillary_files(self):
if self.json_uri... | [
"def",
"read_json",
"(",
"self",
")",
":",
"with",
"reading_ancillary_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"json_uri",
"is",
"None",
":",
"metadata",
"=",
"self",
".",
"_read_json_db",
"(",
")",
"else",
":",
"metadata",
"=",
"self",
".",
"... | 38.217391 | 0.00222 |
def matchfieldnames(field_a, field_b):
"""Check match between two strings, ignoring case and spaces/underscores.
Parameters
----------
a : str
b : str
Returns
-------
bool
"""
normalised_a = field_a.replace(' ', '_').lower()
normalised_b = field_b.replace(' ', ... | [
"def",
"matchfieldnames",
"(",
"field_a",
",",
"field_b",
")",
":",
"normalised_a",
"=",
"field_a",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
"lower",
"(",
")",
"normalised_b",
"=",
"field_b",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
... | 21.235294 | 0.013263 |
def _get_json(self, urlpart):
"""
gets the result object dictionary
"""
url = self._url + "/%s" % urlpart
params = {
"f" : "json",
}
return self._get(url=url,
param_dict=params,
securityHandler=s... | [
"def",
"_get_json",
"(",
"self",
",",
"urlpart",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/%s\"",
"%",
"urlpart",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"}",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_d... | 31.357143 | 0.015487 |
async def get_play_info(self) -> PlayInfo:
"""Return of the device."""
info = await self.services["avContent"]["getPlayingContentInfo"]({})
return PlayInfo.make(**info.pop()) | [
"async",
"def",
"get_play_info",
"(",
"self",
")",
"->",
"PlayInfo",
":",
"info",
"=",
"await",
"self",
".",
"services",
"[",
"\"avContent\"",
"]",
"[",
"\"getPlayingContentInfo\"",
"]",
"(",
"{",
"}",
")",
"return",
"PlayInfo",
".",
"make",
"(",
"*",
"*... | 49 | 0.01005 |
def process_tree_recur(self, file_names, node):
"""
Adds the names of all the files associated with the sub-tree rooted by `node` to `file_names` in post-order.
:param file_names: A global list containing all file names associated with a tree
:param node: The root of the current sub-tree... | [
"def",
"process_tree_recur",
"(",
"self",
",",
"file_names",
",",
"node",
")",
":",
"# Process node's children",
"for",
"child_node",
"in",
"node",
".",
"children",
":",
"self",
".",
"process_tree_recur",
"(",
"file_names",
",",
"child_node",
")",
"# Call children... | 50.25 | 0.008143 |
def coarsen_all_traces(level=2, exponential=False, axes="all", figure=None):
"""
This function does nearest-neighbor coarsening of the data. See
spinmob.fun.coarsen_data for more information.
Parameters
----------
level=2
How strongly to coarsen.
exponential=False
If Tr... | [
"def",
"coarsen_all_traces",
"(",
"level",
"=",
"2",
",",
"exponential",
"=",
"False",
",",
"axes",
"=",
"\"all\"",
",",
"figure",
"=",
"None",
")",
":",
"if",
"axes",
"==",
"\"gca\"",
":",
"axes",
"=",
"_pylab",
".",
"gca",
"(",
")",
"if",
"axes",
... | 27.818182 | 0.010526 |
def _resolve_access(self, addr, size):
"""
Resolves a memory access of a certain size. Returns a sequence of the bases, offsets, and sizes of the accesses required
to fulfil this.
"""
# if we fit in one word
first_offset = addr % self.width
first_base = addr - fi... | [
"def",
"_resolve_access",
"(",
"self",
",",
"addr",
",",
"size",
")",
":",
"# if we fit in one word",
"first_offset",
"=",
"addr",
"%",
"self",
".",
"width",
"first_base",
"=",
"addr",
"-",
"first_offset",
"if",
"first_offset",
"+",
"size",
"<=",
"self",
"."... | 37.181818 | 0.008343 |
def copy_file(self, path, prefixed_path, source_storage):
"""
Overwritten to execute only with --upload-unhashed-files param or StaticCloudinaryStorage.
Otherwise only hashed files will be uploaded during postprocessing.
"""
if (settings.STATICFILES_STORAGE == 'cloudinary_storage... | [
"def",
"copy_file",
"(",
"self",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"if",
"(",
"settings",
".",
"STATICFILES_STORAGE",
"==",
"'cloudinary_storage.storage.StaticCloudinaryStorage'",
"or",
"self",
".",
"upload_unhashed_files",
")",
":",
... | 59.25 | 0.008316 |
def run(self):
"""Execute events until the queue is empty.
When there is a positive delay until the first event, the
delay function is called and the event is left in the queue;
otherwise, the event is removed from the queue and executed
(its action function is called, passing it... | [
"def",
"run",
"(",
"self",
")",
":",
"# localize variable access to minimize overhead",
"# and to improve thread safety",
"q",
"=",
"self",
".",
"_queue",
"delayfunc",
"=",
"self",
".",
"delayfunc",
"timefunc",
"=",
"self",
".",
"timefunc",
"pop",
"=",
"heapq",
".... | 44.410256 | 0.00113 |
def filter(cls, parent=None, **filters):
"""
Gets all resources of the given type and parent (if provided) which match the given filters.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
:par... | [
"def",
"filter",
"(",
"cls",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"data",
"=",
"cls",
".",
"_process_filter_request",
"(",
"parent",
",",
"*",
"*",
"filters",
")",
"return",
"cls",
".",
"_load_resources",
"(",
"data",
")"
] | 55.6 | 0.00885 |
def cli(sequencepath, report, refseq_database):
"""
Pass command line arguments to, and run the feature extraction functions
"""
main(sequencepath, report, refseq_database, num_threads=multiprocessing.cpu_count()) | [
"def",
"cli",
"(",
"sequencepath",
",",
"report",
",",
"refseq_database",
")",
":",
"main",
"(",
"sequencepath",
",",
"report",
",",
"refseq_database",
",",
"num_threads",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")"
] | 45 | 0.008734 |
def print_to_file(object):
"""
Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt
:param: Object: object of type str, list, or dict
:return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt
... | [
"def",
"print_to_file",
"(",
"object",
")",
":",
"with",
"open",
"(",
"'pyoutput.txt'",
",",
"'w'",
")",
"as",
"fh",
":",
"x",
"=",
"None",
"if",
"type",
"(",
"object",
")",
"is",
"list",
":",
"x",
"=",
"json",
".",
"dumps",
"(",
"object",
",",
"... | 40.333333 | 0.01454 |
def send_email(subject, message, sender, recipients, image_png=None):
"""
Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'.
"""
notifiers = {
... | [
"def",
"send_email",
"(",
"subject",
",",
"message",
",",
"sender",
",",
"recipients",
",",
"image_png",
"=",
"None",
")",
":",
"notifiers",
"=",
"{",
"'ses'",
":",
"send_email_ses",
",",
"'sendgrid'",
":",
"send_email_sendgrid",
",",
"'smtp'",
":",
"send_em... | 33.189189 | 0.001582 |
def variable(dims=1):
"""
Simple constructor to create single variables to create polynomials.
Args:
dims (int):
Number of dimensions in the array.
Returns:
(Poly):
Polynomial array with unit components in each dimension.
Examples:
>>> print(variabl... | [
"def",
"variable",
"(",
"dims",
"=",
"1",
")",
":",
"if",
"dims",
"==",
"1",
":",
"return",
"Poly",
"(",
"{",
"(",
"1",
",",
")",
":",
"1",
"}",
",",
"dim",
"=",
"1",
",",
"shape",
"=",
"(",
")",
")",
"return",
"Poly",
"(",
"{",
"tuple",
... | 24.478261 | 0.001709 |
def GetRootKey(self):
"""Retrieves the Windows Registry root key.
Returns:
WinRegistryKey: Windows Registry root key.
Raises:
RuntimeError: if there are multiple matching mappings and
the correct mapping cannot be resolved.
"""
root_registry_key = virtual.VirtualWinRegistryKe... | [
"def",
"GetRootKey",
"(",
"self",
")",
":",
"root_registry_key",
"=",
"virtual",
".",
"VirtualWinRegistryKey",
"(",
"''",
")",
"for",
"mapped_key",
"in",
"self",
".",
"_MAPPED_KEYS",
":",
"key_path_segments",
"=",
"key_paths",
".",
"SplitKeyPath",
"(",
"mapped_k... | 32.742857 | 0.008475 |
def Then(self, f, *args, **kwargs):
"""
`Then(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
return self.ThenAt(1, f, *args, **kwargs) | [
"def",
"Then",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"ThenAt",
"(",
"1",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 43.6 | 0.013514 |
def cluster_target():
"Not so applicable for this sample"
start_centers = [[0.2, 0.2], [0.0, -2.0], [3.0, -3.0], [3.0, 3.0], [-3.0, 3.0], [-3.0, -3.0]]
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TARGET, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_... | [
"def",
"cluster_target",
"(",
")",
":",
"start_centers",
"=",
"[",
"[",
"0.2",
",",
"0.2",
"]",
",",
"[",
"0.0",
",",
"-",
"2.0",
"]",
",",
"[",
"3.0",
",",
"-",
"3.0",
"]",
",",
"[",
"3.0",
",",
"3.0",
"]",
",",
"[",
"-",
"3.0",
",",
"3.0"... | 83.4 | 0.019002 |
def majority(p, a, b, c):
"""Majority gate."""
p.cx(c, b)
p.cx(c, a)
p.ccx(a, b, c) | [
"def",
"majority",
"(",
"p",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"p",
".",
"cx",
"(",
"c",
",",
"b",
")",
"p",
".",
"cx",
"(",
"c",
",",
"a",
")",
"p",
".",
"ccx",
"(",
"a",
",",
"b",
",",
"c",
")"
] | 19 | 0.010101 |
def fromimage(im, flatten=False, mode=None):
"""
Return a copy of a PIL image as a numpy array.
Parameters
----------
im : PIL image
Input image.
flatten : bool
If true, convert the output to grey-scale.
mode : str, optional
Mode to convert image to, e.g. ``'RGB'``. ... | [
"def",
"fromimage",
"(",
"im",
",",
"flatten",
"=",
"False",
",",
"mode",
"=",
"None",
")",
":",
"if",
"not",
"Image",
".",
"isImageType",
"(",
"im",
")",
":",
"raise",
"TypeError",
"(",
"\"Input is not a PIL image.\"",
")",
"if",
"mode",
"is",
"not",
... | 31.705882 | 0.0006 |
def __display_stats(self):
"""Display some stats regarding unify process"""
self.display('unify.tmpl', processed=self.total,
matched=self.matched,
unified=self.total - self.matched) | [
"def",
"__display_stats",
"(",
"self",
")",
":",
"self",
".",
"display",
"(",
"'unify.tmpl'",
",",
"processed",
"=",
"self",
".",
"total",
",",
"matched",
"=",
"self",
".",
"matched",
",",
"unified",
"=",
"self",
".",
"total",
"-",
"self",
".",
"matche... | 39.166667 | 0.008333 |
def delete(ctx, opts, owner_repo_identifier, yes):
"""
Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your... | [
"def",
"delete",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_identifier",
",",
"yes",
")",
":",
"owner",
",",
"repo",
",",
"identifier",
"=",
"owner_repo_identifier",
"delete_args",
"=",
"{",
"\"identifier\"",
":",
"click",
".",
"style",
"(",
"identifier",
","... | 30.55 | 0.001586 |
def cp(i):
"""
Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID
or
(new_repo_uoa) - new repo UOA
... | [
"def",
"cp",
"(",
"i",
")",
":",
"move",
"=",
"i",
".",
"get",
"(",
"'move'",
",",
"''",
")",
"# Check if global writing is allowed",
"r",
"=",
"check_writing",
"(",
"{",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"imp... | 25.384181 | 0.048619 |
def send(self, s):
'''Sends string ``s`` to the child process, returning the number of
bytes written. If a logfile is specified, a copy is written to that
log.
The default terminal input mode is canonical processing unless set
otherwise by the child process. This allows backspac... | [
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"delaybeforesend",
"is",
"not",
"None",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"delaybeforesend",
")",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"self",
".",
... | 41.255814 | 0.001101 |
def update(self, other, **kwargs):
"""
A dict-like update for Struct attributes.
"""
if other is None: return
if not isinstance(other, dict):
other = other.to_dict()
self.__dict__.update(other, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"other",
",",
"dict",
")",
":",
"other",
"=",
"other",
".",
"to_dict",
"(",
")",
"self",
".... | 28.444444 | 0.011364 |
def write(self, *string):
"""
Writes to the output
"""
self._output.write(' '.join([six.text_type(s) for s in string]))
return self | [
"def",
"write",
"(",
"self",
",",
"*",
"string",
")",
":",
"self",
".",
"_output",
".",
"write",
"(",
"' '",
".",
"join",
"(",
"[",
"six",
".",
"text_type",
"(",
"s",
")",
"for",
"s",
"in",
"string",
"]",
")",
")",
"return",
"self"
] | 27.666667 | 0.011696 |
def process_docstring(app, what, name, obj, options, lines):
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following set... | [
"def",
"process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"result_lines",
"=",
"lines",
"if",
"app",
".",
"config",
".",
"napoleon_numpy_docstring",
":",
"docstring",
"=",
"ExtendedNumpyDocstring",
... | 40.22 | 0.000485 |
def _generate_type_code_query(self, value):
"""Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
S... | [
"def",
"_generate_type_code_query",
"(",
"self",
",",
"value",
")",
":",
"mapping_for_value",
"=",
"self",
".",
"TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"mapping_for_value",
":",
"return",
"generate_match_que... | 45.782609 | 0.008372 |
def _index_param_value(num_samples, v, indices):
"""Private helper function for parameter value indexing.
This determines whether a fit parameter `v` to a SearchCV.fit
should be indexed along with `X` and `y`. Note that this differs
from the scikit-learn version. They pass `X` and compute num_samples.
... | [
"def",
"_index_param_value",
"(",
"num_samples",
",",
"v",
",",
"indices",
")",
":",
"if",
"not",
"_is_arraylike",
"(",
"v",
")",
"or",
"_num_samples",
"(",
"v",
")",
"!=",
"num_samples",
":",
"# pass through: skip indexing",
"return",
"v",
"if",
"sp",
".",
... | 39.214286 | 0.001779 |
def _cal_dist2center(X, center):
""" Calculate the SSE to the cluster center
"""
dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')
return(np.sum(dmemb2cen)) | [
"def",
"_cal_dist2center",
"(",
"X",
",",
"center",
")",
":",
"dmemb2cen",
"=",
"scipy",
".",
"spatial",
".",
"distance",
".",
"cdist",
"(",
"X",
",",
"center",
".",
"reshape",
"(",
"1",
",",
"X",
".",
"shape",
"[",
"1",
"]",
")",
",",
"metric",
... | 42.6 | 0.013825 |
def footprint(config, nside=None):
"""
UNTESTED.
Should return a boolean array representing the pixels in the footprint.
"""
config = Config(config)
if nside is None:
nside = config['coords']['nside_pixel']
elif nside < config['coords']['nside_catalog']:
raise Exception('Requ... | [
"def",
"footprint",
"(",
"config",
",",
"nside",
"=",
"None",
")",
":",
"config",
"=",
"Config",
"(",
"config",
")",
"if",
"nside",
"is",
"None",
":",
"nside",
"=",
"config",
"[",
"'coords'",
"]",
"[",
"'nside_pixel'",
"]",
"elif",
"nside",
"<",
"con... | 41 | 0.008518 |
def delete_element_when_value_none(data_structure):
"""
This method remove all entries in a Python dict when its value is None.
:param data_structure: Python dict (lists are supported). e.i:
[{"element1": "e1",
"element2": {"element2.1": "e2",
"element2.2": ... | [
"def",
"delete_element_when_value_none",
"(",
"data_structure",
")",
":",
"if",
"isinstance",
"(",
"data_structure",
",",
"list",
")",
":",
"for",
"element",
"in",
"data_structure",
":",
"delete_element_when_value_none",
"(",
"element",
")",
"elif",
"isinstance",
"(... | 42.5 | 0.001918 |
def write(self):
"""Write the configuration."""
if self.dirty:
with open(self._cache_path, "w") as output_file:
self._config.write(output_file) | [
"def",
"write",
"(",
"self",
")",
":",
"if",
"self",
".",
"dirty",
":",
"with",
"open",
"(",
"self",
".",
"_cache_path",
",",
"\"w\"",
")",
"as",
"output_file",
":",
"self",
".",
"_config",
".",
"write",
"(",
"output_file",
")"
] | 36.6 | 0.010695 |
def close(self):
"""Flush and close the stream.
This is called automatically by the base resource on resources
unless the resource is operating asynchronously; in that case,
this method MUST be called in order to signal the end of the request.
If not the request will simply hang... | [
"def",
"close",
"(",
"self",
")",
":",
"# Ensure we're not closed.",
"self",
".",
"require_not_closed",
"(",
")",
"if",
"not",
"self",
".",
"streaming",
"or",
"self",
".",
"asynchronous",
":",
"# We're not streaming, auto-write content-length if not",
"# already set.",
... | 36.56 | 0.002132 |
def decode_int(stream, signed=False):
"""
Decode C{int}.
"""
n = result = 0
b = stream.read_uchar()
while b & 0x80 != 0 and n < 3:
result <<= 7
result |= b & 0x7f
b = stream.read_uchar()
n += 1
if n < 3:
result <<= 7
result |= b
else:
... | [
"def",
"decode_int",
"(",
"stream",
",",
"signed",
"=",
"False",
")",
":",
"n",
"=",
"result",
"=",
"0",
"b",
"=",
"stream",
".",
"read_uchar",
"(",
")",
"while",
"b",
"&",
"0x80",
"!=",
"0",
"and",
"n",
"<",
"3",
":",
"result",
"<<=",
"7",
"re... | 18.642857 | 0.001821 |
def indexbox(msg="Shall I continue?"
, title=" "
, choices=("Yes","No")
, image=None
):
"""
Display a buttonbox with the specified choices.
Return the index of the choice selected.
"""
reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
index = -1
for choice... | [
"def",
"indexbox",
"(",
"msg",
"=",
"\"Shall I continue?\"",
",",
"title",
"=",
"\" \"",
",",
"choices",
"=",
"(",
"\"Yes\"",
",",
"\"No\"",
")",
",",
"image",
"=",
"None",
")",
":",
"reply",
"=",
"buttonbox",
"(",
"msg",
"=",
"msg",
",",
"choices",
... | 30.375 | 0.021956 |
def get(cls, **kwargs):
"""Retrieve an object by making a GET request to Transifex.
Each value in `kwargs` that corresponds to a field
defined in `self.url_fields` will be used in the URL path
of the request, so that a particular entry of this model
is identified and retrieved.
... | [
"def",
"get",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"fields",
"=",
"{",
"}",
"for",
"field",
"in",
"cls",
".",
"url_fields",
":",
"value",
"=",
"kwargs",
".",
"pop",
"(",
"field",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"cl... | 38.16129 | 0.001649 |
def set_number_of_atoms( self, n, selected_sites=None ):
"""
Set the number of atoms for the simulation, and populate the simulation lattice.
Args:
n (Int): Number of atoms for this simulation.
selected_sites (:obj:(List|Set|String), optional): Selects a subset of site t... | [
"def",
"set_number_of_atoms",
"(",
"self",
",",
"n",
",",
"selected_sites",
"=",
"None",
")",
":",
"self",
".",
"number_of_atoms",
"=",
"n",
"self",
".",
"atoms",
"=",
"species",
".",
"Species",
"(",
"self",
".",
"lattice",
".",
"populate_sites",
"(",
"s... | 43.153846 | 0.019197 |
def get(self):
'''Called by the protocol consumer'''
if self._current:
return self._resume(self._current, False)
else:
return self._get(None) | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current",
":",
"return",
"self",
".",
"_resume",
"(",
"self",
".",
"_current",
",",
"False",
")",
"else",
":",
"return",
"self",
".",
"_get",
"(",
"None",
")"
] | 30.666667 | 0.010582 |
def canonical(self):
"""Convert URL to its canonical form."""
def full_unescape(u):
uu = urllib.unquote(u)
if uu == u:
return uu
else:
return full_unescape(uu)
def full_unescape_to_bytes(u):
uu = urlparse.unquote_to... | [
"def",
"canonical",
"(",
"self",
")",
":",
"def",
"full_unescape",
"(",
"u",
")",
":",
"uu",
"=",
"urllib",
".",
"unquote",
"(",
"u",
")",
"if",
"uu",
"==",
"u",
":",
"return",
"uu",
"else",
":",
"return",
"full_unescape",
"(",
"uu",
")",
"def",
... | 36.432432 | 0.000722 |
async def _on_event(self, event_):
"""Receive a hangouts_pb2.Event and fan out to Conversations.
Args:
event_: hangouts_pb2.Event instance
"""
conv_id = event_.conversation_id.id
try:
conv = await self._get_or_fetch_conversation(conv_id)
except ex... | [
"async",
"def",
"_on_event",
"(",
"self",
",",
"event_",
")",
":",
"conv_id",
"=",
"event_",
".",
"conversation_id",
".",
"id",
"try",
":",
"conv",
"=",
"await",
"self",
".",
"_get_or_fetch_conversation",
"(",
"conv_id",
")",
"except",
"exceptions",
".",
"... | 38.714286 | 0.002401 |
def handle_symbol_info(self, call_id, payload):
"""Handler for response `SymbolInfo`."""
with catch(KeyError, lambda e: self.editor.message("unknown_symbol")):
decl_pos = payload["declPos"]
f = decl_pos.get("file")
call_options = self.call_options[call_id]
... | [
"def",
"handle_symbol_info",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"with",
"catch",
"(",
"KeyError",
",",
"lambda",
"e",
":",
"self",
".",
"editor",
".",
"message",
"(",
"\"unknown_symbol\"",
")",
")",
":",
"decl_pos",
"=",
"payload",
"[... | 46.782609 | 0.001821 |
def generate_license(template, context):
""" Generate a license by extracting variables from the template and
replacing them with the corresponding values in the given context.
"""
out = StringIO()
content = template.getvalue()
for key in extract_vars(template):
if key not in context... | [
"def",
"generate_license",
"(",
"template",
",",
"context",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"content",
"=",
"template",
".",
"getvalue",
"(",
")",
"for",
"key",
"in",
"extract_vars",
"(",
"template",
")",
":",
"if",
"key",
"not",
"in",
"con... | 43.461538 | 0.001733 |
def get_op_result_name(left, right):
"""
Find the appropriate name to pin to an operation result. This result
should always be either an Index or a Series.
Parameters
----------
left : {Series, Index}
right : object
Returns
-------
name : object
Usually a string
""... | [
"def",
"get_op_result_name",
"(",
"left",
",",
"right",
")",
":",
"# `left` is always a pd.Series when called from within ops",
"if",
"isinstance",
"(",
"right",
",",
"(",
"ABCSeries",
",",
"pd",
".",
"Index",
")",
")",
":",
"name",
"=",
"_maybe_match_name",
"(",
... | 24.285714 | 0.001887 |
def _FetchCustomMappings(descriptor_ls):
"""Find and return all custom mappings for descriptors in descriptor_ls."""
custom_mappings = []
for descriptor in descriptor_ls:
if isinstance(descriptor, ExtendedEnumDescriptor):
custom_mappings.extend(
_FormatCustomJsonMapping('... | [
"def",
"_FetchCustomMappings",
"(",
"descriptor_ls",
")",
":",
"custom_mappings",
"=",
"[",
"]",
"for",
"descriptor",
"in",
"descriptor_ls",
":",
"if",
"isinstance",
"(",
"descriptor",
",",
"ExtendedEnumDescriptor",
")",
":",
"custom_mappings",
".",
"extend",
"(",... | 48.058824 | 0.0012 |
def get_params(job_inis, **kw):
"""
Parse one or more INI-style config files.
:param job_inis:
List of configuration files (or list containing a single zip archive)
:param kw:
Optionally override some parameters
:returns:
A dictionary of parameters
"""
input_zip = No... | [
"def",
"get_params",
"(",
"job_inis",
",",
"*",
"*",
"kw",
")",
":",
"input_zip",
"=",
"None",
"if",
"len",
"(",
"job_inis",
")",
"==",
"1",
"and",
"job_inis",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"input_zip",
"=",
"job_inis",
"... | 34.625 | 0.000702 |
def atoms(lines):
"""Parse atom block into atom objects
Returns:
dict: networkx nodes
"""
# Convert sdf style charge to actual charge
conv_charge_table = {0: 0, 1: 3, 2: 2, 3: 1, 4: 0, 5: -1, 6: -2, 7: -3}
results = {}
for i, line in enumerate(lines):
symbol = line[31:34].rs... | [
"def",
"atoms",
"(",
"lines",
")",
":",
"# Convert sdf style charge to actual charge",
"conv_charge_table",
"=",
"{",
"0",
":",
"0",
",",
"1",
":",
"3",
",",
"2",
":",
"2",
",",
"3",
":",
"1",
",",
"4",
":",
"0",
",",
"5",
":",
"-",
"1",
",",
"6"... | 32 | 0.001011 |
def create_query_index(
self,
design_document_id=None,
index_name=None,
index_type='json',
partitioned=False,
**kwargs
):
"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: Th... | [
"def",
"create_query_index",
"(",
"self",
",",
"design_document_id",
"=",
"None",
",",
"index_name",
"=",
"None",
",",
"index_type",
"=",
"'json'",
",",
"partitioned",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"index_type",
"==",
"JSON_INDEX_TYP... | 52.25 | 0.001084 |
def formdata_encode(fields):
"""Encode fields (a dict) as a multipart/form-data HTTP request
payload. Returns a (content type, request body) pair.
"""
BOUNDARY = '----form-data-boundary-ZmRkNzJkMjUtMjkyMC00'
out = []
for (key, value) in fields.items():
out.append('--' + BOUNDARY)
... | [
"def",
"formdata_encode",
"(",
"fields",
")",
":",
"BOUNDARY",
"=",
"'----form-data-boundary-ZmRkNzJkMjUtMjkyMC00'",
"out",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"value",
")",
"in",
"fields",
".",
"items",
"(",
")",
":",
"out",
".",
"append",
"(",
"'--'",... | 37.3125 | 0.001634 |
def Get(self,key):
"""Get disk by providing mount point or ID
If key is not unique and finds multiple matches only the first
will be returned
"""
for disk in self.disks:
if disk.id == key: return(disk)
elif key in disk.partition_paths: return(disk) | [
"def",
"Get",
"(",
"self",
",",
"key",
")",
":",
"for",
"disk",
"in",
"self",
".",
"disks",
":",
"if",
"disk",
".",
"id",
"==",
"key",
":",
"return",
"(",
"disk",
")",
"elif",
"key",
"in",
"disk",
".",
"partition_paths",
":",
"return",
"(",
"disk... | 25.9 | 0.052239 |
def wbem_request(url, data, creds, cimxml_headers=None, debug=False, x509=None,
verify_callback=None, ca_certs=None,
no_verification=False, timeout=None, recorders=None,
conn_id=None):
# pylint: disable=too-many-arguments,unused-argument
# pylint: disable=too-m... | [
"def",
"wbem_request",
"(",
"url",
",",
"data",
",",
"creds",
",",
"cimxml_headers",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"x509",
"=",
"None",
",",
"verify_callback",
"=",
"None",
",",
"ca_certs",
"=",
"None",
",",
"no_verification",
"=",
"False... | 46.047692 | 0.000131 |
def make_prototype_request(*args, **kwargs):
"""Make a prototype Request for a Matcher."""
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
... | [
"def",
"make_prototype_request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"inspect",
".",
"isclass",
"(",
"args",
"[",
"0",
"]",
")",
"and",
"issubclass",
"(",
"args",
"[",
"0",
"]",
",",
"Request",
")",
":",
"reque... | 39 | 0.002088 |
def get(path, value='', load_path=None):
'''
Get a value for a specific augeas path
CLI Example:
.. code-block:: bash
salt '*' augeas.get /files/etc/hosts/1/ ipaddr
path
The path to get the value of
value
The optional value to get
.. versionadded:: 2016.3.0
... | [
"def",
"get",
"(",
"path",
",",
"value",
"=",
"''",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"ret",
"=",
"{",
"}",
"path",
"=... | 21.162791 | 0.00105 |
def _check_for_api_errors(geocoding_results):
"""
Raise any exceptions if there were problems reported
in the api response.
"""
status_result = geocoding_results.get("STATUS", {})
if "NO_RESULTS" in status_result.get("status", ""):
return
api_call_succ... | [
"def",
"_check_for_api_errors",
"(",
"geocoding_results",
")",
":",
"status_result",
"=",
"geocoding_results",
".",
"get",
"(",
"\"STATUS\"",
",",
"{",
"}",
")",
"if",
"\"NO_RESULTS\"",
"in",
"status_result",
".",
"get",
"(",
"\"status\"",
",",
"\"\"",
")",
":... | 41.631579 | 0.002472 |
def clear(self):
"""Clear the cache"""
with self.lock:
self.relations.clear()
self.schemas.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"relations",
".",
"clear",
"(",
")",
"self",
".",
"schemas",
".",
"clear",
"(",
")"
] | 26.8 | 0.014493 |
def _resolve_assignment_parts(parts, assign_path, context):
"""recursive function to resolve multiple assignments"""
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
# A dictionary in an iterating cont... | [
"def",
"_resolve_assignment_parts",
"(",
"parts",
",",
"assign_path",
",",
"context",
")",
":",
"assign_path",
"=",
"assign_path",
"[",
":",
"]",
"index",
"=",
"assign_path",
".",
"pop",
"(",
"0",
")",
"for",
"part",
"in",
"parts",
":",
"assigned",
"=",
... | 33.710526 | 0.000759 |
def printInvoice(self, REQUEST=None, RESPONSE=None):
"""Print invoice
"""
invoice = self.getInvoice()
invoice_url = invoice.absolute_url()
RESPONSE.redirect('{}/invoice_print'.format(invoice_url)) | [
"def",
"printInvoice",
"(",
"self",
",",
"REQUEST",
"=",
"None",
",",
"RESPONSE",
"=",
"None",
")",
":",
"invoice",
"=",
"self",
".",
"getInvoice",
"(",
")",
"invoice_url",
"=",
"invoice",
".",
"absolute_url",
"(",
")",
"RESPONSE",
".",
"redirect",
"(",
... | 38.5 | 0.008475 |
def eparOptionFactory(master, statusBar, param, defaultParam,
doScroll, fieldWidths,
plugIn=None, editedCallbackObj=None,
helpCallbackObj=None, mainGuiObj=None,
defaultsVerb="Default", bg=None, indent=False,
fl... | [
"def",
"eparOptionFactory",
"(",
"master",
",",
"statusBar",
",",
"param",
",",
"defaultParam",
",",
"doScroll",
",",
"fieldWidths",
",",
"plugIn",
"=",
"None",
",",
"editedCallbackObj",
"=",
"None",
",",
"helpCallbackObj",
"=",
"None",
",",
"mainGuiObj",
"=",... | 38.258065 | 0.000822 |
def _getConfigPath(self):
"""
Gets the currently configured config path.
:return: the path, raises ValueError if it doesn't exist.
"""
confHome = environ.get('VIBE_CONFIG_HOME')
return confHome if confHome is not None else path.join(path.expanduser("~"), '.vibe') | [
"def",
"_getConfigPath",
"(",
"self",
")",
":",
"confHome",
"=",
"environ",
".",
"get",
"(",
"'VIBE_CONFIG_HOME'",
")",
"return",
"confHome",
"if",
"confHome",
"is",
"not",
"None",
"else",
"path",
".",
"join",
"(",
"path",
".",
"expanduser",
"(",
"\"~\"",
... | 43.571429 | 0.009646 |
def get_subset_ids(path):
""" Return a list with ids of all available subsets (based on existing csv-files). """
all = []
for path in glob.glob(os.path.join(path, '*.tsv')):
file_name = os.path.split(path)[1]
basename = os.path.splitext(file_name)[0]
all.appe... | [
"def",
"get_subset_ids",
"(",
"path",
")",
":",
"all",
"=",
"[",
"]",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'*.tsv'",
")",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
... | 34.3 | 0.008523 |
def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if... | [
"def",
"partition_items",
"(",
"count",
",",
"bin_size",
")",
":",
"num_bins",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"count",
"/",
"float",
"(",
"bin_size",
")",
")",
")",
"bins",
"=",
"[",
"0",
"]",
"*",
"num_bins",
"for",
"i",
"in",
"range",... | 25.409091 | 0.031034 |
def _is_string(thing):
"""Check that **thing** is a string. The definition of the latter depends
upon the Python version.
:param thing: The thing to check if it's a string.
:rtype: bool
:returns: ``True`` if **thing** is string (or unicode in Python2).
"""
if (_py3k and isinstance(thing, st... | [
"def",
"_is_string",
"(",
"thing",
")",
":",
"if",
"(",
"_py3k",
"and",
"isinstance",
"(",
"thing",
",",
"str",
")",
")",
":",
"return",
"True",
"if",
"(",
"not",
"_py3k",
"and",
"isinstance",
"(",
"thing",
",",
"basestring",
")",
")",
":",
"return",... | 32.538462 | 0.002299 |
def main(argv=None): # IGNORE:C0111
''' Main Entry '''
by = None
reqres = check_requirements()
if reqres == CheckResult.Error:
perr("Requirement checking failed")
sys.exit(const.EFatal)
try:
result = const.ENoError
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
setuphandlers()
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"# IGNORE:C0111",
"by",
"=",
"None",
"reqres",
"=",
"check_requirements",
"(",
")",
"if",
"reqres",
"==",
"CheckResult",
".",
"Error",
":",
"perr",
"(",
"\"Requirement checking failed\"",
")",
"sys",
".",
... | 32.458647 | 0.031243 |
def replace_wrep(t:str) -> str:
"Replace word repetitions in `t`."
def _replace_wrep(m:Collection[str]) -> str:
c,cc = m.groups()
return f' {TK_WREP} {len(cc.split())+1} {c} '
re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})')
return re_wrep.sub(_replace_wrep, t) | [
"def",
"replace_wrep",
"(",
"t",
":",
"str",
")",
"->",
"str",
":",
"def",
"_replace_wrep",
"(",
"m",
":",
"Collection",
"[",
"str",
"]",
")",
"->",
"str",
":",
"c",
",",
"cc",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"f' {TK_WREP} {len(cc.split(... | 40.285714 | 0.013889 |
def double( self ):
"""Return a new point that is twice the old."""
if self == INFINITY:
return INFINITY
# X9.62 B.3:
p = self.__curve.p()
a = self.__curve.a()
l = ( ( 3 * self.__x * self.__x + a ) * \
numbertheory.inverse_mod( 2 * self.__y, p ) ) % p
x3 = ( l * l - 2 * ... | [
"def",
"double",
"(",
"self",
")",
":",
"if",
"self",
"==",
"INFINITY",
":",
"return",
"INFINITY",
"# X9.62 B.3:",
"p",
"=",
"self",
".",
"__curve",
".",
"p",
"(",
")",
"a",
"=",
"self",
".",
"__curve",
".",
"a",
"(",
")",
"l",
"=",
"(",
"(",
"... | 22.722222 | 0.046948 |
def decrypt_ecb(self, data):
"""
Return an iterator that decrypts `data` using the Electronic Codebook (ECB)
mode of operation.
ECB mode can only operate on `data` that is a multiple of the block-size
in length.
Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes)
... | [
"def",
"decrypt_ecb",
"(",
"self",
",",
"data",
")",
":",
"S1",
",",
"S2",
",",
"S3",
",",
"S4",
"=",
"self",
".",
"S",
"P",
"=",
"self",
".",
"P",
"u4_1_pack",
"=",
"self",
".",
"_u4_1_pack",
"u1_4_unpack",
"=",
"self",
".",
"_u1_4_unpack",
"decry... | 31.818182 | 0.010166 |
def write_stats_file(run_output_dict):
"""Writes a dummy PolyChord format .stats file for tests functions for
processing stats files. This is written to:
base_dir/file_root.stats
Also returns the data in the file as a dict for comparison.
Parameters
----------
run_output_dict: dict
... | [
"def",
"write_stats_file",
"(",
"run_output_dict",
")",
":",
"mandatory_keys",
"=",
"[",
"'file_root'",
",",
"'base_dir'",
"]",
"for",
"key",
"in",
"mandatory_keys",
":",
"assert",
"key",
"in",
"run_output_dict",
",",
"key",
"+",
"' not in run_output_dict'",
"defa... | 38.619565 | 0.000274 |
def create(obj: PersistedObject, obj_type: Type[T], errors: Dict[Type, Exception]):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param errors: a dictiona... | [
"def",
"create",
"(",
"obj",
":",
"PersistedObject",
",",
"obj_type",
":",
"Type",
"[",
"T",
"]",
",",
"errors",
":",
"Dict",
"[",
"Type",
",",
"Exception",
"]",
")",
":",
"e",
"=",
"NoParserFoundForUnionType",
"(",
"'{obj} cannot be parsed as a {typ} because ... | 42.722222 | 0.010178 |
async def stop_async(self):
"""
Stop the EventHubClient and all its Sender/Receiver clients.
"""
log.info("%r: Stopping %r clients", self.container_id, len(self.clients))
self.stopped = True
await self._close_clients_async() | [
"async",
"def",
"stop_async",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"%r: Stopping %r clients\"",
",",
"self",
".",
"container_id",
",",
"len",
"(",
"self",
".",
"clients",
")",
")",
"self",
".",
"stopped",
"=",
"True",
"await",
"self",
".",
... | 38 | 0.011029 |
def acquire_fake_data(number_of_points=1000):
"""
This function generates some fake data and returns two channels of data
in the form
time_array, [channel1, channel2]
"""
# time array
t = _n.linspace(0,10,number_of_points)
return(t, [_n.cos(t)*(1.0+0.2*_n.random.random(number_of_points... | [
"def",
"acquire_fake_data",
"(",
"number_of_points",
"=",
"1000",
")",
":",
"# time array",
"t",
"=",
"_n",
".",
"linspace",
"(",
"0",
",",
"10",
",",
"number_of_points",
")",
"return",
"(",
"t",
",",
"[",
"_n",
".",
"cos",
"(",
"t",
")",
"*",
"(",
... | 32 | 0.012658 |
def pack(self, value=None):
"""Pack the struct in a binary representation.
Merge some fields to ensure correct packing.
If no arguments are set for a particular instance, it is interpreted as
abscence of VLAN information, and the pack() method will return an
empty binary string... | [
"def",
"pack",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"type",
"(",
"self",
")",
")",
":",
"return",
"value",
".",
"pack",
"(",
")",
"if",
"self",
".",
"pcp",
"is",
"None",
"and",
"self",
".",
"c... | 36 | 0.002353 |
def fill_buckets(self):
'''
Get the configured backends and the intervals for any backend which
supports them, and set up the update "buckets". There will be one
bucket for each thing being updated at a given interval.
'''
update_intervals = self.fileserver.update_interva... | [
"def",
"fill_buckets",
"(",
"self",
")",
":",
"update_intervals",
"=",
"self",
".",
"fileserver",
".",
"update_intervals",
"(",
")",
"self",
".",
"buckets",
"=",
"{",
"}",
"for",
"backend",
"in",
"self",
".",
"fileserver",
".",
"backends",
"(",
")",
":",... | 49.884615 | 0.000756 |
def query(self, query=None):
"""
If query is given, modify the URL correspondingly, return the current
query otherwise.
"""
if query is None:
return self.url.query
self.url.query = query | [
"def",
"query",
"(",
"self",
",",
"query",
"=",
"None",
")",
":",
"if",
"query",
"is",
"None",
":",
"return",
"self",
".",
"url",
".",
"query",
"self",
".",
"url",
".",
"query",
"=",
"query"
] | 29.875 | 0.00813 |
def _pkl_finder_objectinfo(
objectinfo,
varinfo,
findercmap,
finderconvolve,
sigclip,
normto,
normmingap,
deredden_object=True,
custom_bandpasses=None,
lclistpkl=None,
nbrradiusarcsec=30.0,
maxnumneighbors=5,
plotdpi... | [
"def",
"_pkl_finder_objectinfo",
"(",
"objectinfo",
",",
"varinfo",
",",
"findercmap",
",",
"finderconvolve",
",",
"sigclip",
",",
"normto",
",",
"normmingap",
",",
"deredden_object",
"=",
"True",
",",
"custom_bandpasses",
"=",
"None",
",",
"lclistpkl",
"=",
"No... | 42.298893 | 0.002365 |
def resolution(self, index):
"""Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionationstates.sc``.
Return... | [
"def",
"resolution",
"(",
"self",
",",
"index",
")",
":",
"@",
"api_query",
"(",
"'resolution'",
",",
"id",
"=",
"str",
"(",
"index",
")",
")",
"async",
"def",
"result",
"(",
"_",
",",
"root",
")",
":",
"elem",
"=",
"root",
".",
"find",
"(",
"'RE... | 29.111111 | 0.002463 |
def _decrypt_and_extract(self, fname):
'''
This does the extraction (e.g., it decrypts the image and writes it to a new file on disk).
'''
with open(fname, "r") as fp_in:
encrypted_data = fp_in.read()
decrypted_data = self._hilink_decrypt(encrypted_data)
... | [
"def",
"_decrypt_and_extract",
"(",
"self",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"r\"",
")",
"as",
"fp_in",
":",
"encrypted_data",
"=",
"fp_in",
".",
"read",
"(",
")",
"decrypted_data",
"=",
"self",
".",
"_hilink_decrypt",
"(",
"e... | 40.181818 | 0.00885 |
def _sparse(self, x, y, sparse):
"""
Method that removes every non sparse th element.
For example:
if this argument was 5, This method would plot the 0th, 5th,
10th ... elements.
Parameters
----------
x : list
list of x values, of length j.
... | [
"def",
"_sparse",
"(",
"self",
",",
"x",
",",
"y",
",",
"sparse",
")",
":",
"tmpX",
"=",
"[",
"]",
"tmpY",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
")",
")",
":",
"if",
"sparse",
"==",
"1",
":",
"return",
"x",
",",
... | 24.714286 | 0.009736 |
def process_match(match, fixed_text, cur, cur_end):
"""Processes a single match in rules"""
# Set our tools
# -- Initial/default value for replace
replace = True
# -- Set check cursor depending on match['type']
if match['type'] == 'prefix':
chk = cur - 1
else:
# suffix
... | [
"def",
"process_match",
"(",
"match",
",",
"fixed_text",
",",
"cur",
",",
"cur_end",
")",
":",
"# Set our tools",
"# -- Initial/default value for replace",
"replace",
"=",
"True",
"# -- Set check cursor depending on match['type']",
"if",
"match",
"[",
"'type'",
"]",
"==... | 38.65625 | 0.001971 |
def connect(self, keyfile=None):
"""Connect to the node via ssh using the paramiko library.
:return: :py:class:`paramiko.SSHClient` - ssh connection or None on
failure
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
... | [
"def",
"connect",
"(",
"self",
",",
"keyfile",
"=",
"None",
")",
":",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"ssh",
".",
"set_missing_host_key_policy",
"(",
"paramiko",
".",
"AutoAddPolicy",
"(",
")",
")",
"if",
"keyfile",
"and",
"os",
".",
... | 43.814815 | 0.001654 |
def _AcquireLock(self,
urn,
blocking=None,
blocking_lock_timeout=None,
lease_time=None,
blocking_sleep_interval=None):
"""This actually acquires the lock for a given URN."""
if urn is None:
raise ValueError("URN... | [
"def",
"_AcquireLock",
"(",
"self",
",",
"urn",
",",
"blocking",
"=",
"None",
",",
"blocking_lock_timeout",
"=",
"None",
",",
"lease_time",
"=",
"None",
",",
"blocking_sleep_interval",
"=",
"None",
")",
":",
"if",
"urn",
"is",
"None",
":",
"raise",
"ValueE... | 31.47619 | 0.013216 |
def _writeclientdoc(doc, thing, forceload=0):
"""Write HTML documentation to a file in the current directory.
"""
docmodule = pydoc.HTMLDoc.docmodule
def strongarm(self, object, name=None, mod=None, *ignored):
result = docmodule(self, object, name, mod, *ignored)
# Grab all the aliases ... | [
"def",
"_writeclientdoc",
"(",
"doc",
",",
"thing",
",",
"forceload",
"=",
"0",
")",
":",
"docmodule",
"=",
"pydoc",
".",
"HTMLDoc",
".",
"docmodule",
"def",
"strongarm",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
... | 40.793103 | 0.009083 |
def handler(self):
"""returns the handler"""
if self._handler is None:
self._handler = self.HTTPSClientAuthHandler(key=self._keyfile,
cert=self._certificatefile)
return self._handler | [
"def",
"handler",
"(",
"self",
")",
":",
"if",
"self",
".",
"_handler",
"is",
"None",
":",
"self",
".",
"_handler",
"=",
"self",
".",
"HTTPSClientAuthHandler",
"(",
"key",
"=",
"self",
".",
"_keyfile",
",",
"cert",
"=",
"self",
".",
"_certificatefile",
... | 44.833333 | 0.010949 |
def get():
"""Subarray list.
This method will list all sub-arrays known to SDP.
"""
_url = get_root_url()
LOG.debug('GET Sub array list')
sub_array_ids = sorted(DB.get_sub_array_ids())
response = dict(sub_arrays=[])
for array_id in sub_array_ids:
array_summary = dict(sub_arrar... | [
"def",
"get",
"(",
")",
":",
"_url",
"=",
"get_root_url",
"(",
")",
"LOG",
".",
"debug",
"(",
"'GET Sub array list'",
")",
"sub_array_ids",
"=",
"sorted",
"(",
"DB",
".",
"get_sub_array_ids",
"(",
")",
")",
"response",
"=",
"dict",
"(",
"sub_arrays",
"="... | 34 | 0.001244 |
def show_menu(self, status_icon, button, activate_time):
"""Show the tray icon menu.
"""
menu = self.get_widget('tray-menu')
menu.popup(None, None, None, Gtk.StatusIcon.position_menu, button, activate_time) | [
"def",
"show_menu",
"(",
"self",
",",
"status_icon",
",",
"button",
",",
"activate_time",
")",
":",
"menu",
"=",
"self",
".",
"get_widget",
"(",
"'tray-menu'",
")",
"menu",
".",
"popup",
"(",
"None",
",",
"None",
",",
"None",
",",
"Gtk",
".",
"StatusIc... | 46.8 | 0.012605 |
def indent(self, space=4):
'''Return an indented Newick string, just like ``nw_indent`` in Newick Utilities
Args:
``space`` (``int``): The number of spaces a tab should equal
Returns:
``str``: An indented Newick string
'''
if not isinstance(space,int):
... | [
"def",
"indent",
"(",
"self",
",",
"space",
"=",
"4",
")",
":",
"if",
"not",
"isinstance",
"(",
"space",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"space must be an int\"",
")",
"if",
"space",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"spac... | 35.208333 | 0.017281 |
def evaluate_at(self, eval_at, testcases, mode=None):
""" Sets the evaluation interation indices.
:param list eval_at: iteration indices where an evaluation should be performed
:param numpy.array testcases: testcases used for evaluation
"""
self.eval_at = eval_at
... | [
"def",
"evaluate_at",
"(",
"self",
",",
"eval_at",
",",
"testcases",
",",
"mode",
"=",
"None",
")",
":",
"self",
".",
"eval_at",
"=",
"eval_at",
"self",
".",
"log",
".",
"eval_at",
"=",
"eval_at",
"if",
"mode",
"is",
"None",
":",
"if",
"self",
".",
... | 37.25 | 0.009162 |
def _determine_stream_spread(self,simple=_USESIMPLE):
"""Determine the spread around the stream track, just sets matrices that describe the covariances"""
allErrCovs= numpy.empty((self._nTrackChunks,6,6))
if self._multi is None:
for ii in range(self._nTrackChunks):
al... | [
"def",
"_determine_stream_spread",
"(",
"self",
",",
"simple",
"=",
"_USESIMPLE",
")",
":",
"allErrCovs",
"=",
"numpy",
".",
"empty",
"(",
"(",
"self",
".",
"_nTrackChunks",
",",
"6",
",",
"6",
")",
")",
"if",
"self",
".",
"_multi",
"is",
"None",
":",
... | 61.15 | 0.020318 |
def summary(self):
"""
Summarize the alignments for this subject.
@return: A C{dict} with C{str} keys:
bestScore: The C{float} best score of the matching reads.
coverage: The C{float} fraction of the subject genome that is
matched by at least one read.
... | [
"def",
"summary",
"(",
"self",
")",
":",
"return",
"{",
"'bestScore'",
":",
"self",
".",
"bestHsp",
"(",
")",
".",
"score",
".",
"score",
",",
"'coverage'",
":",
"self",
".",
"coverage",
"(",
")",
",",
"'hspCount'",
":",
"self",
".",
"hspCount",
"(",... | 43.26087 | 0.001967 |
def add_domain(session, organization, domain_name, is_top_domain=False):
"""Add a domain to the session.
This function adds a new domain to the session using
`domain_name` as its identifier. The new domain will
also be linked to the organization object of `organization`.
Values assigned to `domain... | [
"def",
"add_domain",
"(",
"session",
",",
"organization",
",",
"domain_name",
",",
"is_top_domain",
"=",
"False",
")",
":",
"if",
"domain_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"'domain_name' cannot be None\"",
")",
"if",
"domain_name",
"==",
"'... | 35.942857 | 0.000774 |
def combined_analysis(using):
"""
Combine the analysis in ES with the analysis defined in Python. The one in
Python takes precedence
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return python_analysis
# we... | [
"def",
"combined_analysis",
"(",
"using",
")",
":",
"python_analysis",
"=",
"collect_analysis",
"(",
"using",
")",
"es_analysis",
"=",
"existing_analysis",
"(",
"using",
")",
"if",
"es_analysis",
"==",
"DOES_NOT_EXIST",
":",
"return",
"python_analysis",
"# we want t... | 33.727273 | 0.001311 |
def _init_ca(self):
"""Generate the root ca's cert and key.
"""
if not exists(path_join(self.ca_dir, 'ca.cnf')):
with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh:
fh.write(
CA_CONF_TEMPLATE % (self.get_conf_variables()))
if not exist... | [
"def",
"_init_ca",
"(",
"self",
")",
":",
"if",
"not",
"exists",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'ca.cnf'",
")",
")",
":",
"with",
"open",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'ca.cnf'",
")",
",",
"'w'",
")",
"as"... | 46.409091 | 0.001919 |
def put_settings(self, using=None, **kwargs):
"""
Change specific index level settings in real time.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.put_settings`` unchanged.
"""
return self._get_connection(using).indices.put_settings(index=sel... | [
"def",
"put_settings",
"(",
"self",
",",
"using",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get_connection",
"(",
"using",
")",
".",
"indices",
".",
"put_settings",
"(",
"index",
"=",
"self",
".",
"_name",
",",
"*",
"*"... | 41.375 | 0.008876 |
def crc16_ccitt(data, crc=0):
"""Calculate the crc16 ccitt checksum of some data
A starting crc value may be specified if desired. The input data
is expected to be a sequence of bytes (string) and the output
is an integer in the range (0, 0xFFFF). No packing is done to the
resultant crc value. T... | [
"def",
"crc16_ccitt",
"(",
"data",
",",
"crc",
"=",
"0",
")",
":",
"tab",
"=",
"CRC16_CCITT_TAB",
"# minor optimization (now in locals)",
"for",
"byte",
"in",
"six",
".",
"iterbytes",
"(",
"data",
")",
":",
"crc",
"=",
"(",
"(",
"(",
"crc",
"<<",
"8",
... | 46.066667 | 0.001418 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.