text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _agate_to_schema(self, agate_table, column_override):
"""Convert agate.Table with column names to a list of bigquery schemas.
"""
bq_schema = []
for idx, col_name in enumerate(agate_table.column_names):
inferred_type = self.convert_agate_type(agate_table, idx)
... | [
"def",
"_agate_to_schema",
"(",
"self",
",",
"agate_table",
",",
"column_override",
")",
":",
"bq_schema",
"=",
"[",
"]",
"for",
"idx",
",",
"col_name",
"in",
"enumerate",
"(",
"agate_table",
".",
"column_names",
")",
":",
"inferred_type",
"=",
"self",
".",
... | 45.363636 | 17.545455 |
def _find_model(self, constructor, table_name, constraints=None, *, columns=None, order_by=None):
"""Calls DataAccess.find and passes the results to the given constructor."""
data = self.find(table_name, constraints, columns=columns, order_by=order_by)
return constructor(data) if data else None | [
"def",
"_find_model",
"(",
"self",
",",
"constructor",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"find",
"(",
"table_name",
",",
"constra... | 76 | 26 |
def listDF(option='mostactive', token='', version=''):
'''Returns an array of quotes for the top 10 symbols in a specified list.
https://iexcloud.io/docs/api/#list
Updated intraday
Args:
option (string); Option to query
token (string); Access token
version (string); API versio... | [
"def",
"listDF",
"(",
"option",
"=",
"'mostactive'",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"list",
"(",
"option",
",",
"token",
",",
"version",
")",
")",
"_toDatetime",
"(",
"df",
")",... | 24.421053 | 22.105263 |
def get_weighted_random_index(self,weights):
"""Return an index of an array based on the weights
if a random number between 0 and 1 is less than an index return the lowest index
:param weights: a list of floats for how to weight each index [w1, w2, ... wN]
:type weights: list
:return: index
... | [
"def",
"get_weighted_random_index",
"(",
"self",
",",
"weights",
")",
":",
"tot",
"=",
"float",
"(",
"sum",
"(",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"weights",
"]",
")",
")",
"fracarray",
"=",
"[",
"weights",
"[",
"0",
"]",
"]",
"for",
... | 33.333333 | 16.857143 |
def _set_compact_flash(self, v, load=False):
"""
Setter method for compact_flash, mapped from YANG variable /system_monitor/compact_flash (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_compact_flash is considered as a private
method. Backends looking to ... | [
"def",
"_set_compact_flash",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 80.727273 | 37.545455 |
def __ensure_provisioning_alarm(table_name, key_name):
""" Ensure that provisioning alarm threshold is not exceeded
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
"""
lookback_window_start = get_table_op... | [
"def",
"__ensure_provisioning_alarm",
"(",
"table_name",
",",
"key_name",
")",
":",
"lookback_window_start",
"=",
"get_table_option",
"(",
"key_name",
",",
"'lookback_window_start'",
")",
"lookback_period",
"=",
"get_table_option",
"(",
"key_name",
",",
"'lookback_period'... | 40.923913 | 15.673913 |
def redo(self):
"""
Redo the latest undone command.
"""
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack)) | [
"def",
"redo",
"(",
"self",
")",
":",
"self",
".",
"undo_manager",
".",
"redo",
"(",
")",
"self",
".",
"notify_observers",
"(",
")",
"logging",
".",
"debug",
"(",
"'undo_manager redo stack={}'",
".",
"format",
"(",
"self",
".",
"undo_manager",
".",
"_redo_... | 32.571429 | 13.142857 |
def result(retn):
'''
Return a value or raise an exception from a retn tuple.
'''
ok, valu = retn
if ok:
return valu
name, info = valu
ctor = getattr(s_exc, name, None)
if ctor is not None:
raise ctor(**info)
info['errx'] = name
raise s_exc.SynErr(**info) | [
"def",
"result",
"(",
"retn",
")",
":",
"ok",
",",
"valu",
"=",
"retn",
"if",
"ok",
":",
"return",
"valu",
"name",
",",
"info",
"=",
"valu",
"ctor",
"=",
"getattr",
"(",
"s_exc",
",",
"name",
",",
"None",
")",
"if",
"ctor",
"is",
"not",
"None",
... | 17.588235 | 24.647059 |
def random_choices(self, elements=('a', 'b', 'c'), length=None):
"""
Returns a list of random, non-unique elements from a passed object.
If `elements` is a dictionary, the value will be used as
a weighting element. For example::
random_element({"{{variable_1}}": 0.5, "{{var... | [
"def",
"random_choices",
"(",
"self",
",",
"elements",
"=",
"(",
"'a'",
",",
"'b'",
",",
"'c'",
")",
",",
"length",
"=",
"None",
")",
":",
"return",
"self",
".",
"random_elements",
"(",
"elements",
",",
"length",
",",
"unique",
"=",
"False",
")"
] | 39.470588 | 21.705882 |
def start_coordsys(self):
"""
Coordinate system at start of effect.
All axes are parallel to the original vector evaluation location, with
the origin moved to this effect's start point.
:return: coordinate system at start of effect
:rtype: :class:`CoordSys`
"""
... | [
"def",
"start_coordsys",
"(",
"self",
")",
":",
"coordsys",
"=",
"copy",
"(",
"self",
".",
"location",
")",
"coordsys",
".",
"origin",
"=",
"self",
".",
"start_point",
"return",
"coordsys"
] | 31.769231 | 14.846154 |
def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only fi... | [
"def",
"list_objects",
"(",
"self",
",",
"path",
"=",
"''",
",",
"relative",
"=",
"False",
",",
"first_level",
"=",
"False",
",",
"max_request_entries",
"=",
"None",
")",
":",
"entries",
"=",
"0",
"next_values",
"=",
"[",
"]",
"max_request_entries_arg",
"=... | 32.328571 | 19.5 |
def upgrade_plan(self, subid, vpsplanid, params=None):
''' /v1/server/upgrade_plan
POST - account
Upgrade the plan of a virtual machine. The virtual machine will be
rebooted upon a successful upgrade.
Link: https://www.vultr.com/api/#server_upgrade_plan
'''
param... | [
"def",
"upgrade_plan",
"(",
"self",
",",
"subid",
",",
"vpsplanid",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"update_params",
"(",
"params",
",",
"{",
"'SUBID'",
":",
"subid",
",",
"'VPSPLANID'",
":",
"vpsplanid",
"}",
")",
"return",
"self",
... | 36.923077 | 18.615385 |
def extract(self, text: str = None,
extract_first_date_only: bool = False,
additional_formats: List[str] = list(),
use_default_formats: bool = False,
ignore_dates_before: datetime.datetime = None,
ignore_dates_after: datetime.datetime = Non... | [
"def",
"extract",
"(",
"self",
",",
"text",
":",
"str",
"=",
"None",
",",
"extract_first_date_only",
":",
"bool",
"=",
"False",
",",
"additional_formats",
":",
"List",
"[",
"str",
"]",
"=",
"list",
"(",
")",
",",
"use_default_formats",
":",
"bool",
"=",
... | 54.137931 | 26.082759 |
def begin_transaction(
self,
database,
options_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Starts a new transaction.
Example:
>>> from google.cloud im... | [
"def",
"begin_transaction",
"(",
"self",
",",
"database",
",",
"options_",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"m... | 41.571429 | 25 |
def set_affinity_matrix(self, affinity_mat):
"""
Parameters
----------
affinity_mat : sparse matrix (N_obs, N_obs).
The adjacency matrix to input.
"""
affinity_mat = check_array(affinity_mat, accept_sparse=sparse_formats)
if affinity_mat.shape[0] != af... | [
"def",
"set_affinity_matrix",
"(",
"self",
",",
"affinity_mat",
")",
":",
"affinity_mat",
"=",
"check_array",
"(",
"affinity_mat",
",",
"accept_sparse",
"=",
"sparse_formats",
")",
"if",
"affinity_mat",
".",
"shape",
"[",
"0",
"]",
"!=",
"affinity_mat",
".",
"... | 39.636364 | 12.909091 |
def inverse_distance_to_grid(xp, yp, variable, grid_x, grid_y, r, gamma=None, kappa=None,
min_neighbors=3, kind='cressman'):
r"""Generate an inverse distance interpolation of the given points to a regular grid.
Values are assigned to the given grid using inverse distance weighting ... | [
"def",
"inverse_distance_to_grid",
"(",
"xp",
",",
"yp",
",",
"variable",
",",
"grid_x",
",",
"grid_y",
",",
"r",
",",
"gamma",
"=",
"None",
",",
"kappa",
"=",
"None",
",",
"min_neighbors",
"=",
"3",
",",
"kind",
"=",
"'cressman'",
")",
":",
"# Handle ... | 39.36 | 23.72 |
def is_existing_object(did):
"""Return True if PID is for an object for which science bytes are stored locally.
This excludes SIDs and PIDs for unprocessed replica requests, remote or non-existing
revisions of local replicas and objects aggregated in Resource Maps.
"""
return d1_gmn.app.models.Sci... | [
"def",
"is_existing_object",
"(",
"did",
")",
":",
"return",
"d1_gmn",
".",
"app",
".",
"models",
".",
"ScienceObject",
".",
"objects",
".",
"filter",
"(",
"pid__did",
"=",
"did",
")",
".",
"exists",
"(",
")"
] | 45.125 | 26.5 |
def isoformat(self):
"""Return the date formatted according to ISO.
This is 'YYYY-MM-DD'.
References:
- http://www.w3.org/TR/NOTE-datetime
- http://www.cl.cam.ac.uk/~mgk25/iso-time.html
"""
# return "%04d-%02d-%02d" % (self._year, self._month, self._day)
... | [
"def",
"isoformat",
"(",
"self",
")",
":",
"# return \"%04d-%02d-%02d\" % (self._year, self._month, self._day)",
"return",
"\"%s-%s-%s\"",
"%",
"(",
"str",
"(",
"self",
".",
"_year",
")",
".",
"zfill",
"(",
"4",
")",
",",
"str",
"(",
"self",
".",
"_month",
")"... | 37.181818 | 22.545455 |
def execute_sql_statement(sql_statement, query, user_name, session, cursor):
"""Executes a single SQL statement"""
database = query.database
db_engine_spec = database.db_engine_spec
parsed_query = ParsedQuery(sql_statement)
sql = parsed_query.stripped()
SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW... | [
"def",
"execute_sql_statement",
"(",
"sql_statement",
",",
"query",
",",
"user_name",
",",
"session",
",",
"cursor",
")",
":",
"database",
"=",
"query",
".",
"database",
"db_engine_spec",
"=",
"database",
".",
"db_engine_spec",
"parsed_query",
"=",
"ParsedQuery",
... | 43.287879 | 19.484848 |
def get_git_version(git_path=None):
"""
Get the Git version.
"""
if git_path is None: git_path = GIT_PATH
git_version = check_output([git_path, "--version"]).split()[2]
return git_version | [
"def",
"get_git_version",
"(",
"git_path",
"=",
"None",
")",
":",
"if",
"git_path",
"is",
"None",
":",
"git_path",
"=",
"GIT_PATH",
"git_version",
"=",
"check_output",
"(",
"[",
"git_path",
",",
"\"--version\"",
"]",
")",
".",
"split",
"(",
")",
"[",
"2"... | 29.285714 | 9.857143 |
def new_stat(self):
"""Look at the key and value that the user has entered into the stat
configurator, and set them on the currently selected
entity.
"""
key = self.ids.newstatkey.text
value = self.ids.newstatval.text
if not (key and value):
# TODO im... | [
"def",
"new_stat",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"ids",
".",
"newstatkey",
".",
"text",
"value",
"=",
"self",
".",
"ids",
".",
"newstatval",
".",
"text",
"if",
"not",
"(",
"key",
"and",
"value",
")",
":",
"# TODO implement some feedba... | 34.555556 | 12.055556 |
def find_mounts(self):
"""Finds all mountpoints that are mounted to a directory matching :attr:`re_pattern` or originate from a
directory matching :attr:`orig_re_pattern`.
"""
for mountpoint, (orig, fs, opts) in self.mountpoints.items():
if 'bind' not in opts and (re.match(s... | [
"def",
"find_mounts",
"(",
"self",
")",
":",
"for",
"mountpoint",
",",
"(",
"orig",
",",
"fs",
",",
"opts",
")",
"in",
"self",
".",
"mountpoints",
".",
"items",
"(",
")",
":",
"if",
"'bind'",
"not",
"in",
"opts",
"and",
"(",
"re",
".",
"match",
"... | 52.666667 | 22.555556 |
def setup_logging(format="%(asctime)s - %(levelname)s - %(message)s", level='INFO'):
"""Setup the logging framework with a basic configuration"""
try:
import coloredlogs
coloredlogs.install(fmt=format, level=level)
except ImportError:
logging.basicConfig(format=format, level=level) | [
"def",
"setup_logging",
"(",
"format",
"=",
"\"%(asctime)s - %(levelname)s - %(message)s\"",
",",
"level",
"=",
"'INFO'",
")",
":",
"try",
":",
"import",
"coloredlogs",
"coloredlogs",
".",
"install",
"(",
"fmt",
"=",
"format",
",",
"level",
"=",
"level",
")",
... | 44.571429 | 19.142857 |
def load(self, filename):
"""
Load AEAD from a file.
@param filename: File to read AEAD from
@type filename: string
"""
aead_f = open(filename, "rb")
buf = aead_f.read(1024)
if buf.startswith(YHSM_AEAD_CRLF_File_Marker):
buf = YHSM_AEAD_File_M... | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"aead_f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"buf",
"=",
"aead_f",
".",
"read",
"(",
"1024",
")",
"if",
"buf",
".",
"startswith",
"(",
"YHSM_AEAD_CRLF_File_Marker",
")",
":",
"buf",
... | 44.434783 | 20.956522 |
def auth_password(self, username, password, event=None, fallback=True):
"""
Authenticate to the server using a password. The username and password
are sent over an encrypted link.
If an ``event`` is passed in, this method will return immediately, and
the event will be triggered... | [
"def",
"auth_password",
"(",
"self",
",",
"username",
",",
"password",
",",
"event",
"=",
"None",
",",
"fallback",
"=",
"True",
")",
":",
"if",
"(",
"not",
"self",
".",
"active",
")",
"or",
"(",
"not",
"self",
".",
"initial_kex_done",
")",
":",
"# we... | 49.095238 | 24.952381 |
def cleanup(self, sched, coro):
"""Remove this coro from the waiting for signal queue."""
try:
sched.sigwait[self.name].remove((self, coro))
except ValueError:
pass
return True | [
"def",
"cleanup",
"(",
"self",
",",
"sched",
",",
"coro",
")",
":",
"try",
":",
"sched",
".",
"sigwait",
"[",
"self",
".",
"name",
"]",
".",
"remove",
"(",
"(",
"self",
",",
"coro",
")",
")",
"except",
"ValueError",
":",
"pass",
"return",
"True"
] | 33.142857 | 15.714286 |
def get_washing_regex():
"""Return a washing regex list."""
global _washing_regex
if len(_washing_regex):
return _washing_regex
washing_regex = [
# Replace non and anti with non- and anti-. This allows a better
# detection of keywords such as nonabelian.
(re.compile(r"(\... | [
"def",
"get_washing_regex",
"(",
")",
":",
"global",
"_washing_regex",
"if",
"len",
"(",
"_washing_regex",
")",
":",
"return",
"_washing_regex",
"washing_regex",
"=",
"[",
"# Replace non and anti with non- and anti-. This allows a better",
"# detection of keywords such as nonab... | 37.30303 | 19.666667 |
def _view(self, ddoc, view,
use_devmode=False,
params=None,
unrecognized_ok=False,
passthrough=False):
"""Internal method to Execute a view (MapReduce) query
:param string ddoc: Name of the design document
:param string view: Name of the v... | [
"def",
"_view",
"(",
"self",
",",
"ddoc",
",",
"view",
",",
"use_devmode",
"=",
"False",
",",
"params",
"=",
"None",
",",
"unrecognized_ok",
"=",
"False",
",",
"passthrough",
"=",
"False",
")",
":",
"if",
"params",
":",
"if",
"not",
"isinstance",
"(",
... | 35.967742 | 16.258065 |
def present(name, profile="github", **kwargs):
'''
Ensure a user is present
.. code-block:: yaml
ensure user test is present in github:
github.present:
- name: 'gitexample'
The following parameters are required:
name
This is the github handle of the us... | [
"def",
"present",
"(",
"name",
",",
"profile",
"=",
"\"github\"",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"target",
... | 29.833333 | 24.537037 |
def random_array(shape, mean=128., std=20.):
"""Creates a uniformly distributed random array with the given `mean` and `std`.
Args:
shape: The desired shape
mean: The desired mean (Default value = 128)
std: The desired std (Default value = 20)
Returns: Random numpy array of given `... | [
"def",
"random_array",
"(",
"shape",
",",
"mean",
"=",
"128.",
",",
"std",
"=",
"20.",
")",
":",
"x",
"=",
"np",
".",
"random",
".",
"random",
"(",
"shape",
")",
"# normalize around mean=0, std=1",
"x",
"=",
"(",
"x",
"-",
"np",
".",
"mean",
"(",
"... | 35.9375 | 17.25 |
def longest_common_substring(s1, s2):
"""
References:
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2
"""
m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(s1)):
for y in ran... | [
"def",
"longest_common_substring",
"(",
"s1",
",",
"s2",
")",
":",
"m",
"=",
"[",
"[",
"0",
"]",
"*",
"(",
"1",
"+",
"len",
"(",
"s2",
")",
")",
"for",
"i",
"in",
"range",
"(",
"1",
"+",
"len",
"(",
"s1",
")",
")",
"]",
"longest",
",",
"x_l... | 35.882353 | 11.058824 |
def rename(self, old_label_name, new_label_name):
"""
Take into account that a label has been renamed
"""
assert(old_label_name != new_label_name)
self._bayes.pop(old_label_name)
old_baye_dir = self._get_baye_dir(old_label_name)
new_baye_dir = self._get_baye_dir(n... | [
"def",
"rename",
"(",
"self",
",",
"old_label_name",
",",
"new_label_name",
")",
":",
"assert",
"(",
"old_label_name",
"!=",
"new_label_name",
")",
"self",
".",
"_bayes",
".",
"pop",
"(",
"old_label_name",
")",
"old_baye_dir",
"=",
"self",
".",
"_get_baye_dir"... | 43.75 | 13.75 |
def _get_core_transform(self, resolution):
"""The projection for the stereonet as a matplotlib transform. This is
primarily called by LambertAxes._set_lim_and_transforms."""
return self._base_transform(self._center_longitude,
self._center_latitude,
... | [
"def",
"_get_core_transform",
"(",
"self",
",",
"resolution",
")",
":",
"return",
"self",
".",
"_base_transform",
"(",
"self",
".",
"_center_longitude",
",",
"self",
".",
"_center_latitude",
",",
"resolution",
")"
] | 58.5 | 7.666667 |
def compute_dominance_frontier(graph, domtree):
"""
Compute a dominance frontier based on the given post-dominator tree.
This implementation is based on figure 2 of paper An Efficient Method of Computing Static Single Assignment
Form by Ron Cytron, etc.
:param graph: The graph where we want to c... | [
"def",
"compute_dominance_frontier",
"(",
"graph",
",",
"domtree",
")",
":",
"df",
"=",
"{",
"}",
"# Perform a post-order search on the dominator tree",
"for",
"x",
"in",
"networkx",
".",
"dfs_postorder_nodes",
"(",
"domtree",
")",
":",
"if",
"x",
"not",
"in",
"... | 26.785714 | 22.02381 |
def add_seqs_to_alignment(seqs, aln, params=None):
"""Returns an Alignment object from seqs and existing Alignment.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
aln: a cogent.core.alignment.Alignment object, or data that can be used
to build one
... | [
"def",
"add_seqs_to_alignment",
"(",
"seqs",
",",
"aln",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"#create SequenceCollection object from seqs",
"seqs_collection",
"=",
"SequenceCollection",
"(",
"seqs",
")",
"#C... | 33.314286 | 17.757143 |
def once(self):
"""
Returns a function that will be executed at most one time,
no matter how often you call it. Useful for lazy initialization.
"""
ns = self.Namespace()
ns.memo = None
ns.run = False
def work_once(*args, **kwargs):
if ns.run i... | [
"def",
"once",
"(",
"self",
")",
":",
"ns",
"=",
"self",
".",
"Namespace",
"(",
")",
"ns",
".",
"memo",
"=",
"None",
"ns",
".",
"run",
"=",
"False",
"def",
"work_once",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ns",
".",
"ru... | 28.5 | 16.5 |
def delete_external_nodes(sender, **kwargs):
""" sync by deleting nodes from external layers when needed """
node = kwargs['instance']
if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None:
return False
if hasattr(node, 'exte... | [
"def",
"delete_external_nodes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"kwargs",
"[",
"'instance'",
"]",
"if",
"node",
".",
"layer",
".",
"is_external",
"is",
"False",
"or",
"not",
"hasattr",
"(",
"node",
".",
"layer",
",",
"'ex... | 40.384615 | 21.692308 |
def ensure_self(func):
"""
Decorator that can be used to ensure 'self' is the first argument on a task method.
This only needs to be used with task methods that are used as a callback to
a chord or in link_error and is really just a hack to get around https://github.com/celery/celery/issues/2137
U... | [
"def",
"ensure_self",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
"=",
"kwargs",
".",
"pop",
"(",
"'this'",
")",
"if",
"len",
"(",
"args",
")",
... | 27.843137 | 24.705882 |
def _zfs_image_create(vm_name,
pool,
disk_name,
hostname_property_name,
sparse_volume,
disk_size,
disk_image_name):
'''
Clones an existing image, or creates a new one.
When cl... | [
"def",
"_zfs_image_create",
"(",
"vm_name",
",",
"pool",
",",
"disk_name",
",",
"hostname_property_name",
",",
"sparse_volume",
",",
"disk_size",
",",
"disk_image_name",
")",
":",
"if",
"not",
"disk_image_name",
"and",
"not",
"disk_size",
":",
"raise",
"CommandExe... | 35.820896 | 17.701493 |
def canonical_name(sgf_name):
"""Keep filename and some date folders"""
sgf_name = os.path.normpath(sgf_name)
assert sgf_name.endswith('.sgf'), sgf_name
# Strip off '.sgf'
sgf_name = sgf_name[:-4]
# Often eval is inside a folder with the run name.
# include from folder before /eval/ if part... | [
"def",
"canonical_name",
"(",
"sgf_name",
")",
":",
"sgf_name",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"sgf_name",
")",
"assert",
"sgf_name",
".",
"endswith",
"(",
"'.sgf'",
")",
",",
"sgf_name",
"# Strip off '.sgf'",
"sgf_name",
"=",
"sgf_name",
"[",... | 33 | 14.666667 |
def get_history(self):
"""Returns the history from cache or DB or a newly created one."""
if hasattr(self, '_history'):
return self._history
try:
self._history = APICallDayHistory.objects.get(
user=self.user, creation_date=now().date())
except APIC... | [
"def",
"get_history",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_history'",
")",
":",
"return",
"self",
".",
"_history",
"try",
":",
"self",
".",
"_history",
"=",
"APICallDayHistory",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"sel... | 43.181818 | 12.636364 |
def entries_view(self, request, form_id):
"""
Displays the form entries in a HTML table with option to
export as CSV file.
"""
if request.POST.get("back"):
change_url = admin_url(Form, "change", form_id)
return HttpResponseRedirect(change_url)
form... | [
"def",
"entries_view",
"(",
"self",
",",
"request",
",",
"form_id",
")",
":",
"if",
"request",
".",
"POST",
".",
"get",
"(",
"\"back\"",
")",
":",
"change_url",
"=",
"admin_url",
"(",
"Form",
",",
"\"change\"",
",",
"form_id",
")",
"return",
"HttpRespons... | 49.981132 | 15.301887 |
def _create_regex_pattern_add_optional_spaces_to_word_characters(word):
r"""Add the regex special characters (\s*) to allow optional spaces.
:param word: (string) the word to be inserted into a regex pattern.
:return: (string) the regex pattern for that word with optional spaces
betwe... | [
"def",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"word",
")",
":",
"new_word",
"=",
"u\"\"",
"for",
"ch",
"in",
"word",
":",
"if",
"ch",
".",
"isspace",
"(",
")",
":",
"new_word",
"+=",
"ch",
"else",
":",
"new_word",
"+=",
"ch",
"+... | 35.785714 | 19.571429 |
def genes_to_json(store, query):
"""Fetch matching genes and convert to JSON."""
gene_query = store.hgnc_genes(query, search=True)
json_terms = [{'name': "{} | {} ({})".format(gene['hgnc_id'], gene['hgnc_symbol'],
', '.join(gene['aliases'])),
... | [
"def",
"genes_to_json",
"(",
"store",
",",
"query",
")",
":",
"gene_query",
"=",
"store",
".",
"hgnc_genes",
"(",
"query",
",",
"search",
"=",
"True",
")",
"json_terms",
"=",
"[",
"{",
"'name'",
":",
"\"{} | {} ({})\"",
".",
"format",
"(",
"gene",
"[",
... | 55 | 21.142857 |
def check(self, orb):
"""Method that check whether or not the listener is triggered
Args:
orb (Orbit):
Return:
bool: True if there is a zero-crossing for the parameter watched by the listener
"""
return self.prev is not None and np.sign(self(orb)) != np... | [
"def",
"check",
"(",
"self",
",",
"orb",
")",
":",
"return",
"self",
".",
"prev",
"is",
"not",
"None",
"and",
"np",
".",
"sign",
"(",
"self",
"(",
"orb",
")",
")",
"!=",
"np",
".",
"sign",
"(",
"self",
"(",
"self",
".",
"prev",
")",
")"
] | 30.181818 | 27.818182 |
def _init_hdrgo_sortby(self, hdrgo_sortby, sortby):
"""Initialize header sort function."""
if hdrgo_sortby is not None:
return hdrgo_sortby
if sortby is not None:
return sortby
return self.sortby | [
"def",
"_init_hdrgo_sortby",
"(",
"self",
",",
"hdrgo_sortby",
",",
"sortby",
")",
":",
"if",
"hdrgo_sortby",
"is",
"not",
"None",
":",
"return",
"hdrgo_sortby",
"if",
"sortby",
"is",
"not",
"None",
":",
"return",
"sortby",
"return",
"self",
".",
"sortby"
] | 35 | 9 |
def _connect(cls):
"""
Connect signal to current model
"""
post_save.connect(
notify_items, sender=cls,
dispatch_uid='knocker_{0}'.format(cls.__name__)
) | [
"def",
"_connect",
"(",
"cls",
")",
":",
"post_save",
".",
"connect",
"(",
"notify_items",
",",
"sender",
"=",
"cls",
",",
"dispatch_uid",
"=",
"'knocker_{0}'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
")"
] | 26.25 | 11.25 |
def _remove_bound_conditions(agent, keep_criterion):
"""Removes bound conditions of agent such that keep_criterion is False.
Parameters
----------
agent: Agent
The agent whose bound conditions we evaluate
keep_criterion: function
Evaluates removal_criterion(a) for each agent a in a ... | [
"def",
"_remove_bound_conditions",
"(",
"agent",
",",
"keep_criterion",
")",
":",
"new_bc",
"=",
"[",
"]",
"for",
"ind",
"in",
"range",
"(",
"len",
"(",
"agent",
".",
"bound_conditions",
")",
")",
":",
"if",
"keep_criterion",
"(",
"agent",
".",
"bound_cond... | 39.125 | 18.75 |
def get_by(self, field, value):
"""
Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to
filter the list of resources returned.
The search is case-insensitive.
Args:
field: Field name to filter.
value:... | [
"def",
"get_by",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"firmwares",
"=",
"self",
".",
"get_all",
"(",
")",
"matches",
"=",
"[",
"]",
"for",
"item",
"in",
"firmwares",
":",
"if",
"item",
".",
"get",
"(",
"field",
")",
"==",
"value",
"... | 29.55 | 16.85 |
def exists(self, index, doc_type, id, **query_params):
"""
Return if a document exists
"""
path = make_path(index, doc_type, id)
return self._send_request('HEAD', path, params=query_params) | [
"def",
"exists",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"*",
"*",
"query_params",
")",
":",
"path",
"=",
"make_path",
"(",
"index",
",",
"doc_type",
",",
"id",
")",
"return",
"self",
".",
"_send_request",
"(",
"'HEAD'",
",",
"pat... | 37.333333 | 8.666667 |
def from_molecule(cls, mol, theory, charge=None, spin_multiplicity=None,
basis_set="6-31g", basis_set_option="cartesian",
title=None, operation="optimize", theory_directives=None,
alternate_directives=None):
"""
Very flexible arguments to... | [
"def",
"from_molecule",
"(",
"cls",
",",
"mol",
",",
"theory",
",",
"charge",
"=",
"None",
",",
"spin_multiplicity",
"=",
"None",
",",
"basis_set",
"=",
"\"6-31g\"",
",",
"basis_set_option",
"=",
"\"cartesian\"",
",",
"title",
"=",
"None",
",",
"operation",
... | 52.096774 | 23.290323 |
def get_registry(self, registry):
'''**Description**
Find the registry and return its json description
**Arguments**
- registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
**Success Return Value**
A JSON object representing the registry.
... | [
"def",
"get_registry",
"(",
"self",
",",
"registry",
")",
":",
"if",
"self",
".",
"_registry_string_is_valid",
"(",
"registry",
")",
":",
"return",
"[",
"False",
",",
"\"input registry name cannot contain '/' characters - valid registry names are of the form <host>:<port> whe... | 41.578947 | 27.263158 |
def get_graph_by_name_version(self, name: str, version: str) -> Optional[BELGraph]:
"""Load the BEL graph with the given name, or allows for specification of version."""
network = self.get_network_by_name_version(name, version)
if network is None:
return
return network.as_b... | [
"def",
"get_graph_by_name_version",
"(",
"self",
",",
"name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"Optional",
"[",
"BELGraph",
"]",
":",
"network",
"=",
"self",
".",
"get_network_by_name_version",
"(",
"name",
",",
"version",
")",
"if",
"net... | 39.625 | 24 |
def store(self, name, data, version, size=0,
compressed=False, digest=None, logical_size=None):
"""Adds a new file to the storage.
If the file with the same name existed before, it's not
guaranteed that the link for the old version will exist until
the operation co... | [
"def",
"store",
"(",
"self",
",",
"name",
",",
"data",
",",
"version",
",",
"size",
"=",
"0",
",",
"compressed",
"=",
"False",
",",
"digest",
"=",
"None",
",",
"logical_size",
"=",
"None",
")",
":",
"with",
"_exclusive_lock",
"(",
"self",
".",
"_lock... | 49.243478 | 22.556522 |
def secretly(reactor, action, system=None, username=None,
prompt="Password:"):
"""
Call the given C{action} with a secret value.
@return: a L{Deferred} that fires with C{action}'s result, or
L{NoSecretError} if no secret can be retrieved.
"""
if system is None:
system =... | [
"def",
"secretly",
"(",
"reactor",
",",
"action",
",",
"system",
"=",
"None",
",",
"username",
"=",
"None",
",",
"prompt",
"=",
"\"Password:\"",
")",
":",
"if",
"system",
"is",
"None",
":",
"system",
"=",
"action",
".",
"__module__",
"if",
"system",
"=... | 34.925926 | 13 |
def OrEvent(*events):
'''
Parameters
----------
events : list(threading.Event)
List of events.
Returns
-------
threading.Event
Event that is set when **at least one** of the events in :data:`events`
is set.
'''
or_event = threading.Event()
def changed():... | [
"def",
"OrEvent",
"(",
"*",
"events",
")",
":",
"or_event",
"=",
"threading",
".",
"Event",
"(",
")",
"def",
"changed",
"(",
")",
":",
"'''\n Set ``or_event`` if any of the specified events have been set.\n '''",
"bools",
"=",
"[",
"event_i",
".",
"is_... | 25.03125 | 23.53125 |
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.messa... | [
"def",
"get_workspaces",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"message",
"(",
"MessageType",
".",
"GET_WORKSPACES",
",",
"''",
")",
"return",
"json",
".",
"loads",
"(",
"data",
",",
"object_hook",
"=",
"WorkspaceReply",
")"
] | 33.583333 | 21.416667 |
def _delete_forever_values(self, forever_key):
"""
Delete all of the keys that have been stored forever.
:type forever_key: str
"""
forever = self._store.connection().lrange(forever_key, 0, -1)
if len(forever) > 0:
self._store.connection().delete(*forever) | [
"def",
"_delete_forever_values",
"(",
"self",
",",
"forever_key",
")",
":",
"forever",
"=",
"self",
".",
"_store",
".",
"connection",
"(",
")",
".",
"lrange",
"(",
"forever_key",
",",
"0",
",",
"-",
"1",
")",
"if",
"len",
"(",
"forever",
")",
">",
"0... | 30.9 | 17.1 |
def _maybe_restore_empty_groups(self, combined):
"""Our index contained empty groups (e.g., from a resampling). If we
reduced on that dimension, we want to restore the full index.
"""
if (self._full_index is not None and
self._group.name in combined.dims):
ind... | [
"def",
"_maybe_restore_empty_groups",
"(",
"self",
",",
"combined",
")",
":",
"if",
"(",
"self",
".",
"_full_index",
"is",
"not",
"None",
"and",
"self",
".",
"_group",
".",
"name",
"in",
"combined",
".",
"dims",
")",
":",
"indexers",
"=",
"{",
"self",
... | 48 | 11 |
def _reset_on_error(self, server, func, *args, **kwargs):
"""Execute an operation. Reset the server on network error.
Returns fn()'s return value on success. On error, clears the server's
pool and marks the server Unknown.
Re-raises any exception thrown by fn().
"""
try... | [
"def",
"_reset_on_error",
"(",
"self",
",",
"server",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"NetworkTimeout",
":",
"# The socket has bee... | 35.875 | 17.375 |
def display_config(self):
"""Set up status display if option selected. NB: this method
assumes that the first entry is the iteration count and the
last is the rho value.
"""
if self.opt['Verbose']:
hdrtxt = type(self).hdrtxt()
# Call utility function to c... | [
"def",
"display_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Verbose'",
"]",
":",
"hdrtxt",
"=",
"type",
"(",
"self",
")",
".",
"hdrtxt",
"(",
")",
"# Call utility function to construct status display formatting",
"self",
".",
"hdrstr",
","... | 43.538462 | 19.153846 |
def visit_list(self, node, *args, **kwargs):
"""As transformers may return lists in some places this method
can be used to enforce a list as return value.
"""
rv = self.visit(node, *args, **kwargs)
if not isinstance(rv, list):
rv = [rv]
return rv | [
"def",
"visit_list",
"(",
"self",
",",
"node",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rv",
"=",
"self",
".",
"visit",
"(",
"node",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"isinstance",
"(",
"rv",
",",
"list",... | 37.375 | 8.75 |
def boolean(value):
'''
Convert the content of a string (or a number) to a boolean.
Do nothing when input value is already a boolean.
This filter accepts usual values for ``True`` and ``False``:
"0", "f", "false", "n", etc.
'''
if value is None or isinstance(value, bool):
return val... | [
"def",
"boolean",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"try",
":",
"return",
"bool",
"(",
"int",
"(",
"value",
")",
")",
"except",
"ValueError",
":",
"lower_v... | 31.681818 | 20.5 |
def exponentiate_commuting_pauli_sum(pauli_sum):
"""
Returns a function that maps all substituent PauliTerms and sums them into a program. NOTE: Use
this function with care. Substituent PauliTerms should commute.
:param PauliSum pauli_sum: PauliSum to exponentiate.
:returns: A function that paramet... | [
"def",
"exponentiate_commuting_pauli_sum",
"(",
"pauli_sum",
")",
":",
"if",
"not",
"isinstance",
"(",
"pauli_sum",
",",
"PauliSum",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument 'pauli_sum' must be a PauliSum.\"",
")",
"fns",
"=",
"[",
"exponential_map",
"(",
"t... | 35.333333 | 21.111111 |
def _read_subtitles(self, lines):
"""
Read text fragments from a subtitles format text file.
:param list lines: the lines of the subtitles text file
:raises: ValueError: if the id regex is not valid
"""
self.log(u"Parsing fragments from subtitles text format")
id... | [
"def",
"_read_subtitles",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from subtitles text format\"",
")",
"id_format",
"=",
"self",
".",
"_get_id_format",
"(",
")",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"f... | 38 | 13.185185 |
def output_reduce(input_file, path=True, pdb_name=None, force=False):
"""Runs Reduce on a pdb or mmol file and creates a new file with the output.
Parameters
----------
input_file : str or pathlib.Path
Path to file to run Reduce on.
path : bool
True if input_file is a path.
pdb_n... | [
"def",
"output_reduce",
"(",
"input_file",
",",
"path",
"=",
"True",
",",
"pdb_name",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"path",
":",
"output_path",
"=",
"reduce_output_path",
"(",
"path",
"=",
"input_file",
")",
"else",
":",
"outpu... | 31.354839 | 18.16129 |
def get_unresolved_properties_by_inheritance(self, timeperiod):
"""
Fill full properties with template if needed for the
unresolved values (example: sunday ETCETC)
:return: None
"""
# Ok, I do not have prop, Maybe my templates do?
# Same story for plus
for... | [
"def",
"get_unresolved_properties_by_inheritance",
"(",
"self",
",",
"timeperiod",
")",
":",
"# Ok, I do not have prop, Maybe my templates do?",
"# Same story for plus",
"for",
"i",
"in",
"timeperiod",
".",
"templates",
":",
"template",
"=",
"self",
".",
"templates",
"[",... | 40 | 11.090909 |
def _set_auto_fields(self, model_obj):
"""Set the values of the auto field using counter"""
for field_name, field_obj in \
self.entity_cls.meta_.auto_fields:
counter_key = f'{self.schema_name}_{field_name}'
if not (field_name in model_obj and model_obj[field_name]... | [
"def",
"_set_auto_fields",
"(",
"self",
",",
"model_obj",
")",
":",
"for",
"field_name",
",",
"field_obj",
"in",
"self",
".",
"entity_cls",
".",
"meta_",
".",
"auto_fields",
":",
"counter_key",
"=",
"f'{self.schema_name}_{field_name}'",
"if",
"not",
"(",
"field_... | 48.692308 | 17.769231 |
def remove_existing_pidfile(pidfile_path):
""" Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
"""
try:
os.remove(pidfile_path)
except OSError... | [
"def",
"remove_existing_pidfile",
"(",
"pidfile_path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"pidfile_path",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"pass",
"else",
":",
"raise"
... | 26.733333 | 19.933333 |
def open_as_needed(filename):
"""Return a file-object given either a filename or an object.
Handles opening with the right class based on the file extension.
"""
if hasattr(filename, 'read'):
return filename
if filename.endswith('.bz2'):
return bz2.BZ2File(filename, 'rb')
elif... | [
"def",
"open_as_needed",
"(",
"filename",
")",
":",
"if",
"hasattr",
"(",
"filename",
",",
"'read'",
")",
":",
"return",
"filename",
"if",
"filename",
".",
"endswith",
"(",
"'.bz2'",
")",
":",
"return",
"bz2",
".",
"BZ2File",
"(",
"filename",
",",
"'rb'"... | 28.2 | 15.933333 |
def format_labels(labels):
""" Convert a dictionary of labels into a comma separated string """
if labels:
return ','.join(['{}={}'.format(k, v) for k, v in labels.items()])
else:
return '' | [
"def",
"format_labels",
"(",
"labels",
")",
":",
"if",
"labels",
":",
"return",
"','",
".",
"join",
"(",
"[",
"'{}={}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"labels",
".",
"items",
"(",
")",
"]",
")",
"else",
":"... | 35.333333 | 21.333333 |
def keep_alive(self, val: bool) -> None:
"""Set keep-alive connection mode.
:param bool val: new state.
"""
self._keepalive = val
if self._keepalive_handle:
self._keepalive_handle.cancel()
self._keepalive_handle = None | [
"def",
"keep_alive",
"(",
"self",
",",
"val",
":",
"bool",
")",
"->",
"None",
":",
"self",
".",
"_keepalive",
"=",
"val",
"if",
"self",
".",
"_keepalive_handle",
":",
"self",
".",
"_keepalive_handle",
".",
"cancel",
"(",
")",
"self",
".",
"_keepalive_han... | 30.555556 | 7.333333 |
def pypirc_temp(index_url):
""" Create a temporary pypirc file for interaction with twine """
pypirc_file = tempfile.NamedTemporaryFile(suffix='.pypirc', delete=False)
print(pypirc_file.name)
with open(pypirc_file.name, 'w') as fh:
fh.write(PYPIRC_TEMPLATE.format(index_name=PYPIRC_TEMP_INDEX_NAM... | [
"def",
"pypirc_temp",
"(",
"index_url",
")",
":",
"pypirc_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.pypirc'",
",",
"delete",
"=",
"False",
")",
"print",
"(",
"pypirc_file",
".",
"name",
")",
"with",
"open",
"(",
"pypirc_file",... | 52.285714 | 19.285714 |
def _log_graphql_error(self, query, data):
'''Log a ``{"errors": [...]}`` GraphQL return and return itself.
:param query: the GraphQL query that triggered the result.
:type query: str
:param data: the decoded JSON object.
:type data: dict
:return: the input ``data``
... | [
"def",
"_log_graphql_error",
"(",
"self",
",",
"query",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"bytes",
")",
":",
"# pragma: no cover",
"query",
"=",
"query",
".",
"decode",
"(",
"'utf-8'",
")",
"elif",
"not",
"isinstance",
"(",
"q... | 37.871795 | 18.897436 |
def plot(self, df_data, center=False, save=False,
save_name=None, save_path='saved', dated=True, notebook=True):
"df_data format is a dataframe with columns x, y, z (required), and style, filter (optional)"
data = df_data.to_json(orient='records')
options = self.to_dict()
re... | [
"def",
"plot",
"(",
"self",
",",
"df_data",
",",
"center",
"=",
"False",
",",
"save",
"=",
"False",
",",
"save_name",
"=",
"None",
",",
"save_path",
"=",
"'saved'",
",",
"dated",
"=",
"True",
",",
"notebook",
"=",
"True",
")",
":",
"data",
"=",
"df... | 65.428571 | 27.714286 |
def get_activity_query_session(self):
"""Gets the ``OsidSession`` associated with the activity query service.
return: (osid.learning.ActivityQuerySession) - a
``ActivityQuerySession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports... | [
"def",
"get_activity_query_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_activity_query",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"ActivityQuerySession",
"(",
... | 42.375 | 14.625 |
def format_units(self, value, unit="B", optimal=5, auto=True, si=False):
"""
Takes a value and formats it for user output, we can choose the unit to
use eg B, MiB, kbits/second. This is mainly for use with bytes/bits it
converts the value into a human readable form. It has various
... | [
"def",
"format_units",
"(",
"self",
",",
"value",
",",
"unit",
"=",
"\"B\"",
",",
"optimal",
"=",
"5",
",",
"auto",
"=",
"True",
",",
"si",
"=",
"False",
")",
":",
"UNITS",
"=",
"\"KMGTPEZY\"",
"DECIMAL_SIZE",
"=",
"1000",
"BINARY_SIZE",
"=",
"1024",
... | 36.764045 | 19.775281 |
def _transform_col(self, x, i):
"""Encode one categorical column into average target values.
Args:
x (pandas.Series): a categorical column to encode
i (int): column index
Returns:
x (pandas.Series): a column with labels.
"""
return x.fillna(NAN... | [
"def",
"_transform_col",
"(",
"self",
",",
"x",
",",
"i",
")",
":",
"return",
"x",
".",
"fillna",
"(",
"NAN_INT",
")",
".",
"map",
"(",
"self",
".",
"target_encoders",
"[",
"i",
"]",
")",
".",
"fillna",
"(",
"self",
".",
"target_mean",
")"
] | 41.222222 | 16.222222 |
def reset(self):
'''
Reset the state of the market (attributes in sow_vars, etc) to some
user-defined initial state, and erase the histories of tracked variables.
Parameters
----------
none
Returns
-------
none
'''
for var_name in... | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"var_name",
"in",
"self",
".",
"track_vars",
":",
"# Reset the history of tracked variables",
"setattr",
"(",
"self",
",",
"var_name",
"+",
"'_hist'",
",",
"[",
"]",
")",
"for",
"var_name",
"in",
"self",
".",
"... | 35.25 | 27.55 |
def ParseStatusRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses a contact row from the database.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... | [
"def",
"ParseStatusRow",
"(",
"self",
",",
"parser_mediator",
",",
"query",
",",
"row",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"query_hash",
"=",
"hash",
"(",
"query",
")",
"event_data",
"=",
"TwitterIOSStatusEventData",
"(",
")",
"event_data",
".",
"favo... | 44.230769 | 19.128205 |
def register_plugin(self, name):
"""Load and register a plugin given its package name."""
logger.info("Registering plugin: " + name)
module = importlib.import_module(name)
module.register_plugin(self) | [
"def",
"register_plugin",
"(",
"self",
",",
"name",
")",
":",
"logger",
".",
"info",
"(",
"\"Registering plugin: \"",
"+",
"name",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"module",
".",
"register_plugin",
"(",
"self",
")"
] | 45.6 | 5.6 |
def extract(data, items, out_dir=None):
"""Extract germline calls for the given sample, if tumor only.
"""
if vcfutils.get_paired_phenotype(data):
if len(items) == 1:
germline_vcf = _remove_prioritization(data["vrn_file"], data, out_dir)
germline_vcf = vcfutils.bgzip_and_inde... | [
"def",
"extract",
"(",
"data",
",",
"items",
",",
"out_dir",
"=",
"None",
")",
":",
"if",
"vcfutils",
".",
"get_paired_phenotype",
"(",
"data",
")",
":",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"germline_vcf",
"=",
"_remove_prioritization",
"(",
... | 46.888889 | 16.333333 |
def list_configured_members(lbn, profile='default'):
'''
Return a list of member workers from the configuration files
CLI Examples:
.. code-block:: bash
salt '*' modjk.list_configured_members loadbalancer1
salt '*' modjk.list_configured_members loadbalancer1 other-profile
'''
... | [
"def",
"list_configured_members",
"(",
"lbn",
",",
"profile",
"=",
"'default'",
")",
":",
"config",
"=",
"dump_config",
"(",
"profile",
")",
"try",
":",
"ret",
"=",
"config",
"[",
"'worker.{0}.balance_workers'",
".",
"format",
"(",
"lbn",
")",
"]",
"except",... | 24.95 | 27.65 |
def deny_assignments(self):
"""Instance depends on the API version:
* 2018-07-01-preview: :class:`DenyAssignmentsOperations<azure.mgmt.authorization.v2018_07_01_preview.operations.DenyAssignmentsOperations>`
"""
api_version = self._get_api_version('deny_assignments')
if api_v... | [
"def",
"deny_assignments",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'deny_assignments'",
")",
"if",
"api_version",
"==",
"'2018-07-01-preview'",
":",
"from",
".",
"v2018_07_01_preview",
".",
"operations",
"import",
"DenyAssig... | 63.090909 | 39.636364 |
def refresh_content(self, order=None, name=None):
"""
Re-download all submissions and reset the page index
"""
order = order or self.content.order
# Preserve the query if staying on the current page
if name is None:
query = self.content.query
else:
... | [
"def",
"refresh_content",
"(",
"self",
",",
"order",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"order",
"=",
"order",
"or",
"self",
".",
"content",
".",
"order",
"# Preserve the query if staying on the current page",
"if",
"name",
"is",
"None",
":",
"... | 33.958333 | 17.208333 |
def _get_template(self, root=None, **metadata_defaults):
""" Iterate over items metadata_defaults {prop: val, ...} to populate template """
if root is None:
if self._data_map is None:
self._init_data_map()
root = self._xml_root = self._data_map['_root']
... | [
"def",
"_get_template",
"(",
"self",
",",
"root",
"=",
"None",
",",
"*",
"*",
"metadata_defaults",
")",
":",
"if",
"root",
"is",
"None",
":",
"if",
"self",
".",
"_data_map",
"is",
"None",
":",
"self",
".",
"_init_data_map",
"(",
")",
"root",
"=",
"se... | 35.111111 | 19.555556 |
def grammatical_join(l, initial_joins=", ", final_join=" and "):
"""
Display a list of items nicely, with a different string before the final
item. Useful for using lists in sentences.
>>> grammatical_join(['apples', 'pears', 'bananas'])
'apples, pears and bananas'
>>> grammatical_join(['apple... | [
"def",
"grammatical_join",
"(",
"l",
",",
"initial_joins",
"=",
"\", \"",
",",
"final_join",
"=",
"\" and \"",
")",
":",
"# http://stackoverflow.com/questions/19838976/grammatical-list-join-in-python",
"return",
"initial_joins",
".",
"join",
"(",
"l",
"[",
":",
"-",
"... | 44.611111 | 23.944444 |
def call(self, scope, args=[]):
"""Call mixin. Parses a copy of the mixins body
in the current scope and returns it.
args:
scope (Scope): current scope
args (list): arguments
raises:
SyntaxError
returns:
list or False
"""
... | [
"def",
"call",
"(",
"self",
",",
"scope",
",",
"args",
"=",
"[",
"]",
")",
":",
"ret",
"=",
"False",
"if",
"args",
":",
"args",
"=",
"[",
"[",
"a",
".",
"parse",
"(",
"scope",
")",
"if",
"isinstance",
"(",
"a",
",",
"Expression",
")",
"else",
... | 29.814815 | 14.259259 |
def get_order_line_item_by_id(cls, order_line_item_id, **kwargs):
"""Find OrderLineItem
Return single instance of OrderLineItem by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_o... | [
"def",
"get_order_line_item_by_id",
"(",
"cls",
",",
"order_line_item_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_order... | 45.142857 | 22.761905 |
def conversations(self, getsrcdst=None, **kargs):
"""Graphes a conversations between sources and destinations and display it
(using graphviz and imagemagick)
getsrcdst: a function that takes an element of the list and
returns the source, the destination and optionally
... | [
"def",
"conversations",
"(",
"self",
",",
"getsrcdst",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"getsrcdst",
"is",
"None",
":",
"def",
"getsrcdst",
"(",
"pkt",
")",
":",
"\"\"\"Extract src and dst addresses\"\"\"",
"if",
"'IP'",
"in",
"pkt",
":... | 46.488372 | 16.744186 |
def uavionix_adsb_out_dynamic_send(self, utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk, force_mavlink1=False):
'''
Dynamic data used to generate ADS-B out transponder data (send ... | [
"def",
"uavionix_adsb_out_dynamic_send",
"(",
"self",
",",
"utcTime",
",",
"gpsLat",
",",
"gpsLon",
",",
"gpsAlt",
",",
"gpsFix",
",",
"numSats",
",",
"baroAltMSL",
",",
"accuracyHor",
",",
"accuracyVert",
",",
"accuracyVel",
",",
"velVert",
",",
"velNS",
",",... | 108.869565 | 79.478261 |
def _output_digraph(self, target):
"""Graphviz format depmap output handler."""
color_by_type = {}
def maybe_add_type(dep, dep_id):
"""Add a class type to a dependency id if --show-types is passed."""
return dep_id if not self.show_types else '\\n'.join((dep_id, dep.__class__.__name__))
de... | [
"def",
"_output_digraph",
"(",
"self",
",",
"target",
")",
":",
"color_by_type",
"=",
"{",
"}",
"def",
"maybe_add_type",
"(",
"dep",
",",
"dep_id",
")",
":",
"\"\"\"Add a class type to a dependency id if --show-types is passed.\"\"\"",
"return",
"dep_id",
"if",
"not",... | 38.755556 | 23.111111 |
def main(cls):
"""Main entry point of Laniakea.
"""
args = cls.parse_args()
if args.focus:
Focus.init()
else:
Focus.disable()
logging.basicConfig(format='[Laniakea] %(asctime)s %(levelname)s: %(message)s',
level=args.v... | [
"def",
"main",
"(",
"cls",
")",
":",
"args",
"=",
"cls",
".",
"parse_args",
"(",
")",
"if",
"args",
".",
"focus",
":",
"Focus",
".",
"init",
"(",
")",
"else",
":",
"Focus",
".",
"disable",
"(",
")",
"logging",
".",
"basicConfig",
"(",
"format",
"... | 34.392157 | 25.078431 |
def get_style(self, name, workspace=None):
'''
returns a single style object.
Will return None if no style is found.
Will raise an error if more than one style with the same name is found.
'''
styles = self.get_styles(names=name, workspaces=workspace)
retur... | [
"def",
"get_style",
"(",
"self",
",",
"name",
",",
"workspace",
"=",
"None",
")",
":",
"styles",
"=",
"self",
".",
"get_styles",
"(",
"names",
"=",
"name",
",",
"workspaces",
"=",
"workspace",
")",
"return",
"self",
".",
"_return_first_item",
"(",
"style... | 38.333333 | 20.111111 |
def _computeAsymptoticCovarianceMatrix(self, W, N_k, method=None):
"""Compute estimate of the asymptotic covariance matrix.
Parameters
----------
W : np.ndarray, shape=(N, K), dtype='float'
The normalized weight matrix for snapshots and states.
W[n, k] is the wei... | [
"def",
"_computeAsymptoticCovarianceMatrix",
"(",
"self",
",",
"W",
",",
"N_k",
",",
"method",
"=",
"None",
")",
":",
"# Set 'svd-ew' as default if uncertainty method specified as None.",
"if",
"method",
"==",
"None",
":",
"method",
"=",
"'svd-ew'",
"# Get dimensions of... | 42.130841 | 26.719626 |
def _encrypt_password(self, password):
"""encrypt the password for given mode """
if self.encryption_mode.lower() == 'crypt':
return self._crypt_password(password)
elif self.encryption_mode.lower() == 'md5':
return self._md5_password(password)
elif self.encryption... | [
"def",
"_encrypt_password",
"(",
"self",
",",
"password",
")",
":",
"if",
"self",
".",
"encryption_mode",
".",
"lower",
"(",
")",
"==",
"'crypt'",
":",
"return",
"self",
".",
"_crypt_password",
"(",
"password",
")",
"elif",
"self",
".",
"encryption_mode",
... | 46.8 | 11.6 |
def _manage_cmd(cmd, settings=None):
# type: () -> None
""" Run django ./manage.py command manually.
This function eliminates the need for having ``manage.py`` (reduces file
clutter).
"""
import sys
from os import environ
from peltak.core import conf
from peltak.core import context
... | [
"def",
"_manage_cmd",
"(",
"cmd",
",",
"settings",
"=",
"None",
")",
":",
"# type: () -> None",
"import",
"sys",
"from",
"os",
"import",
"environ",
"from",
"peltak",
".",
"core",
"import",
"conf",
"from",
"peltak",
".",
"core",
"import",
"context",
"from",
... | 30.32 | 19.72 |
def _parseline(self, line):
"""
All lines come to this method.
:param line: a to parse
:returns: the number of rows to jump and parse the next data line or
return the code error -1
"""
sline = line.split(SEPARATOR)
segment = sline[0]
handlers = {
... | [
"def",
"_parseline",
"(",
"self",
",",
"line",
")",
":",
"sline",
"=",
"line",
".",
"split",
"(",
"SEPARATOR",
")",
"segment",
"=",
"sline",
"[",
"0",
"]",
"handlers",
"=",
"{",
"SEGMENT_HEADER",
":",
"self",
".",
"_handle_header",
",",
"SEGMENT_EOF",
... | 33.157895 | 12.315789 |
def cyk(grammar, parse_sequence):
# type: (Grammar, Iterable[Any]) -> Nonterminal
"""
Perform CYK algorithm.
:param grammar: Grammar to use in Chomsky Normal Form.
:param parse_sequence: Input sequence to parse.
:return: Instance of root Nonterminal in parsed tree.
"""
# check start symb... | [
"def",
"cyk",
"(",
"grammar",
",",
"parse_sequence",
")",
":",
"# type: (Grammar, Iterable[Any]) -> Nonterminal",
"# check start symbol",
"if",
"grammar",
".",
"start",
"is",
"None",
":",
"raise",
"StartSymbolNotSetException",
"(",
")",
"# create variables",
"parse_sequen... | 44.072464 | 13.521739 |
def p_file_depends(self, f_term, predicate):
"""Sets file dependencies."""
for _, _, other_file in self.graph.triples((f_term, predicate, None)):
name = self.get_file_name(other_file)
if name is not None:
self.builder.add_file_dep(six.text_type(name))
... | [
"def",
"p_file_depends",
"(",
"self",
",",
"f_term",
",",
"predicate",
")",
":",
"for",
"_",
",",
"_",
",",
"other_file",
"in",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"f_term",
",",
"predicate",
",",
"None",
")",
")",
":",
"name",
"=",
"se... | 44.5 | 13.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.