text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def environment(request=None):
"""
Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed
in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context.
"""
context = {
'COMPRESS_ENABLED': settings.COMPRESS_ENABLED,
'SITE_NAME': settings.SITE_NAME,
}
for key in settings.IC... | [
"def",
"environment",
"(",
"request",
"=",
"None",
")",
":",
"context",
"=",
"{",
"'COMPRESS_ENABLED'",
":",
"settings",
".",
"COMPRESS_ENABLED",
",",
"'SITE_NAME'",
":",
"settings",
".",
"SITE_NAME",
",",
"}",
"for",
"key",
"in",
"settings",
".",
"ICEKIT_CO... | 34.333333 | 0.002364 |
def _execute_for_run_dates(self, run_dates, ti_status, executor, pickle_id,
start_date, session=None):
"""
Computes the dag runs and their respective task instances for
the given run dates and executes the task instances.
Returns a list of execution dates o... | [
"def",
"_execute_for_run_dates",
"(",
"self",
",",
"run_dates",
",",
"ti_status",
",",
"executor",
",",
"pickle_id",
",",
"start_date",
",",
"session",
"=",
"None",
")",
":",
"for",
"next_run_date",
"in",
"run_dates",
":",
"dag_run",
"=",
"self",
".",
"_get_... | 44.394737 | 0.00232 |
def get_full_archive_path(self, path):
"""
Returns the full archive path
"""
return os.path.join(self.archive_dir, path.lstrip('/')) | [
"def",
"get_full_archive_path",
"(",
"self",
",",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_dir",
",",
"path",
".",
"lstrip",
"(",
"'/'",
")",
")"
] | 32 | 0.012195 |
def push(path, keep_symlinks=False, upload_path=None, remove_source=False):
'''
WARNING Files pushed to the master will have global read permissions..
Push a file from the minion up to the master, the file will be saved to
the salt master in the master's minion files cachedir
(defaults to ``/var/ca... | [
"def",
"push",
"(",
"path",
",",
"keep_symlinks",
"=",
"False",
",",
"upload_path",
"=",
"None",
",",
"remove_source",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"'Trying to copy \\'%s\\' to master'",
",",
"path",
")",
"if",
"'../'",
"in",
"path",
"... | 38.795699 | 0.001081 |
def verify(self, base_path, update=False):
"""Verify the submission and return testables that can be executed."""
return self.project.verify_submission(base_path, self, update=update) | [
"def",
"verify",
"(",
"self",
",",
"base_path",
",",
"update",
"=",
"False",
")",
":",
"return",
"self",
".",
"project",
".",
"verify_submission",
"(",
"base_path",
",",
"self",
",",
"update",
"=",
"update",
")"
] | 65.666667 | 0.01005 |
def reject(self, reason):
"""Rejects the promise with the given reason."""
if self._state != 'pending':
raise RuntimeError('Promise is no longer pending.')
self.reason = reason
self._state = 'rejected'
errbacks = self._errbacks
self._errbacks = None
f... | [
"def",
"reject",
"(",
"self",
",",
"reason",
")",
":",
"if",
"self",
".",
"_state",
"!=",
"'pending'",
":",
"raise",
"RuntimeError",
"(",
"'Promise is no longer pending.'",
")",
"self",
".",
"reason",
"=",
"reason",
"self",
".",
"_state",
"=",
"'rejected'",
... | 32.818182 | 0.005391 |
def _pirls(self, X, Y, weights):
"""
Performs stable PIRLS iterations to estimate GAM coefficients
Parameters
---------
X : array-like of shape (n_samples, m_features)
containing input data
Y : array-like of shape (n,)
containing target data
... | [
"def",
"_pirls",
"(",
"self",
",",
"X",
",",
"Y",
",",
"weights",
")",
":",
"modelmat",
"=",
"self",
".",
"_modelmat",
"(",
"X",
")",
"# build a basis matrix for the GLM",
"n",
",",
"m",
"=",
"modelmat",
".",
"shape",
"# initialize GLM coefficients if model is... | 34.831776 | 0.007044 |
def sample_bitstrings(self, n_samples):
"""
Sample bitstrings from the distribution defined by the wavefunction.
:param n_samples: The number of bitstrings to sample
:return: An array of shape (n_samples, n_qubits)
"""
possible_bitstrings = np.array(list(itertools.produc... | [
"def",
"sample_bitstrings",
"(",
"self",
",",
"n_samples",
")",
":",
"possible_bitstrings",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"itertools",
".",
"product",
"(",
"(",
"0",
",",
"1",
")",
",",
"repeat",
"=",
"len",
"(",
"self",
")",
")",
")",
... | 45.272727 | 0.007874 |
def eval_objfn(self):
"""Compute components of objective function as well as total
contribution to objective function.
"""
fval = self.obfn_f(self.X)
gval = self.obfn_g(self.X)
obj = fval + gval
return (obj, fval, gval) | [
"def",
"eval_objfn",
"(",
"self",
")",
":",
"fval",
"=",
"self",
".",
"obfn_f",
"(",
"self",
".",
"X",
")",
"gval",
"=",
"self",
".",
"obfn_g",
"(",
"self",
".",
"X",
")",
"obj",
"=",
"fval",
"+",
"gval",
"return",
"(",
"obj",
",",
"fval",
",",... | 29.777778 | 0.007246 |
def _export_prb_file(recording, file_name, format=None, adjacency_distance=None, graph=False, geometry=True, radius=100,
dimensions='all'):
'''Exports .prb file
Parameters
----------
recording: RecordingExtractor
The recording extractor to save probe file from
file_name... | [
"def",
"_export_prb_file",
"(",
"recording",
",",
"file_name",
",",
"format",
"=",
"None",
",",
"adjacency_distance",
"=",
"None",
",",
"graph",
"=",
"False",
",",
"geometry",
"=",
"True",
",",
"radius",
"=",
"100",
",",
"dimensions",
"=",
"'all'",
")",
... | 39.74359 | 0.001888 |
def pull(self):
"""This coroutine handles the server connection, does a basic parse on
the received messages and put them in a queue named events.
The controllers pull method will take the messages from that queue.
"""
self.sock = sockets.Socket()
self.sock.settimeo... | [
"def",
"pull",
"(",
"self",
")",
":",
"self",
".",
"sock",
"=",
"sockets",
".",
"Socket",
"(",
")",
"self",
".",
"sock",
".",
"settimeout",
"(",
"self",
".",
"sock_timo",
")",
"yield",
"events",
".",
"AddCoro",
"(",
"self",
".",
"monitor",
")",
"wh... | 46.742857 | 0.003593 |
def api_model_exists(restApiId, modelName, region=None, key=None, keyid=None, profile=None):
'''
Check to see if the given modelName exists in the given restApiId
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.api_model_exists restApiId modelName
'''
r = describe_api_... | [
"def",
"api_model_exists",
"(",
"restApiId",
",",
"modelName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"r",
"=",
"describe_api_model",
"(",
"restApiId",
",",
"modelName",
",",... | 33.384615 | 0.006726 |
async def lookup(source_id: str, schema_id: str):
"""
Create a new schema object from an existing ledger schema
:param source_id: Institution's personal identification for the schema
:param schema_id: Ledger schema ID for lookup
Example:
source_id = 'foobar123'
n... | [
"async",
"def",
"lookup",
"(",
"source_id",
":",
"str",
",",
"schema_id",
":",
"str",
")",
":",
"try",
":",
"schema",
"=",
"Schema",
"(",
"source_id",
",",
"''",
",",
"''",
",",
"[",
"]",
")",
"if",
"not",
"hasattr",
"(",
"Schema",
".",
"lookup",
... | 41.795455 | 0.002657 |
def to_dict(self):
"""Convert a Traceback into a dictionary representation"""
if self.tb_next is None:
tb_next = None
else:
tb_next = self.tb_next.to_dict()
code = {
'co_filename': self.tb_frame.f_code.co_filename,
'co_name': self.tb_frame... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"tb_next",
"is",
"None",
":",
"tb_next",
"=",
"None",
"else",
":",
"tb_next",
"=",
"self",
".",
"tb_next",
".",
"to_dict",
"(",
")",
"code",
"=",
"{",
"'co_filename'",
":",
"self",
".",
"t... | 28.2 | 0.003431 |
def download_items(cache_fn, start=None):
"""
Open the `cache_fn` as database and download all not-yet downloaded items.
Args:
cache_fn (str): Path to the sqlite database. If not exists, it will be
created.
start (int, default None): If set, start from this sysno.
"""
wi... | [
"def",
"download_items",
"(",
"cache_fn",
",",
"start",
"=",
"None",
")",
":",
"with",
"SqliteDict",
"(",
"cache_fn",
")",
"as",
"db",
":",
"last_id",
"=",
"db",
".",
"get",
"(",
"\"last_id\"",
",",
"0",
")",
"if",
"not",
"start",
"else",
"start",
"_... | 35.230769 | 0.002128 |
def reconnect(self):
'''
Try to reconnect and re-authenticate with the server.
'''
log.debug('Closing the SSH socket.')
try:
self.ssl_skt.close()
except socket.error:
log.error('The socket seems to be closed already.')
log.debug('Re-opening... | [
"def",
"reconnect",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Closing the SSH socket.'",
")",
"try",
":",
"self",
".",
"ssl_skt",
".",
"close",
"(",
")",
"except",
"socket",
".",
"error",
":",
"log",
".",
"error",
"(",
"'The socket seems to be clo... | 32.363636 | 0.005464 |
def from_offset(cls, chunk_type, stream_rdr, offset):
"""
Return an _IHDRChunk instance containing the image dimensions
extracted from the IHDR chunk in *stream* at *offset*.
"""
px_width = stream_rdr.read_long(offset)
px_height = stream_rdr.read_long(offset, 4)
r... | [
"def",
"from_offset",
"(",
"cls",
",",
"chunk_type",
",",
"stream_rdr",
",",
"offset",
")",
":",
"px_width",
"=",
"stream_rdr",
".",
"read_long",
"(",
"offset",
")",
"px_height",
"=",
"stream_rdr",
".",
"read_long",
"(",
"offset",
",",
"4",
")",
"return",
... | 44.375 | 0.005525 |
def consume_assignment_list(self):
self.expect('(')
self.expect('model')
"""Parses a list of expressions from the tokens"""
assignments = []
while True:
next_token = self.tokens.consume()
self.tokens.add_extra_token(next_token) # push it back
... | [
"def",
"consume_assignment_list",
"(",
"self",
")",
":",
"self",
".",
"expect",
"(",
"'('",
")",
"self",
".",
"expect",
"(",
"'model'",
")",
"assignments",
"=",
"[",
"]",
"while",
"True",
":",
"next_token",
"=",
"self",
".",
"tokens",
".",
"consume",
"... | 27.411765 | 0.004149 |
def from_keywords(self, keyword_list, strictness=2, timeout=3):
"""
Generate a sentence from initial_list.
:param list keyword_list: a list of keywords to be included in the sentence.
:param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching
... | [
"def",
"from_keywords",
"(",
"self",
",",
"keyword_list",
",",
"strictness",
"=",
"2",
",",
"timeout",
"=",
"3",
")",
":",
"return",
"self",
".",
"keyword_parse",
".",
"from_keyword_list",
"(",
"keyword_list",
",",
"strictness",
",",
"timeout",
")"
] | 78.538462 | 0.006776 |
def tag_secondary_structure(self, force=False):
"""Tags each `Residue` of the `Polypeptide` with secondary structure.
Notes
-----
DSSP must be available to call. Check by running
`isambard.external_programs.dssp.test_dssp`. If DSSP is not
available, please follow instruc... | [
"def",
"tag_secondary_structure",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"tagged",
"=",
"[",
"'secondary_structure'",
"in",
"x",
".",
"tags",
".",
"keys",
"(",
")",
"for",
"x",
"in",
"self",
".",
"_monomers",
"]",
"if",
"(",
"not",
"all",
... | 38.411765 | 0.001494 |
def _seqcluster_stats(data, out_dir):
"""Parse seqcluster output"""
name = dd.get_sample_name(data)
fn = data.get("seqcluster", {}).get("stat_file", None)
if not fn:
return None
out_file = os.path.join(out_dir, "%s.txt" % name)
df = pd.read_csv(fn, sep="\t", names = ["reads", "sample", "... | [
"def",
"_seqcluster_stats",
"(",
"data",
",",
"out_dir",
")",
":",
"name",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"fn",
"=",
"data",
".",
"get",
"(",
"\"seqcluster\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"stat_file\"",
",",
"None",
"... | 38.090909 | 0.006993 |
def from_attrdict(cls, attrdict: OrderedNamespace) -> object:
"""
Builds a new instance of the ORM object from values in an attrdict.
"""
dictionary = attrdict.__dict__
# noinspection PyArgumentList
return cls(**dictionary) | [
"def",
"from_attrdict",
"(",
"cls",
",",
"attrdict",
":",
"OrderedNamespace",
")",
"->",
"object",
":",
"dictionary",
"=",
"attrdict",
".",
"__dict__",
"# noinspection PyArgumentList",
"return",
"cls",
"(",
"*",
"*",
"dictionary",
")"
] | 37.857143 | 0.00738 |
def _parse_meta_info(self, line):
"""Parse and extract all meta data by looping through the dictionary of meta_info regexs
updates self.meta_info
Args:
line (str): line of the msp file
"""
if self.mslevel:
self.meta_info['ms_level'] = self.mslevel
... | [
"def",
"_parse_meta_info",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"mslevel",
":",
"self",
".",
"meta_info",
"[",
"'ms_level'",
"]",
"=",
"self",
".",
"mslevel",
"if",
"self",
".",
"polarity",
":",
"self",
".",
"meta_info",
"[",
"'polari... | 28.857143 | 0.004792 |
def hardware_port_group_mode_support_multispeed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
port_group = ET.SubElement(hardware, "port-group")
name_ke... | [
"def",
"hardware_port_group_mode_support_multispeed",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hardware\"",
",",
"xmlns",
"="... | 47.5 | 0.004425 |
def sort_dependencies(objects):
"""
Sort a list of instances by their model dependancy graph.
This is very similar to Django's sort_dependencies method except
for two big differences:
1. We graph dependencies unrelated to natural_key.
2. We take a list of objects, and return a sorted list of o... | [
"def",
"sort_dependencies",
"(",
"objects",
")",
":",
"from",
"django",
".",
"db",
".",
"models",
"import",
"get_model",
"# Process the list of models, and get the list of dependencies",
"model_dependencies",
"=",
"[",
"]",
"models",
"=",
"set",
"(",
")",
"model_list"... | 39.525641 | 0.003165 |
def get_zenith(self, channel=0) -> tuple:
"""Get the coordinates, in units, of the maximum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in unit... | [
"def",
"get_zenith",
"(",
"self",
",",
"channel",
"=",
"0",
")",
"->",
"tuple",
":",
"# get channel",
"if",
"isinstance",
"(",
"channel",
",",
"int",
")",
":",
"channel_index",
"=",
"channel",
"elif",
"isinstance",
"(",
"channel",
",",
"str",
")",
":",
... | 31.4 | 0.003708 |
def _get_progress(self):
"""
Get current progress of emerge.
Returns a dict containing current and total value.
"""
input_data = []
ret = {}
# traverse emerge.log from bottom up to get latest information
last_lines = self.py3.command_output(["tail", "-50"... | [
"def",
"_get_progress",
"(",
"self",
")",
":",
"input_data",
"=",
"[",
"]",
"ret",
"=",
"{",
"}",
"# traverse emerge.log from bottom up to get latest information",
"last_lines",
"=",
"self",
".",
"py3",
".",
"command_output",
"(",
"[",
"\"tail\"",
",",
"\"-50\"",
... | 37.636364 | 0.010989 |
def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self... | [
"def",
"item_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"actions",
"=",
"self",
".",
"_item_actions",
".",
"copy",
"(",
")",
"if",
"self",
".",
"_resource",
".",
"is_singular",
":",
"actions",
"[",
"'create'",
"]",
"=",
"(",
"'POST'",
... | 39.75 | 0.004098 |
def _slice_weights(self, arr, li, lh):
"""slice fused rnn weights"""
args = {}
gate_names = self._gate_names
directions = self._directions
b = len(directions)
p = 0
for layer in range(self._num_layers):
for direction in directions:
for... | [
"def",
"_slice_weights",
"(",
"self",
",",
"arr",
",",
"li",
",",
"lh",
")",
":",
"args",
"=",
"{",
"}",
"gate_names",
"=",
"self",
".",
"_gate_names",
"directions",
"=",
"self",
".",
"_directions",
"b",
"=",
"len",
"(",
"directions",
")",
"p",
"=",
... | 40.342105 | 0.006369 |
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage,
key: str,
default: bool = None) -> Optional[bool]:
"""
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``,
other string = ``False``, absent/zero-length stri... | [
"def",
"get_cgi_parameter_bool_or_default",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
",",
"default",
":",
"bool",
"=",
"None",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"s",
"=",
"get_cgi_parameter_str",
"(",
"form",
",",
... | 41.272727 | 0.002155 |
def bar(iter_content, parts, title=''):
""" Iterates over the "iter_content" and draws a progress bar to stdout.
"""
parts = max(float(parts), 1.0)
cells = 10
progress = 0
step = cells / parts
draw = lambda progress: sys.stdout.write(
'\r[{0:10}] {1:.2f}% {2}'.format(
'#... | [
"def",
"bar",
"(",
"iter_content",
",",
"parts",
",",
"title",
"=",
"''",
")",
":",
"parts",
"=",
"max",
"(",
"float",
"(",
"parts",
")",
",",
"1.0",
")",
"cells",
"=",
"10",
"progress",
"=",
"0",
"step",
"=",
"cells",
"/",
"parts",
"draw",
"=",
... | 23.857143 | 0.003839 |
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
"""
if (self.current_retry_attempt_count < self._max_retry_attempt_count) and self.needsRetry(excepti... | [
"def",
"ShouldRetry",
"(",
"self",
",",
"exception",
")",
":",
"if",
"(",
"self",
".",
"current_retry_attempt_count",
"<",
"self",
".",
"_max_retry_attempt_count",
")",
"and",
"self",
".",
"needsRetry",
"(",
"exception",
".",
"status_code",
")",
":",
"self",
... | 32.230769 | 0.006961 |
def boxify(message, border_color=None):
"""Put a message inside a box.
Args:
message (unicode): message to decorate.
border_color (unicode): name of the color to outline the box with.
"""
lines = message.split("\n")
max_width = max(_visual_width(line) for line in lines)
padding... | [
"def",
"boxify",
"(",
"message",
",",
"border_color",
"=",
"None",
")",
":",
"lines",
"=",
"message",
".",
"split",
"(",
"\"\\n\"",
")",
"max_width",
"=",
"max",
"(",
"_visual_width",
"(",
"line",
")",
"for",
"line",
"in",
"lines",
")",
"padding_horizont... | 30.133333 | 0.000714 |
def zan(self, id_reply):
'''
先在外部表中更新,然后更新内部表字段的值。
有冗余,但是查看的时候避免了联合查询
'''
logger.info('zan: {0}'.format(id_reply))
MReply2User.create_reply(self.userinfo.uid, id_reply)
cur_count = MReply2User.get_voter_count(id_reply)
if cur_count:
MReply.up... | [
"def",
"zan",
"(",
"self",
",",
"id_reply",
")",
":",
"logger",
".",
"info",
"(",
"'zan: {0}'",
".",
"format",
"(",
"id_reply",
")",
")",
"MReply2User",
".",
"create_reply",
"(",
"self",
".",
"userinfo",
".",
"uid",
",",
"id_reply",
")",
"cur_count",
"... | 29.055556 | 0.003704 |
def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opene... | [
"def",
"cos_open",
"(",
"file",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"storage_parameters",
"=",
"None",
",",... | 41.810811 | 0.000947 |
def get_range(self, start=None, stop=None):
"""Return a RangeMap for the range start to stop.
Returns:
A RangeMap
"""
return self.from_iterable(self.ranges(start, stop)) | [
"def",
"get_range",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"return",
"self",
".",
"from_iterable",
"(",
"self",
".",
"ranges",
"(",
"start",
",",
"stop",
")",
")"
] | 25 | 0.038674 |
def argspec_args(argspec, constructor, *args, **kwargs):
"""
Return (args, kwargs) matching the argspec object
:param argspec: argspec to use
:type argspec: argspec
:param constructor: is it a constructor ?
:type constructor: bool
:param args:
:type args:
:param kwargs:
:type kw... | [
"def",
"argspec_args",
"(",
"argspec",
",",
"constructor",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"argspec",
".",
"varkw",
":",
"call_kwarg",
"=",
"kwargs",
"else",
":",
"call_kwarg",
"=",
"dict",
"(",
"(",
"k",
",",
"kwargs",
"["... | 30.208333 | 0.002674 |
def add_polyhedron(self, neighbors, center, color, opacity=1.0,
draw_edges=False, edges_color=[0.0, 0.0, 0.0],
edges_linewidth=2):
"""
Adds a polyhedron.
Args:
neighbors: Neighbors of the polyhedron (the vertices).
center: Th... | [
"def",
"add_polyhedron",
"(",
"self",
",",
"neighbors",
",",
"center",
",",
"color",
",",
"opacity",
"=",
"1.0",
",",
"draw_edges",
"=",
"False",
",",
"edges_color",
"=",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
",",
"edges_linewidth",
"=",
"2",
")",
... | 39.636364 | 0.002238 |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
pretty = spaces + 'class ' + self.name
if self.superclasses:
... | [
"def",
"pretty_str",
"(",
"self",
",",
"indent",
"=",
"0",
")",
":",
"spaces",
"=",
"' '",
"*",
"indent",
"pretty",
"=",
"spaces",
"+",
"'class '",
"+",
"self",
".",
"name",
"if",
"self",
".",
"superclasses",
":",
"superclasses",
"=",
"', '",
".",
"j... | 33.2 | 0.002928 |
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cook... | [
"def",
"set_cookie",
"(",
"self",
",",
"name",
",",
"value",
",",
"domain",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"path",
"=",
"\"/\"",
",",
"expires_days",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"cookie_monst... | 43.916667 | 0.007435 |
def _get_attributes_from_managed_object(self, managed_object, attr_names):
"""
Given a kmip.pie object and a list of attribute names, attempt to get
all of the existing attribute values from the object.
"""
attr_factory = attribute_factory.AttributeFactory()
retrieved_att... | [
"def",
"_get_attributes_from_managed_object",
"(",
"self",
",",
"managed_object",
",",
"attr_names",
")",
":",
"attr_factory",
"=",
"attribute_factory",
".",
"AttributeFactory",
"(",
")",
"retrieved_attributes",
"=",
"list",
"(",
")",
"if",
"not",
"attr_names",
":",... | 39.22 | 0.000995 |
def subset_(self, *args):
"""
Returns a Dataswim instance with a subset data based in positions
Select a subset of the main dataframe based on position:
ex: ds.subset(0,10) or ds.subset(10) is equivalent: it starts
at the first row if only one argument is provided
"""
... | [
"def",
"subset_",
"(",
"self",
",",
"*",
"args",
")",
":",
"df",
"=",
"self",
".",
"_subset",
"(",
"*",
"args",
")",
"if",
"df",
"is",
"None",
":",
"self",
".",
"err",
"(",
"\"Can not get subset of data\"",
")",
"return",
"return",
"self",
".",
"_dup... | 38.916667 | 0.004184 |
def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the yesVal or noVal argument, not value.
* value (str): The value being... | [
"def",
"validateBool",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"trueVal",
"=",
"'True'",
",",
"falseVal",
"=",
"'False'",
",",
"caseSensitive",
"=... | 54.98 | 0.006076 |
def wait_for_event(
name,
id_list,
event_id='id',
timeout=300,
node='master'):
'''
Watch Salt's event bus and block until a condition is met
.. versionadded:: 2014.7.0
name
An event tag to watch for; supports Reactor-style globbing.
id_list
A... | [
"def",
"wait_for_event",
"(",
"name",
",",
"id_list",
",",
"event_id",
"=",
"'id'",
",",
"timeout",
"=",
"300",
",",
"node",
"=",
"'master'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
... | 32.716814 | 0.000525 |
def plot(self,init=None):
"""Interactive plotting of parsing features."""
if not init:
init=self
init.plotstats={}
init.unitfeats=self._getFeatValDict()
sels=[]
for k,v in sorted(init.unitfeats.items()):
for kk,vv in v.items():
sels.append((k,kk))
conditions={'x':[],'y':[]}
targets=... | [
"def",
"plot",
"(",
"self",
",",
"init",
"=",
"None",
")",
":",
"if",
"not",
"init",
":",
"init",
"=",
"self",
"init",
".",
"plotstats",
"=",
"{",
"}",
"init",
".",
"unitfeats",
"=",
"self",
".",
"_getFeatValDict",
"(",
")",
"sels",
"=",
"[",
"]"... | 25.675676 | 0.053506 |
def get_composition(self, composition_id):
"""Gets the ``Composition`` specified by its ``Id``.
arg: composition_id (osid.id.Id): ``Id`` of the
``Composiiton``
return: (osid.repository.Composition) - the composition
raise: NotFound - ``composition_id`` not found
... | [
"def",
"get_composition",
"(",
"self",
",",
"composition_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resource",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'repository'",
... | 51.565217 | 0.003311 |
def set_pointing_label(self):
"""Let the label of the current pointing to the value in the plabel box"""
self.pointings[self.current]['label']['text']=w.plabel.get()
self.reset() | [
"def",
"set_pointing_label",
"(",
"self",
")",
":",
"self",
".",
"pointings",
"[",
"self",
".",
"current",
"]",
"[",
"'label'",
"]",
"[",
"'text'",
"]",
"=",
"w",
".",
"plabel",
".",
"get",
"(",
")",
"self",
".",
"reset",
"(",
")"
] | 38 | 0.046392 |
def getCustomLogger(name, logLevel, logFormat='%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'):
'''
Set up logging
:param str name: What log level to set
:param str logLevel: What log level to use
:param str logFormat: Format string for logging
:rtype: logger
'''
assert isin... | [
"def",
"getCustomLogger",
"(",
"name",
",",
"logLevel",
",",
"logFormat",
"=",
"'%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'",
")",
":",
"assert",
"isinstance",
"(",
"logFormat",
",",
"basestring",
")",
",",
"(",
"\"logFormat must be a string ... | 37.068966 | 0.016319 |
def hash_hook(path, options):
"""Hash a hook file"""
with open(path, 'r') as f:
data = f.read()
for key in sorted(iterkeys(options)):
data += '\n#{}={}'.format(key, options.get(key))
return hashlib.md5(data.encode()).hexdigest() | [
"def",
"hash_hook",
"(",
"path",
",",
"options",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"for",
"key",
"in",
"sorted",
"(",
"iterkeys",
"(",
"options",
")",
")",
":",
"dat... | 38 | 0.003676 |
def drop_duplicates(self, keep="first", inplace=False, **kwargs):
"""Return DataFrame with duplicate rows removed, optionally only considering certain columns
Args:
subset : column label or sequence of labels, optional
Only consider certain columns for ident... | [
"def",
"drop_duplicates",
"(",
"self",
",",
"keep",
"=",
"\"first\"",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"\"inplace\"",
")",
"if",
"kwargs",
".",
"get",
"(",
"\"sub... | 51.25 | 0.004789 |
def move_partition(self, partition, broker_destination):
"""Move partition to destination broker and adjust replicas."""
self.remove_partition(partition)
broker_destination.add_partition(partition) | [
"def",
"move_partition",
"(",
"self",
",",
"partition",
",",
"broker_destination",
")",
":",
"self",
".",
"remove_partition",
"(",
"partition",
")",
"broker_destination",
".",
"add_partition",
"(",
"partition",
")"
] | 54.5 | 0.00905 |
def reviewboard(client, channel, nick, message, matches):
"""
Automatically responds to reviewboard urls if a user mentions a pattern
like cr####. Requires REVIEWBOARD_URL to exist in settings with formattable
substring '{review}'
"""
url_fmt = getattr(settings, 'REVIEWBOARD_URL', 'http://localh... | [
"def",
"reviewboard",
"(",
"client",
",",
"channel",
",",
"nick",
",",
"message",
",",
"matches",
")",
":",
"url_fmt",
"=",
"getattr",
"(",
"settings",
",",
"'REVIEWBOARD_URL'",
",",
"'http://localhost/{review}'",
")",
"reviews",
"=",
"[",
"url_fmt",
".",
"f... | 52.777778 | 0.004141 |
def step(self, con=None, path=None, peer_table=None, local_inv=None):
"""
Find peers with stale zonefile inventory data,
and refresh them.
Return True on success
Return False on error
"""
if path is None:
path = self.atlasdb_path
peer_hostpor... | [
"def",
"step",
"(",
"self",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"local_inv",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"atlasdb_path",
"peer_hostports",
"=",
... | 38.05 | 0.007687 |
def info(self, abspath=True):
"""
Return a dictionary with configuration information.
No guarantee is made about which keys exist. Therefore this function
should only be used for testing and debugging.
"""
logger.debug(str(''))
return self._call_and_parse(['info... | [
"def",
"info",
"(",
"self",
",",
"abspath",
"=",
"True",
")",
":",
"logger",
".",
"debug",
"(",
"str",
"(",
"''",
")",
")",
"return",
"self",
".",
"_call_and_parse",
"(",
"[",
"'info'",
",",
"'--json'",
"]",
",",
"abspath",
"=",
"abspath",
")"
] | 38 | 0.005714 |
def list_nodes_min(location=None, call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
... | [
"def",
"list_nodes_min",
"(",
"location",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_min function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"... | 35.162162 | 0.000748 |
def get_invocation_command_nodefault(
toolset, tool, user_provided_command=[], additional_paths=[], path_last=False):
"""
A helper rule to get the command to invoke some tool. If
'user-provided-command' is not given, tries to find binary named 'tool' in
PATH and in the passed 'additional... | [
"def",
"get_invocation_command_nodefault",
"(",
"toolset",
",",
"tool",
",",
"user_provided_command",
"=",
"[",
"]",
",",
"additional_paths",
"=",
"[",
"]",
",",
"path_last",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"toolset",
",",
"basestring",
")... | 47.722222 | 0.008557 |
def plot_points(self, ax,
legend=None,
field=None,
field_function=None,
undefined=0,
**kwargs):
"""
Plotting, but only for points (as opposed to intervals).
"""
ys = [iv.top.z for iv in s... | [
"def",
"plot_points",
"(",
"self",
",",
"ax",
",",
"legend",
"=",
"None",
",",
"field",
"=",
"None",
",",
"field_function",
"=",
"None",
",",
"undefined",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"ys",
"=",
"[",
"iv",
".",
"top",
".",
"z",
... | 27.76 | 0.009749 |
def evaluate(self, dataset, metric="auto",
missing_value_action='auto', with_predictions=False, options={}, **kwargs):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFr... | [
"def",
"evaluate",
"(",
"self",
",",
"dataset",
",",
"metric",
"=",
"\"auto\"",
",",
"missing_value_action",
"=",
"'auto'",
",",
"with_predictions",
"=",
"False",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"missing_value_action... | 42.97619 | 0.003792 |
def deprecated(message, stacklevel=2): # pragma: no cover
"""
Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026
"""
def _decorator(func):
@wraps(func)
def _func(*args, **kwargs):
warnings.warn... | [
"def",
"deprecated",
"(",
"message",
",",
"stacklevel",
"=",
"2",
")",
":",
"# pragma: no cover",
"def",
"_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnin... | 31 | 0.001739 |
def set_pdb_trace(pm=False):
"""Start the Python debugger when robotframework is running.
This makes sure that pdb can use stdin/stdout even though
robotframework has redirected I/O.
"""
import sys
import pdb
for attr in ("stdin", "stdout", "stderr"):
setattr(sys, attr, getattr(sys... | [
"def",
"set_pdb_trace",
"(",
"pm",
"=",
"False",
")",
":",
"import",
"sys",
"import",
"pdb",
"for",
"attr",
"in",
"(",
"\"stdin\"",
",",
"\"stdout\"",
",",
"\"stderr\"",
")",
":",
"setattr",
"(",
"sys",
",",
"attr",
",",
"getattr",
"(",
"sys",
",",
"... | 27.6875 | 0.002183 |
def replace_namespaced_daemon_set(self, name, namespace, body, **kwargs):
"""
replace the specified DaemonSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_daemon_set(n... | [
"def",
"replace_namespaced_daemon_set",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"retu... | 67.6 | 0.004667 |
def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the
TMOC instance.
Parameters
----------
times : `astropy.time.Time`
astropy times to check whe... | [
"def",
"contains",
"(",
"self",
",",
"times",
",",
"keep_inside",
"=",
"True",
",",
"delta_t",
"=",
"DEFAULT_OBSERVATION_TIME",
")",
":",
"# the requested order for filtering the astropy observations table is more precise than the order",
"# of the TimeMoc object",
"current_max_o... | 46.265306 | 0.006048 |
def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]:
"""Executes SQL; returns list of dictionaries, where each dict contains
fieldname/value pairs."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
... | [
"def",
"fetchall_as_dictlist",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
... | 40.5 | 0.003017 |
def variance(self):
'''
Compute variance.
Returns:
variance.
'''
alpha = self.__success + self.__default_alpha
beta = self.__failure + self.__default_beta
try:
variance = alpha * beta / ((alpha + beta) ** 2) * (alpha + beta + 1)
e... | [
"def",
"variance",
"(",
"self",
")",
":",
"alpha",
"=",
"self",
".",
"__success",
"+",
"self",
".",
"__default_alpha",
"beta",
"=",
"self",
".",
"__failure",
"+",
"self",
".",
"__default_beta",
"try",
":",
"variance",
"=",
"alpha",
"*",
"beta",
"/",
"(... | 25.4 | 0.007595 |
def on_next_request(self, py_db, request):
'''
:param NextRequest request:
'''
arguments = request.arguments # : :type arguments: NextArguments
thread_id = arguments.threadId
if py_db.get_use_libraries_filter():
step_cmd_id = CMD_STEP_OVER_MY_CODE
el... | [
"def",
"on_next_request",
"(",
"self",
",",
"py_db",
",",
"request",
")",
":",
"arguments",
"=",
"request",
".",
"arguments",
"# : :type arguments: NextArguments",
"thread_id",
"=",
"arguments",
".",
"threadId",
"if",
"py_db",
".",
"get_use_libraries_filter",
"(",
... | 33.625 | 0.003617 |
def _x_for_spln(x, nx, log_spacing):
"""
Create vector of values to be used in constructing a spline.
Parameters
----------
x : num | num iterable
Resulted values will span the range [min(x), max(x)]
nx : int
Length of returned vector.
log_spacing: bool
False - Creat... | [
"def",
"_x_for_spln",
"(",
"x",
",",
"nx",
",",
"log_spacing",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"xmin",
"=",
"min",
"(",
"x",
")",
"xmax",
"=",
"max",
"(",
"x",
")",
"if",
"xmin",
"==",
"xmax",
":",
"return",
"asarray",
"(",
"[",
... | 32.054795 | 0.001244 |
def _spawn_thread(self, target):
""" Create a thread """
t = Thread(target=target)
t.daemon = True
t.start()
return t | [
"def",
"_spawn_thread",
"(",
"self",
",",
"target",
")",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"target",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"return",
"t"
] | 25.333333 | 0.012739 |
def _checkServer(self, address, port):
"""Check that the TCP Port we've decided to use for tunnelling is available
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
... | [
"def",
"_checkServer",
"(",
"self",
",",
"address",
",",
"port",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_checkServer`` method'",
")",
"# CREATE A TCP SOCKET",
"import",
"socket",
"s",
"=",
"socket",
".",
"socket",
"(",
")",
"self",
... | 37.16129 | 0.00423 |
def execute_file(self, filename):
"""
Execute a file and provide feedback to the user.
:param filename: The pathname of the file to execute (a string).
:returns: Whatever the executed file returns on stdout (a string).
"""
logger.info("Executing file: %s", format_path(fi... | [
"def",
"execute_file",
"(",
"self",
",",
"filename",
")",
":",
"logger",
".",
"info",
"(",
"\"Executing file: %s\"",
",",
"format_path",
"(",
"filename",
")",
")",
"contents",
"=",
"self",
".",
"context",
".",
"execute",
"(",
"filename",
",",
"capture",
"=... | 44.428571 | 0.00315 |
def from_client(catalog, client_id, lowcut, highcut, samp_rate, filt_order,
length, prepick, swin, process_len=86400, data_pad=90,
all_horiz=False, delayed=True, plot=False, debug=0,
return_event=False, min_snr=None):
"""
Generate multiplexed template from FDSN cl... | [
"def",
"from_client",
"(",
"catalog",
",",
"client_id",
",",
"lowcut",
",",
"highcut",
",",
"samp_rate",
",",
"filt_order",
",",
"length",
",",
"prepick",
",",
"swin",
",",
"process_len",
"=",
"86400",
",",
"data_pad",
"=",
"90",
",",
"all_horiz",
"=",
"... | 45.373737 | 0.000218 |
def search(cls, session, queries):
"""Search for a customer given a domain.
Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply... | [
"def",
"search",
"(",
"cls",
",",
"session",
",",
"queries",
")",
":",
"return",
"super",
"(",
"Customers",
",",
"cls",
")",
".",
"search",
"(",
"session",
",",
"queries",
",",
"SearchCustomer",
")"
] | 46.176471 | 0.002497 |
def check_service(self, info):
"""Checks the network for a unique service name, modifying the
ServiceInfo passed in if it is not unique."""
now = current_time_millis()
next_time = now
i = 0
while i < 3:
for record in self.cache.entries_with_name(info.type):
... | [
"def",
"check_service",
"(",
"self",
",",
"info",
")",
":",
"now",
"=",
"current_time_millis",
"(",
")",
"next_time",
"=",
"now",
"i",
"=",
"0",
"while",
"i",
"<",
"3",
":",
"for",
"record",
"in",
"self",
".",
"cache",
".",
"entries_with_name",
"(",
... | 42.121212 | 0.00211 |
def roles_dict(path, repo_prefix="", repo_sub_dir=""):
"""
Return a dict of role names and repo paths.
"""
exit_if_path_not_found(path)
aggregated_roles = {}
roles = os.walk(path).next()[1]
# First scan all directories
for role in roles:
for sub_role in roles_dict(path + "/" +... | [
"def",
"roles_dict",
"(",
"path",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"\"\"",
")",
":",
"exit_if_path_not_found",
"(",
"path",
")",
"aggregated_roles",
"=",
"{",
"}",
"roles",
"=",
"os",
".",
"walk",
"(",
"path",
")",
".",
"next",
... | 29.92 | 0.001295 |
def stack(datasets):
"""First dataset at the bottom."""
base = datasets[0].copy()
for dataset in datasets[1:]:
base = base.where(dataset.isnull(), dataset)
return base | [
"def",
"stack",
"(",
"datasets",
")",
":",
"base",
"=",
"datasets",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"for",
"dataset",
"in",
"datasets",
"[",
"1",
":",
"]",
":",
"base",
"=",
"base",
".",
"where",
"(",
"dataset",
".",
"isnull",
"(",
")",
"... | 31 | 0.005236 |
def get_ordered_children(self):
"""
Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>`
"""
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
chil... | [
"def",
"get_ordered_children",
"(",
"self",
")",
":",
"ordered_keys",
"=",
"self",
".",
"element",
".",
"ordered_children",
"if",
"self",
".",
"element",
".",
"ordered_children",
"is",
"not",
"None",
"else",
"[",
"]",
"children",
"=",
"[",
"self",
".",
"in... | 43.555556 | 0.0075 |
def compile_action_preconditions(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> List[TensorFluent]:
'''Compiles the action preconditions given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
... | [
"def",
"compile_action_preconditions",
"(",
"self",
",",
"state",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
",",
"action",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
")",
"->",
"List",
"[",
"TensorFluent",
"]",
":",
"scope",
"=",
"self",
"."... | 40.75 | 0.004796 |
def evaluate_mrz():
"""
A script for evaluating the current MRZ recognition pipeline by applying it to a list of files in a directory and reporting how well it went.
"""
parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the sample test data, reporting the quality sum... | [
"def",
"evaluate_mrz",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run the MRZ OCR recognition algorithm on the sample test data, reporting the quality summary.'",
")",
"parser",
".",
"add_argument",
"(",
"'-j'",
",",
"'--jobs... | 53.655914 | 0.003935 |
def reboot(name, call=None):
'''
Reboot a node.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot mymachine
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'RebootInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
... | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"instance_id",
"=",
"_get_node",
"(",
"name",
")",
"[",
"'instanceId'",
"]",
"params",
"=",
"{",
"'Action'",
":",
"'RebootInstances'",
",",
"'InstanceId.1'",
":",
"instance_id",
"}",
"result... | 23.4 | 0.001642 |
def get_mapping(repo, content_type):
"""
Return an ES mapping for a content type in a repository.
:param Repo repo:
This git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_mappings',
'... | [
"def",
"get_mapping",
"(",
"repo",
",",
"content_type",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo",
".",
"working_dir",
",",
"'_mappings'",
",",
"'%s.json'",
"%",
"(",
"content_type",
",",
")",
")",
",",
"'... | 28 | 0.00216 |
def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): # pylint: disable=too-many-arguments
"""Find Notes based on the specified criteria.
Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the ... | [
"def",
"find",
"(",
"self",
",",
"query",
"=",
"None",
",",
"func",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"colors",
"=",
"None",
",",
"pinned",
"=",
"None",
",",
"archived",
"=",
"None",
",",
"trashed",
"=",
"False",
")",
":",
"# pylint: di... | 51.485714 | 0.009259 |
def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs):
"""
Clean text string of simbols only alphanumeric chars.
"""
clean_str = re.sub(r'[^\w{}]'.format(
"".join(exclusion)), separate_char, text.strip()) or ''
clean_lowerbar = clean_str_without_accent... | [
"def",
"normalizer",
"(",
"text",
",",
"exclusion",
"=",
"OPERATIONS_EXCLUSION",
",",
"lower",
"=",
"True",
",",
"separate_char",
"=",
"'-'",
",",
"*",
"*",
"kwargs",
")",
":",
"clean_str",
"=",
"re",
".",
"sub",
"(",
"r'[^\\w{}]'",
".",
"format",
"(",
... | 35.875 | 0.003394 |
def list_upgrades(refresh=True, **kwargs):
'''
Check whether or not an upgrade is available for all packages
The ``fromrepo``, ``enablerepo``, and ``disablerepo`` arguments are
supported, as used in pkg states, and the ``disableexcludes`` option is
also supported.
.. versionadded:: 2014.7.0
... | [
"def",
"list_upgrades",
"(",
"refresh",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"_get_options",
"(",
"*",
"*",
"kwargs",
")",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"refresh",
")",
":",
"refresh_db",
"("... | 28.733333 | 0.001122 |
def set_comments(self):
"""Parses comments and set value."""
try:
self.comments = self.soup.find('comments').string
except AttributeError:
self.comments = None | [
"def",
"set_comments",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"comments",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'comments'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"comments",
"=",
"None"
] | 33.666667 | 0.009662 |
def _output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
[self._validate_channel(pin) for pin in pins.keys()]
# Set e... | [
"def",
"_output_pins",
"(",
"self",
",",
"pins",
")",
":",
"[",
"self",
".",
"_validate_channel",
"(",
"pin",
")",
"for",
"pin",
"in",
"pins",
".",
"keys",
"(",
")",
"]",
"# Set each changed pin's bit.",
"for",
"pin",
",",
"value",
"in",
"iter",
"(",
"... | 42.214286 | 0.008278 |
def match_alignment_and_tree_sequence_ids(self, sequence_names, tree):
'''Check to make sure that the sequences specified in the alignment
and the tree are the same, otherwise raise an Exception detailing
the problem for the user to fix
Parameters
----------
sequence_nam... | [
"def",
"match_alignment_and_tree_sequence_ids",
"(",
"self",
",",
"sequence_names",
",",
"tree",
")",
":",
"tip_names_count",
"=",
"{",
"}",
"for",
"t",
"in",
"tree",
".",
"leaf_node_iter",
"(",
")",
":",
"# replace spaces with underscores as this is how they are given ... | 43.5 | 0.005622 |
def loads(self, data):
"""
Deserializes the given byte array into an object and returns it.
"""
st = BytesIO(data)
try:
return self.load(st)
finally:
st.close() | [
"def",
"loads",
"(",
"self",
",",
"data",
")",
":",
"st",
"=",
"BytesIO",
"(",
"data",
")",
"try",
":",
"return",
"self",
".",
"load",
"(",
"st",
")",
"finally",
":",
"st",
".",
"close",
"(",
")"
] | 24.888889 | 0.008621 |
def excepts(cls):
"""Return tuple of underlying exception classes to trap and wrap.
:rtype: ``tuple`` of ``type``
"""
if cls._excepts is None:
cls._excepts = tuple(cls.translations.keys())
return cls._excepts | [
"def",
"excepts",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_excepts",
"is",
"None",
":",
"cls",
".",
"_excepts",
"=",
"tuple",
"(",
"cls",
".",
"translations",
".",
"keys",
"(",
")",
")",
"return",
"cls",
".",
"_excepts"
] | 31.75 | 0.007663 |
def nl_nlmsg_flags2str(flags, buf, _=None):
"""Netlink Message Flags Translations.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L664
Positional arguments:
flags -- integer.
buf -- bytearray().
Keyword arguments:
_ -- unused.
Returns:
Reference to `buf`.
"""
... | [
"def",
"nl_nlmsg_flags2str",
"(",
"flags",
",",
"buf",
",",
"_",
"=",
"None",
")",
":",
"del",
"buf",
"[",
":",
"]",
"all_flags",
"=",
"(",
"(",
"'REQUEST'",
",",
"libnl",
".",
"linux_private",
".",
"netlink",
".",
"NLM_F_REQUEST",
")",
",",
"(",
"'M... | 32.333333 | 0.00077 |
def update_alias(self, addressid, data):
"""Update alias address"""
return self.api_call(
ENDPOINTS['aliases']['update'],
dict(addressid=addressid),
body=data) | [
"def",
"update_alias",
"(",
"self",
",",
"addressid",
",",
"data",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"ENDPOINTS",
"[",
"'aliases'",
"]",
"[",
"'update'",
"]",
",",
"dict",
"(",
"addressid",
"=",
"addressid",
")",
",",
"body",
"=",
"data... | 34.333333 | 0.009479 |
def get_bytes(obj):
"""
Infers the input type and reads the first 262 bytes,
returning a sliced bytearray.
Args:
obj: path to readable, file, bytes or bytearray.
Returns:
First 262 bytes of the file content as bytearray type.
Raises:
TypeError: if obj is not a supporte... | [
"def",
"get_bytes",
"(",
"obj",
")",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"read",
"(",
"_NUM_SIGNATURE_BYTES",
")",
"except",
"AttributeError",
":",
"# duck-typing as readable failed - we'll try the other options",
"pass",
"kind",
"=",
"type",
"(",
"obj",
")",... | 22.628571 | 0.001211 |
def safe_mkdir(directory, clean=False):
"""Safely create a directory.
Ensures a directory is present. If it's not there, it is created. If it
is, it's a no-op. If clean is True, ensures the directory is empty.
"""
if clean:
safe_rmtree(directory)
try:
os.makedirs(directory)
except OSError as e:... | [
"def",
"safe_mkdir",
"(",
"directory",
",",
"clean",
"=",
"False",
")",
":",
"if",
"clean",
":",
"safe_rmtree",
"(",
"directory",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"err... | 27.076923 | 0.016484 |
def leave_group(self, group_alias):
"""
退出小组
:param group_alias: 小组ID
:return:
"""
return self.api.req(API_GROUP_GROUP_HOME % group_alias, params={
'action': 'quit',
'ck': self.api.ck(),
}) | [
"def",
"leave_group",
"(",
"self",
",",
"group_alias",
")",
":",
"return",
"self",
".",
"api",
".",
"req",
"(",
"API_GROUP_GROUP_HOME",
"%",
"group_alias",
",",
"params",
"=",
"{",
"'action'",
":",
"'quit'",
",",
"'ck'",
":",
"self",
".",
"api",
".",
"... | 24.454545 | 0.014337 |
def apply_activation(
books,
x,
activation,
activation_args=(),
activation_kwargs=None):
"""Returns activation(x, *activation_args, **activation_kwargs).
This applies the given activation and adds useful summaries specific to the
activation.
Args:
books: The bookkeeper.
x: The tens... | [
"def",
"apply_activation",
"(",
"books",
",",
"x",
",",
"activation",
",",
"activation_args",
"=",
"(",
")",
",",
"activation_kwargs",
"=",
"None",
")",
":",
"if",
"activation",
"is",
"None",
":",
"return",
"x",
"if",
"activation_kwargs",
"is",
"None",
":"... | 34.142857 | 0.00678 |
def get_templates(self):
"""
Return a list of template_dicts based on the config.yaml in
$self.base_path. Keys correspond to templates and values represent
further settings regarding each template. A pystache object containing
the parsed corresponding mustache file is added to th... | [
"def",
"get_templates",
"(",
"self",
")",
":",
"config_path",
"=",
"rel_to_cwd",
"(",
"self",
".",
"base_path",
",",
"'templates'",
",",
"'config.yaml'",
")",
"templates",
"=",
"get_yaml_dict",
"(",
"config_path",
")",
"for",
"temp",
",",
"sub",
"in",
"templ... | 52.214286 | 0.002688 |
def _get_outputs(self):
"""List all the output NDArray.
Returns
-------
A list of ndarray bound to the heads of executor.
"""
out_size = mx_uint()
handles = ctypes.POINTER(NDArrayHandle)()
check_call(_LIB.MXExecutorOutputs(self.handle,
... | [
"def",
"_get_outputs",
"(",
"self",
")",
":",
"out_size",
"=",
"mx_uint",
"(",
")",
"handles",
"=",
"ctypes",
".",
"POINTER",
"(",
"NDArrayHandle",
")",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXExecutorOutputs",
"(",
"self",
".",
"handle",
",",
"ctyp... | 37.357143 | 0.007463 |
def miraligner(args):
"""
Realign BAM hits to miRBAse to get better accuracy and annotation
"""
hairpin, mirna = _download_mirbase(args)
precursors = _read_precursor(args.hairpin, args.sps)
matures = _read_mature(args.mirna, args.sps)
gtf = _read_gtf(args.gtf)
out_dts = []
out_files ... | [
"def",
"miraligner",
"(",
"args",
")",
":",
"hairpin",
",",
"mirna",
"=",
"_download_mirbase",
"(",
"args",
")",
"precursors",
"=",
"_read_precursor",
"(",
"args",
".",
"hairpin",
",",
"args",
".",
"sps",
")",
"matures",
"=",
"_read_mature",
"(",
"args",
... | 37.57377 | 0.00085 |
def parse_napp(napp_id):
"""Convert a napp_id in tuple with username, napp name and version.
Args:
napp_id: String with the form 'username/napp[:version]' (version is
optional). If no version is found, it will be None.
Returns:
tuple: A tuple with (username, napp, version... | [
"def",
"parse_napp",
"(",
"napp_id",
")",
":",
"# `napp_id` regex, composed by two mandatory parts (username, napp_name)",
"# and one optional (version).",
"# username and napp_name need to start with a letter, are composed of",
"# letters, numbers and uderscores and must have at least three chara... | 36.451613 | 0.000862 |
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 452... | [
"def",
"_update_discovery_config",
"(",
"opts",
")",
":",
"if",
"opts",
".",
"get",
"(",
"'discovery'",
")",
"not",
"in",
"(",
"None",
",",
"False",
")",
":",
"if",
"opts",
"[",
"'discovery'",
"]",
"is",
"True",
":",
"opts",
"[",
"'discovery'",
"]",
... | 44 | 0.004944 |
def update(self, id, newObj):
"""Update a object
Args:
id (int): Target Object ID
newObj (object): New object will be merged into original object
Returns:
Object: Updated object
None: If specified object id is not found
... | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"newObj",
")",
":",
"newObj",
"=",
"self",
".",
"validation",
"(",
"newObj",
")",
"for",
"obj",
"in",
"self",
".",
"model",
".",
"db",
":",
"if",
"obj",
"[",
"\"id\"",
"]",
"!=",
"id",
":",
"continue"... | 31.869565 | 0.002649 |
def crypto_core_ed25519_is_valid_point(p):
"""
Check if ``p`` represents a point on the edwards25519 curve, in canonical
form, on the main subgroup, and that the point doesn't have a small order.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on... | [
"def",
"crypto_core_ed25519_is_valid_point",
"(",
"p",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"p",
",",
"bytes",
")",
"and",
"len",
"(",
"p",
")",
"==",
"crypto_core_ed25519_BYTES",
",",
"'Point must be a crypto_core_ed25519_BYTES long bytes sequence'",
",",
"rai... | 36.277778 | 0.001493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.