text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def check(self, diff):
"""Check that the new file introduced is a python source file"""
path = diff.b_path
assert any(
path.endswith(ext)
for ext in importlib.machinery.SOURCE_SUFFIXES
) | [
"def",
"check",
"(",
"self",
",",
"diff",
")",
":",
"path",
"=",
"diff",
".",
"b_path",
"assert",
"any",
"(",
"path",
".",
"endswith",
"(",
"ext",
")",
"for",
"ext",
"in",
"importlib",
".",
"machinery",
".",
"SOURCE_SUFFIXES",
")"
] | 33.714286 | 16 |
def difference_update(self, values):
'''Remove an iterable of *values* from the set.'''
d = self.value_pickler.dumps
return self.cache.remove(tuple((d(v) for v in values))) | [
"def",
"difference_update",
"(",
"self",
",",
"values",
")",
":",
"d",
"=",
"self",
".",
"value_pickler",
".",
"dumps",
"return",
"self",
".",
"cache",
".",
"remove",
"(",
"tuple",
"(",
"(",
"d",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
")",... | 49 | 12 |
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):... | [
"def",
"_adjust_log_file_override",
"(",
"overrides",
",",
"default_log_file",
")",
":",
"if",
"overrides",
".",
"get",
"(",
"'log_dir'",
")",
":",
"# Adjust log_file if a log_dir override is introduced",
"if",
"overrides",
".",
"get",
"(",
"'log_file'",
")",
":",
"... | 45.3125 | 18.6875 |
def mount(self, mount_point=None):
"""
mount container filesystem
:return: str, the location of the mounted file system
"""
cmd = ["podman", "mount", self._id or self.get_id()]
output = run_cmd(cmd, return_output=True).rstrip("\n\r")
return output | [
"def",
"mount",
"(",
"self",
",",
"mount_point",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"\"podman\"",
",",
"\"mount\"",
",",
"self",
".",
"_id",
"or",
"self",
".",
"get_id",
"(",
")",
"]",
"output",
"=",
"run_cmd",
"(",
"cmd",
",",
"return_output",
... | 32.888889 | 15.111111 |
def WriteClientSnapshotHistory(self, clients, cursor=None):
"""Writes the full history for a particular client."""
client_id = clients[0].client_id
latest_timestamp = max(client.timestamp for client in clients)
query = ""
params = {
"client_id": db_utils.ClientIDToInt(client_id),
"l... | [
"def",
"WriteClientSnapshotHistory",
"(",
"self",
",",
"clients",
",",
"cursor",
"=",
"None",
")",
":",
"client_id",
"=",
"clients",
"[",
"0",
"]",
".",
"client_id",
"latest_timestamp",
"=",
"max",
"(",
"client",
".",
"timestamp",
"for",
"client",
"in",
"c... | 35.964286 | 18.785714 |
def __get_base_bundle_url(self):
"""Returns ``{rest api url}/{serviceInstanceId}/v2/bundles`` """
return self.__serviceAccount.get_url() + '/' + \
self.__serviceAccount.get_instance_id() + self.__BUNDLES_PATH | [
"def",
"__get_base_bundle_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"__serviceAccount",
".",
"get_url",
"(",
")",
"+",
"'/'",
"+",
"self",
".",
"__serviceAccount",
".",
"get_instance_id",
"(",
")",
"+",
"self",
".",
"__BUNDLES_PATH"
] | 59 | 14.25 |
def _get_programs_dict():
"""
Builds and returns programs dictionary
This will have to import the packages in COLLABORATORS_S in order to get their absolute path.
Returns:
dictionary: {"packagename": [ExeInfo0, ...], ...}
"packagename" examples: "f311.explorer", "numpy"
"""
global... | [
"def",
"_get_programs_dict",
"(",
")",
":",
"global",
"__programs_dict",
"if",
"__programs_dict",
"is",
"not",
"None",
":",
"return",
"__programs_dict",
"d",
"=",
"__programs_dict",
"=",
"OrderedDict",
"(",
")",
"for",
"pkgname",
"in",
"COLLABORATORS_S",
":",
"t... | 30.3 | 24.033333 |
def on_key_up(self):
""" Process key up event by updating buffer and release key. """
if (self.last_pressed is not None):
self.set_key_state(self.last_pressed, 0)
self.buffer = self.last_pressed.update_buffer(self.buffer)
self.text_consumer(self.buffer)
se... | [
"def",
"on_key_up",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"last_pressed",
"is",
"not",
"None",
")",
":",
"self",
".",
"set_key_state",
"(",
"self",
".",
"last_pressed",
",",
"0",
")",
"self",
".",
"buffer",
"=",
"self",
".",
"last_pressed",
... | 48 | 10.285714 |
def process_post(self):
"""
Analyse the POST request:
* check that the LoginTicket is valid
* check that the user sumited credentials are valid
:return:
* :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid
... | [
"def",
"process_post",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"check_lt",
"(",
")",
":",
"self",
".",
"init_form",
"(",
"self",
".",
"request",
".",
"POST",
")",
"logger",
".",
"warning",
"(",
"\"Received an invalid login ticket\"",
")",
"return"... | 49.333333 | 21.897436 |
def create_atom_data(self):
'''The atom site work is split into two parts. This function type-converts the tags.'''
current_atom_site = self.current_atom_site
# Only parse ATOM records
if current_atom_site.IsHETATM:
# Early out - do not parse HETATM records
retu... | [
"def",
"create_atom_data",
"(",
"self",
")",
":",
"current_atom_site",
"=",
"self",
".",
"current_atom_site",
"# Only parse ATOM records",
"if",
"current_atom_site",
".",
"IsHETATM",
":",
"# Early out - do not parse HETATM records",
"return",
"None",
",",
"None",
",",
"... | 39.615385 | 19.769231 |
def patched_fax_init(self, twilio):
"""
Initialize the Fax Domain
:returns: Domain for Fax
:rtype: twilio.rest.fax.Fax
"""
super(TwilioFax, self).__init__(twilio)
self.base_url = ''
self.account_sid = twilio.account_sid
# Versions
self._v1 = None | [
"def",
"patched_fax_init",
"(",
"self",
",",
"twilio",
")",
":",
"super",
"(",
"TwilioFax",
",",
"self",
")",
".",
"__init__",
"(",
"twilio",
")",
"self",
".",
"base_url",
"=",
"''",
"self",
".",
"account_sid",
"=",
"twilio",
".",
"account_sid",
"# Versi... | 19.692308 | 15.076923 |
def get_all_items(self):
"""
Returns all items in the combobox dictionary.
"""
return [self._widget.itemText(k) for k in range(self._widget.count())] | [
"def",
"get_all_items",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_widget",
".",
"itemText",
"(",
"k",
")",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"_widget",
".",
"count",
"(",
")",
")",
"]"
] | 35.4 | 13.4 |
def merge(self, other, inplace=False):
"""
Merge holiday calendars together. The caller's class
rules take precedence. The merge will be done
based on each holiday's name.
Parameters
----------
other : holiday calendar
inplace : bool (default=False)
... | [
"def",
"merge",
"(",
"self",
",",
"other",
",",
"inplace",
"=",
"False",
")",
":",
"holidays",
"=",
"self",
".",
"merge_class",
"(",
"self",
",",
"other",
")",
"if",
"inplace",
":",
"self",
".",
"rules",
"=",
"holidays",
"else",
":",
"return",
"holid... | 31.470588 | 14.529412 |
def parse_args(self):
""" Parse the cli args
Returns:
args (namespace): The args
"""
parser = ArgumentParser(description='',
formatter_class=RawTextHelpFormatter)
parser.add_argument("--generate", action="store", dest='generate... | [
"def",
"parse_args",
"(",
"self",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"''",
",",
"formatter_class",
"=",
"RawTextHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"\"--generate\"",
",",
"action",
"=",
"\"store\"",
",",
"d... | 54.324324 | 20.945946 |
def basic_types(self):
"""Returns non-postgres types referenced in user supplied model """
if not self.foreign_key_definitions:
return self.standard_types
else:
tmp = self.standard_types
tmp.append('ForeignKey')
return tmp | [
"def",
"basic_types",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"foreign_key_definitions",
":",
"return",
"self",
".",
"standard_types",
"else",
":",
"tmp",
"=",
"self",
".",
"standard_types",
"tmp",
".",
"append",
"(",
"'ForeignKey'",
")",
"return",
... | 35.875 | 9.5 |
def split_all(reference, sep):
"""
Splits a given string at a given separator or list of separators.
:param reference: The reference to split.
:param sep: Separator string or list of separator strings.
:return: A list of split strings
"""
parts = partition_all(reference, sep)
return [p ... | [
"def",
"split_all",
"(",
"reference",
",",
"sep",
")",
":",
"parts",
"=",
"partition_all",
"(",
"reference",
",",
"sep",
")",
"return",
"[",
"p",
"for",
"p",
"in",
"parts",
"if",
"p",
"not",
"in",
"sep",
"]"
] | 34.2 | 11.6 |
def ends(self, s):
length = len(s)
""" True iff 0...k ends with string s """
res = (self.b[self.k-length+1:self.k+1] == s)
if res:
self.j = self.k - length
return res | [
"def",
"ends",
"(",
"self",
",",
"s",
")",
":",
"length",
"=",
"len",
"(",
"s",
")",
"res",
"=",
"(",
"self",
".",
"b",
"[",
"self",
".",
"k",
"-",
"length",
"+",
"1",
":",
"self",
".",
"k",
"+",
"1",
"]",
"==",
"s",
")",
"if",
"res",
"... | 30.285714 | 14.714286 |
def save_yaml_file(file, val):
"""
Save data to yaml file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | unicode | list | dict
"""
opened = False
if not hasattr(file, "write")... | [
"def",
"save_yaml_file",
"(",
"file",
",",
"val",
")",
":",
"opened",
"=",
"False",
"if",
"not",
"hasattr",
"(",
"file",
",",
"\"write\"",
")",
":",
"file",
"=",
"io",
".",
"open",
"(",
"file",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
... | 23.6 | 17.3 |
def run_converter(arguments):
"""
Converts notebooks to HTML files. Returns list of output file paths
"""
# Get spec from config file
if os.path.isfile(CONFIG_FILE):
with open(CONFIG_FILE, encoding='utf-8') as f:
config = json.load(f)
arguments['--spec'] = arguments['... | [
"def",
"run_converter",
"(",
"arguments",
")",
":",
"# Get spec from config file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"CONFIG_FILE",
")",
":",
"with",
"open",
"(",
"CONFIG_FILE",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"config",
"="... | 28.222222 | 18.355556 |
def get_logger(name):
"""Return logger with null handler added if needed."""
if not hasattr(logging.Logger, 'trace'):
logging.addLevelName(TRACE_LEVEL, 'TRACE')
def trace(self, message, *args, **kwargs):
if self.isEnabledFor(TRACE_LEVEL):
# Yes, logger takes its '*ar... | [
"def",
"get_logger",
"(",
"name",
")",
":",
"if",
"not",
"hasattr",
"(",
"logging",
".",
"Logger",
",",
"'trace'",
")",
":",
"logging",
".",
"addLevelName",
"(",
"TRACE_LEVEL",
",",
"'TRACE'",
")",
"def",
"trace",
"(",
"self",
",",
"message",
",",
"*",... | 33.875 | 16.75 |
def _read_geojson_features(data, features=None, prefix=""):
"""Return a dict of features keyed by ID."""
if features is None:
features = collections.OrderedDict()
for i, feature in enumerate(data['features']):
key = feature.get('id', prefix + str(i))
feature_t... | [
"def",
"_read_geojson_features",
"(",
"data",
",",
"features",
"=",
"None",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"i",
",",
"feature",
"in",
"enumer... | 47.722222 | 15.055556 |
def _appendSegment(self, type=None, points=None, smooth=False, **kwargs):
"""
Subclasses may override this method.
"""
self._insertSegment(len(self), type=type, points=points,
smooth=smooth, **kwargs) | [
"def",
"_appendSegment",
"(",
"self",
",",
"type",
"=",
"None",
",",
"points",
"=",
"None",
",",
"smooth",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_insertSegment",
"(",
"len",
"(",
"self",
")",
",",
"type",
"=",
"type",
",",
... | 42.5 | 12.166667 |
def _get_internal_status(pipeline_key=None,
pipeline_dict=None,
slot_dict=None,
barrier_dict=None,
status_dict=None):
"""Gets the UI dictionary of a pipeline from a set of status dictionaries.
Args:
pipeline_key... | [
"def",
"_get_internal_status",
"(",
"pipeline_key",
"=",
"None",
",",
"pipeline_dict",
"=",
"None",
",",
"slot_dict",
"=",
"None",
",",
"barrier_dict",
"=",
"None",
",",
"status_dict",
"=",
"None",
")",
":",
"if",
"pipeline_dict",
"is",
"None",
":",
"pipelin... | 41.740964 | 19.831325 |
def get_display_names_metadata(self):
"""Gets the metadata for all display_names.
return: (osid.Metadata) - metadata for the display_names
*compliance: mandatory -- This method must be implemented.*
"""
metadata = dict(self._display_names_metadata)
metadata.update({'exi... | [
"def",
"get_display_names_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_display_names_metadata",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing_string_values'",
":",
"[",
"t",
"[",
"'text'",
"]",
"for",
"t",
"in",
"self... | 44 | 23.4 |
def linearize(self, index=0):
'''Linearize circular DNA at an index.
:param index: index at which to linearize.
:type index: int
:returns: A linearized version of the current sequence.
:rtype: coral.DNA
:raises: ValueError if the input is linear DNA.
'''
... | [
"def",
"linearize",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"circular",
":",
"raise",
"ValueError",
"(",
"'Cannot relinearize linear DNA.'",
")",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"# Snip at the index",
"if",
"ind... | 29.857143 | 17.952381 |
def plugins(self):
"""
:returns: {plugin_name: plugin_class, ...}
:rtype: dict
"""
if self._plugins is None:
self.load_plugins()
if self._plugins is None:
self._plugins = {}
return self._plugins | [
"def",
"plugins",
"(",
"self",
")",
":",
"if",
"self",
".",
"_plugins",
"is",
"None",
":",
"self",
".",
"load_plugins",
"(",
")",
"if",
"self",
".",
"_plugins",
"is",
"None",
":",
"self",
".",
"_plugins",
"=",
"{",
"}",
"return",
"self",
".",
"_plu... | 27.3 | 8.9 |
def _GetArgsFromRequest(self, request, method_metadata, route_args):
"""Builds args struct out of HTTP request."""
format_mode = GetRequestFormatMode(request, method_metadata)
if request.method in ["GET", "HEAD"]:
if method_metadata.args_type:
unprocessed_request = request.args
if has... | [
"def",
"_GetArgsFromRequest",
"(",
"self",
",",
"request",
",",
"method_metadata",
",",
"route_args",
")",
":",
"format_mode",
"=",
"GetRequestFormatMode",
"(",
"request",
",",
"method_metadata",
")",
"if",
"request",
".",
"method",
"in",
"[",
"\"GET\"",
",",
... | 41.72549 | 19.196078 |
def get_relative_breadcrumbs(self):
"""
get the breadcrumbs as relative to the basedir
"""
basedir = self.basedir
crumbs = self.breadcrumbs
return [(relpath(b, basedir), e) for b, e in crumbs] | [
"def",
"get_relative_breadcrumbs",
"(",
"self",
")",
":",
"basedir",
"=",
"self",
".",
"basedir",
"crumbs",
"=",
"self",
".",
"breadcrumbs",
"return",
"[",
"(",
"relpath",
"(",
"b",
",",
"basedir",
")",
",",
"e",
")",
"for",
"b",
",",
"e",
"in",
"cru... | 26 | 15.111111 |
def ligas(self, query):
""" Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa.
Args:
query (str): Termo para utilizar na busca.
Returns:
Uma lista de instâncias de cartolafc.Liga, uma para cada liga contento o termo utilizado na busca.
... | [
"def",
"ligas",
"(",
"self",
",",
"query",
")",
":",
"url",
"=",
"'{api_url}/ligas'",
".",
"format",
"(",
"api_url",
"=",
"self",
".",
"_api_url",
")",
"data",
"=",
"self",
".",
"_request",
"(",
"url",
",",
"params",
"=",
"dict",
"(",
"q",
"=",
"qu... | 38.153846 | 25.538462 |
def parse_warc_record(self, record):
""" Parse warc record
"""
entry = self._create_index_entry(record.rec_type)
if record.rec_type == 'warcinfo':
entry['url'] = record.rec_headers.get_header('WARC-Filename')
entry['urlkey'] = entry['url']
entry['_wa... | [
"def",
"parse_warc_record",
"(",
"self",
",",
"record",
")",
":",
"entry",
"=",
"self",
".",
"_create_index_entry",
"(",
"record",
".",
"rec_type",
")",
"if",
"record",
".",
"rec_type",
"==",
"'warcinfo'",
":",
"entry",
"[",
"'url'",
"]",
"=",
"record",
... | 36.509434 | 20.622642 |
def getOperation(self, ps, action):
'''Returns a method of class.
action -- soapAction value
'''
opName = self.getOperationName(ps, action)
return getattr(self, opName) | [
"def",
"getOperation",
"(",
"self",
",",
"ps",
",",
"action",
")",
":",
"opName",
"=",
"self",
".",
"getOperationName",
"(",
"ps",
",",
"action",
")",
"return",
"getattr",
"(",
"self",
",",
"opName",
")"
] | 34.333333 | 9 |
def apply_tile_groups(self, tile_groups):
"""Increase mana, xp, money, anvils and scrolls based on tile groups."""
self_increase_types = ('r', 'g', 'b', 'y', 'x', 'm', 'h', 'c')
attack_types = ('s', '*')
total_attack = 0
for tile_group in tile_groups:
group_type = Non... | [
"def",
"apply_tile_groups",
"(",
"self",
",",
"tile_groups",
")",
":",
"self_increase_types",
"=",
"(",
"'r'",
",",
"'g'",
",",
"'b'",
",",
"'y'",
",",
"'x'",
",",
"'m'",
",",
"'h'",
",",
"'c'",
")",
"attack_types",
"=",
"(",
"'s'",
",",
"'*'",
")",
... | 43.575 | 11.475 |
def as_bel(self) -> str:
"""Return this fusion range as a BEL string."""
return '{reference}.{start}_{stop}'.format(
reference=self[FUSION_REFERENCE],
start=self[FUSION_START],
stop=self[FUSION_STOP],
) | [
"def",
"as_bel",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{reference}.{start}_{stop}'",
".",
"format",
"(",
"reference",
"=",
"self",
"[",
"FUSION_REFERENCE",
"]",
",",
"start",
"=",
"self",
"[",
"FUSION_START",
"]",
",",
"stop",
"=",
"self",
"[",
... | 36.571429 | 10.142857 |
def make_new_projection_values(self,width=160):
"""Run do_step function until the diagramms have diverged from each other.
Also determines how big the figure is going to be by calculating the borders
from new residue coordinates. These are then added some buffer space.
"""
#Make... | [
"def",
"make_new_projection_values",
"(",
"self",
",",
"width",
"=",
"160",
")",
":",
"#Make gap between residues bigger if plots have a lot of rings - each ring after the 4th",
"#give extra 12.5px space",
"start",
"=",
"timer",
"(",
")",
"if",
"self",
".",
"topology_data",
... | 51.736842 | 24.526316 |
def add_install_defaults(args):
"""Add any saved installation defaults to the upgrade.
"""
# Ensure we install data if we've specified any secondary installation targets
if len(args.genomes) > 0 or len(args.aligners) > 0 or len(args.datatarget) > 0:
args.install_data = True
install_config = ... | [
"def",
"add_install_defaults",
"(",
"args",
")",
":",
"# Ensure we install data if we've specified any secondary installation targets",
"if",
"len",
"(",
"args",
".",
"genomes",
")",
">",
"0",
"or",
"len",
"(",
"args",
".",
"aligners",
")",
">",
"0",
"or",
"len",
... | 47.621622 | 17.648649 |
def _required_envs(env_vars):
"""
Parse environment variables for required values,
raising a `BrowserConfig` error if they are not found.
Returns a `dict` of environment variables.
"""
envs = {
key: os.environ.get(key)
for key in env_vars
}
# Check for missing keys
... | [
"def",
"_required_envs",
"(",
"env_vars",
")",
":",
"envs",
"=",
"{",
"key",
":",
"os",
".",
"environ",
".",
"get",
"(",
"key",
")",
"for",
"key",
"in",
"env_vars",
"}",
"# Check for missing keys",
"missing",
"=",
"[",
"key",
"for",
"key",
",",
"val",
... | 28.5 | 20.192308 |
def split(self):
"""Split a duplicate."""
key = '%s/split' % self.key
return self._server.query(key, method=self._server._session.put) | [
"def",
"split",
"(",
"self",
")",
":",
"key",
"=",
"'%s/split'",
"%",
"self",
".",
"key",
"return",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"put",
")"
] | 38.75 | 15.25 |
def CountMethodCall(fn):
""" Decorator for counting memoizer hits/misses while retrieving
a simple value in a class method. It wraps the given method
fn and uses a CountValue object to keep track of the
caching statistics.
Wrapping gets enabled by calling EnableMemoization().
"""... | [
"def",
"CountMethodCall",
"(",
"fn",
")",
":",
"if",
"use_memoizer",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"CounterList",
"key",
"=",
"self",
".",
"__class__",
".",
"__name__",
"+",
"'.'",
... | 40.578947 | 15.157895 |
def _is_in_comment_type(token_type):
"""Return true if this kind of token can be inside a comment."""
return token_type in [TokenType.Comment,
TokenType.Newline,
TokenType.Whitespace,
TokenType.RST,
TokenType... | [
"def",
"_is_in_comment_type",
"(",
"token_type",
")",
":",
"return",
"token_type",
"in",
"[",
"TokenType",
".",
"Comment",
",",
"TokenType",
".",
"Newline",
",",
"TokenType",
".",
"Whitespace",
",",
"TokenType",
".",
"RST",
",",
"TokenType",
".",
"BeginRSTComm... | 47.888889 | 5.666667 |
def dist(appname='',version=''):
'''makes a tarball for redistributing the sources'''
import tarfile
if not appname:appname=Utils.g_module.APPNAME
if not version:version=Utils.g_module.VERSION
tmp_folder=appname+'-'+version
if g_gz in['gz','bz2']:
arch_name=tmp_folder+'.tar.'+g_gz
else:
arch_name=tmp_folder+... | [
"def",
"dist",
"(",
"appname",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"import",
"tarfile",
"if",
"not",
"appname",
":",
"appname",
"=",
"Utils",
".",
"g_module",
".",
"APPNAME",
"if",
"not",
"version",
":",
"version",
"=",
"Utils",
".",
"g_m... | 25.888889 | 18.644444 |
def setContentsMargins(self, left, top, right, bottom):
"""
Sets the contents margins for this node to the inputed values.
:param left | <int>
top | <int>
right | <int>
bottom | <int>
"""
self._ma... | [
"def",
"setContentsMargins",
"(",
"self",
",",
"left",
",",
"top",
",",
"right",
",",
"bottom",
")",
":",
"self",
".",
"_margins",
"=",
"(",
"left",
",",
"top",
",",
"right",
",",
"bottom",
")",
"self",
".",
"adjustTitleFont",
"(",
")"
] | 34.272727 | 10.818182 |
def reindex_repo_dev_panel(self, project, repository):
"""
Reindex all of the Jira issues related to this repository, including branches and pull requests.
This automatically happens as part of an upgrade, and calling this manually should only be required
if something unforeseen happens ... | [
"def",
"reindex_repo_dev_panel",
"(",
"self",
",",
"project",
",",
"repository",
")",
":",
"url",
"=",
"'rest/jira-dev/1.0/projects/{projectKey}/repos/{repositorySlug}/reindex'",
".",
"format",
"(",
"projectKey",
"=",
"project",
",",
"repositorySlug",
"=",
"repository",
... | 61.692308 | 36.307692 |
def AnularCTG(self, carta_porte, ctg):
"Anular el CTG si se creó el mismo por error"
response = self.client.anularCTG(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
... | [
"def",
"AnularCTG",
"(",
"self",
",",
"carta_porte",
",",
"ctg",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"anularCTG",
"(",
"request",
"=",
"dict",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",... | 48.1875 | 12.5625 |
def mainloop(self):
""" The main loop.
"""
# Print usage if not enough args or bad options
if len(self.args) < 1:
self.parser.error("You have to provide the root directory of your watch tree, or a metafile path!")
configuration.engine.load_config()
pathname ... | [
"def",
"mainloop",
"(",
"self",
")",
":",
"# Print usage if not enough args or bad options",
"if",
"len",
"(",
"self",
".",
"args",
")",
"<",
"1",
":",
"self",
".",
"parser",
".",
"error",
"(",
"\"You have to provide the root directory of your watch tree, or a metafile ... | 45.28125 | 26.8125 |
def pickFilepath( self ):
"""
Prompts the user to select a filepath from the system based on the \
current filepath mode.
"""
mode = self.filepathMode()
filepath = ''
filepaths = []
curr_dir = nativestring(self._filepathEdit.text())
if (... | [
"def",
"pickFilepath",
"(",
"self",
")",
":",
"mode",
"=",
"self",
".",
"filepathMode",
"(",
")",
"filepath",
"=",
"''",
"filepaths",
"=",
"[",
"]",
"curr_dir",
"=",
"nativestring",
"(",
"self",
".",
"_filepathEdit",
".",
"text",
"(",
")",
")",
"if",
... | 43.904762 | 19.619048 |
def prepare(self):
"""Prepare server to serving requests.
It binds a socket's port, setups the socket to ``listen()`` and does
other preparing things.
"""
self._interrupt = None
if self.software is None:
self.software = '%s Server' % self.version
# ... | [
"def",
"prepare",
"(",
"self",
")",
":",
"self",
".",
"_interrupt",
"=",
"None",
"if",
"self",
".",
"software",
"is",
"None",
":",
"self",
".",
"software",
"=",
"'%s Server'",
"%",
"self",
".",
"version",
"# Select the appropriate socket",
"self",
".",
"so... | 34.373134 | 16.238806 |
def customer_card_id(self, customer_card_id):
"""
Sets the customer_card_id of this ChargeRequest.
The ID of the customer card on file to charge. Do not provide a value for this field if you provide a value for `card_nonce`. If you provide this value, you _must_ also provide a value for `custom... | [
"def",
"customer_card_id",
"(",
"self",
",",
"customer_card_id",
")",
":",
"if",
"customer_card_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `customer_card_id`, must not be `None`\"",
")",
"if",
"len",
"(",
"customer_card_id",
")",
">",
"19... | 49.4 | 32.866667 |
def sprint_info(self, board_id, sprint_id):
"""Return the information about a sprint.
:param board_id: the board retrieving issues from. Deprecated and ignored.
:param sprint_id: the sprint retrieving issues from
"""
sprint = Sprint(self._options, self._session)
sprint.f... | [
"def",
"sprint_info",
"(",
"self",
",",
"board_id",
",",
"sprint_id",
")",
":",
"sprint",
"=",
"Sprint",
"(",
"self",
".",
"_options",
",",
"self",
".",
"_session",
")",
"sprint",
".",
"find",
"(",
"sprint_id",
")",
"return",
"sprint",
".",
"raw"
] | 39.111111 | 15.777778 |
def add_backend_policy(self, json_data):
"""Attaches backend server policies to an ELB
Args:
json_data (json): return data from ELB upsert
"""
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclient = env.client('elb')
# Attach ... | [
"def",
"add_backend_policy",
"(",
"self",
",",
"json_data",
")",
":",
"env",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"profile_name",
"=",
"self",
".",
"env",
",",
"region_name",
"=",
"self",
".",
"region",
")",
"elbclient",
"=",
"env",
".",
... | 48.666667 | 21.888889 |
def do_gate_matrix(self, matrix: np.ndarray,
qubits: Sequence[int]) -> 'AbstractQuantumSimulator':
"""
Apply an arbitrary unitary; not necessarily a named gate.
:param matrix: The unitary matrix to apply. No checks are done
:param qubits: A list of qubits to apply... | [
"def",
"do_gate_matrix",
"(",
"self",
",",
"matrix",
":",
"np",
".",
"ndarray",
",",
"qubits",
":",
"Sequence",
"[",
"int",
"]",
")",
"->",
"'AbstractQuantumSimulator'",
":",
"unitary",
"=",
"lifted_gate_matrix",
"(",
"matrix",
"=",
"matrix",
",",
"qubit_ind... | 48.25 | 23.25 |
def addCategory(self, categoryUri, weight):
"""
add a relevant category to the topic page
@param categoryUri: uri of the category to be added
@param weight: importance of the provided category (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weigh... | [
"def",
"addCategory",
"(",
"self",
",",
"categoryUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"ca... | 55.375 | 22.625 |
def get_action(self, action):
"""Get a callable action."""
func_name = action.replace('-', '_')
if not hasattr(self, func_name):
# Function doesn't exist
raise DaemonError(
'Invalid action "{action}"'.format(action=action))
func = getattr(self, fu... | [
"def",
"get_action",
"(",
"self",
",",
"action",
")",
":",
"func_name",
"=",
"action",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"func_name",
")",
":",
"# Function doesn't exist",
"raise",
"DaemonError",
"(",
... | 37.375 | 14.75 |
def calcFnWeight(node):
'''Calculates the weight of a function definition by recursively counting
its child nodes in the AST. Note that the tree traversal will become
O(n^2) instead of O(n) if this feature is enabled.'''
stack = [node]
count = 0
while len(stack) > 0:
node = stack.pop()... | [
"def",
"calcFnWeight",
"(",
"node",
")",
":",
"stack",
"=",
"[",
"node",
"]",
"count",
"=",
"0",
"while",
"len",
"(",
"stack",
")",
">",
"0",
":",
"node",
"=",
"stack",
".",
"pop",
"(",
")",
"children",
"=",
"[",
"x",
"for",
"x",
"in",
"ast",
... | 37.416667 | 20.25 |
def scrollParts( self, amount ):
"""
Scrolls the parts to offset the scrolling amount.
:param amount | <int>
"""
change = self._scrollAmount - amount
self._partsWidget.scroll(change, 0)
self._scrollAmount = amount | [
"def",
"scrollParts",
"(",
"self",
",",
"amount",
")",
":",
"change",
"=",
"self",
".",
"_scrollAmount",
"-",
"amount",
"self",
".",
"_partsWidget",
".",
"scroll",
"(",
"change",
",",
"0",
")",
"self",
".",
"_scrollAmount",
"=",
"amount"
] | 30.555556 | 8.333333 |
def delete(self):
"""Mark an instance and all of its databases for permanent deletion.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance
Immediately upon completion of the request:
... | [
"def",
"delete",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_client",
".",
"instance_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"api",
".",
"delete_instance",
"(",
"self",
".",
"name",
",",
"metadata",
"=",
... | 37.210526 | 29.368421 |
def _get_class_repr(cls, type_, bound, keyfunc, keyfunc_name):
# type: (Any, slice, Callable, str) -> str
"""Return a class representation using the slice parameters.
Args:
type_: The type the class was sliced with.
bound: The boundaries specified for the values of type_... | [
"def",
"_get_class_repr",
"(",
"cls",
",",
"type_",
",",
"bound",
",",
"keyfunc",
",",
"keyfunc_name",
")",
":",
"# type: (Any, slice, Callable, str) -> str",
"if",
"keyfunc",
"is",
"not",
"cls",
".",
"_default",
":",
"return",
"\"{}.{}[{}, {}, {}]\"",
".",
"forma... | 34.75 | 13.928571 |
def as_swc_standard_format(self):
"""Format defined for integration and correlation.
:return:
"""
_issues = []
source_list = []
for key, issue in self.issues.items():
idx = self.source.get_source_index(issue.bytecode_hash)
try:
t... | [
"def",
"as_swc_standard_format",
"(",
"self",
")",
":",
"_issues",
"=",
"[",
"]",
"source_list",
"=",
"[",
"]",
"for",
"key",
",",
"issue",
"in",
"self",
".",
"issues",
".",
"items",
"(",
")",
":",
"idx",
"=",
"self",
".",
"source",
".",
"get_source_... | 32.878049 | 19.097561 |
def ajContractions(self):
""" Charge et établit une liste qui donne, chaque contraction, forme non contracte qui lui correspond.
"""
for lin in lignesFichier(self.path("contractions.la")):
ass1, ass2 = tuple(lin.split(':'))
self.lemmatiseur._contractions[ass1] = ass2 | [
"def",
"ajContractions",
"(",
"self",
")",
":",
"for",
"lin",
"in",
"lignesFichier",
"(",
"self",
".",
"path",
"(",
"\"contractions.la\"",
")",
")",
":",
"ass1",
",",
"ass2",
"=",
"tuple",
"(",
"lin",
".",
"split",
"(",
"':'",
")",
")",
"self",
".",
... | 51.666667 | 9.833333 |
def run_checks(self):
"""Run all the checks functions.
Returns
-------
bool
True if all the checks are true
False otherwise
dict
Dictionary of lists of differences
"""
result = True
differen... | [
"def",
"run_checks",
"(",
"self",
")",
":",
"result",
"=",
"True",
"differences_dict",
"=",
"{",
"}",
"if",
"'tables'",
"not",
"in",
"self",
".",
"ignore_list",
":",
"tmp_result",
",",
"differences_dict",
"[",
"'tables'",
"]",
"=",
"self",
".",
"check_tabl... | 44.255319 | 16.744681 |
def pipeline(*functions, funcs=None):
"""like pipe, but curried:
pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs)))
"""
if funcs:
functions = funcs
head, *tail = functions
return lambda *args, **kwargs: pipe(head(*args, **kwargs), funcs=tail) | [
"def",
"pipeline",
"(",
"*",
"functions",
",",
"funcs",
"=",
"None",
")",
":",
"if",
"funcs",
":",
"functions",
"=",
"funcs",
"head",
",",
"",
"*",
"tail",
"=",
"functions",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"pipe",
"("... | 31.333333 | 17.888889 |
def cmd_average_response_time(self):
"""Returns the average response time of all, non aborted, requests."""
average = [
line.time_wait_response
for line in self._valid_lines
if line.time_wait_response >= 0
]
divisor = float(len(average))
if di... | [
"def",
"cmd_average_response_time",
"(",
"self",
")",
":",
"average",
"=",
"[",
"line",
".",
"time_wait_response",
"for",
"line",
"in",
"self",
".",
"_valid_lines",
"if",
"line",
".",
"time_wait_response",
">=",
"0",
"]",
"divisor",
"=",
"float",
"(",
"len",... | 32.5 | 13.5 |
def show_firmware_version_output_show_firmware_version_build_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_firmware_vers... | [
"def",
"show_firmware_version_output_show_firmware_version_build_time",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_firmware_version",
"=",
"ET",
".",
"Element",
"(",
"\"show_firmware_version\"",
... | 47.307692 | 18.615385 |
def validate_time(self, duration=False):
""" Validate filter condition (template method) for timestamps and durations.
"""
super(TimeFilter, self).validate()
timestamp = now = time.time()
if str(self._value).isdigit():
# Literal UNIX timestamp
try:
... | [
"def",
"validate_time",
"(",
"self",
",",
"duration",
"=",
"False",
")",
":",
"super",
"(",
"TimeFilter",
",",
"self",
")",
".",
"validate",
"(",
")",
"timestamp",
"=",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"str",
"(",
"self",
".",
"_val... | 38.827586 | 16.172414 |
def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
r... | [
"def",
"is_dataframe",
"(",
"obj",
")",
":",
"try",
":",
"# This is the best method of type checking",
"from",
"pandas",
"import",
"DataFrame",
"return",
"isinstance",
"(",
"obj",
",",
"DataFrame",
")",
"except",
"ImportError",
":",
"# Pandas is not a dependency, so thi... | 29.3125 | 16.6875 |
def pretend_option(fn):
# type: (FunctionType) -> FunctionType
""" Decorator to add a --pretend option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'pretend' if the command n... | [
"def",
"pretend_option",
"(",
"fn",
")",
":",
"# type: (FunctionType) -> FunctionType",
"def",
"set_pretend",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=missing-docstring",
"# type: (click.Context, str, Any) -> None",
"from",
"peltak",
".",
"core... | 34.611111 | 19.944444 |
def learn(self, inputPattern, inputCategory, partitionId=None, isSparse=0,
rowID=None):
"""
Train the classifier to associate specified input pattern with a
particular category.
:param inputPattern: (list) The pattern to be assigned a category. If
isSparse is 0, this should be a den... | [
"def",
"learn",
"(",
"self",
",",
"inputPattern",
",",
"inputCategory",
",",
"partitionId",
"=",
"None",
",",
"isSparse",
"=",
"0",
",",
"rowID",
"=",
"None",
")",
":",
"if",
"self",
".",
"verbosity",
">=",
"1",
":",
"print",
"\"%s learn:\"",
"%",
"g_d... | 39.945205 | 21.671233 |
def add(doc, pointer, value):
"""Add element to sequence, member to mapping.
:param doc: the document base
:param pointer: the path to add in it
:param value: the new value
:return: the new object
"""
return Target(doc).add(pointer, value).document | [
"def",
"add",
"(",
"doc",
",",
"pointer",
",",
"value",
")",
":",
"return",
"Target",
"(",
"doc",
")",
".",
"add",
"(",
"pointer",
",",
"value",
")",
".",
"document"
] | 29.888889 | 10.222222 |
def cell_fate(data, groupby='clusters', disconnected_groups=None, self_transitions=False, n_neighbors=None, copy=False):
"""Computes individual cell endpoints
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
groupby: `str` (default: `'clusters'`)
Key to whi... | [
"def",
"cell_fate",
"(",
"data",
",",
"groupby",
"=",
"'clusters'",
",",
"disconnected_groups",
"=",
"None",
",",
"self_transitions",
"=",
"False",
",",
"n_neighbors",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"adata",
"=",
"data",
".",
"copy",
"... | 39.622642 | 19.735849 |
def iter_change_type(self, change_type):
"""
:return:
iterator yielding Diff instances that match the given change_type
:param change_type:
Member of DiffIndex.change_type, namely:
* 'A' for added paths
* 'D' for deleted paths
* 'R' f... | [
"def",
"iter_change_type",
"(",
"self",
",",
"change_type",
")",
":",
"if",
"change_type",
"not",
"in",
"self",
".",
"change_type",
":",
"raise",
"ValueError",
"(",
"\"Invalid change type: %s\"",
"%",
"change_type",
")",
"for",
"diff",
"in",
"self",
":",
"if",... | 36.178571 | 16.714286 |
def from_maildir(self, codes: str) -> FrozenSet[Flag]:
"""Return the set of IMAP flags that correspond to the letter codes.
Args:
codes: The letter codes to map.
"""
flags = set()
for code in codes:
if code == ',':
break
to_sy... | [
"def",
"from_maildir",
"(",
"self",
",",
"codes",
":",
"str",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"flags",
"=",
"set",
"(",
")",
"for",
"code",
"in",
"codes",
":",
"if",
"code",
"==",
"','",
":",
"break",
"to_sys",
"=",
"self",
".",
"_... | 30.105263 | 13.105263 |
def count_by_type(self):
"""Count how many times each individual salt bridge occured throughout the simulation.
Returns numpy array."""
saltbridges = defaultdict(int)
for contact in self.timeseries:
#count by residue name not by proteinring
pkey = (contact.liganda... | [
"def",
"count_by_type",
"(",
"self",
")",
":",
"saltbridges",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"contact",
"in",
"self",
".",
"timeseries",
":",
"#count by residue name not by proteinring",
"pkey",
"=",
"(",
"contact",
".",
"ligandatomid",
",",
"contac... | 57.714286 | 18.928571 |
def brozzler_new_site(argv=None):
'''
Command line utility entry point for queuing a new brozzler site.
Takes a seed url and creates a site and page object in rethinkdb, which
brozzler-workers will look at and start crawling.
'''
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
... | [
"def",
"brozzler_new_site",
"(",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"argv",
"or",
"sys",
".",
"argv",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"argv",
"[",
"0",
"]",
")"... | 44.303571 | 18.410714 |
def generate_context(context_file='cookiecutter.json', default_context=None,
extra_context=None):
"""Generate the context for a Cookiecutter project template.
Loads the JSON file as a Python object, with key being the JSON filename.
:param context_file: JSON file containing key/value ... | [
"def",
"generate_context",
"(",
"context_file",
"=",
"'cookiecutter.json'",
",",
"default_context",
"=",
"None",
",",
"extra_context",
"=",
"None",
")",
":",
"context",
"=",
"OrderedDict",
"(",
"[",
"]",
")",
"try",
":",
"with",
"open",
"(",
"context_file",
... | 41.05 | 20.775 |
def _close_pidfile(self):
"""Closes and removes the PID file."""
if self._pid_fd is not None:
os.close(self._pid_fd)
try:
os.remove(self.pidfile)
except OSError as ex:
if ex.errno != errno.ENOENT:
raise | [
"def",
"_close_pidfile",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pid_fd",
"is",
"not",
"None",
":",
"os",
".",
"close",
"(",
"self",
".",
"_pid_fd",
")",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"pidfile",
")",
"except",
"OSError",
"a... | 30.888889 | 9.777778 |
def LinShuReductionFactor(axiPot,R,sigmar,nonaxiPot=None,
k=None,m=None,OmegaP=None):
"""
NAME:
LinShuReductionFactor
PURPOSE:
Calculate the Lin & Shu (1966) reduction factor: the reduced linear response of a kinematically-warm stellar disk to a perturbation
I... | [
"def",
"LinShuReductionFactor",
"(",
"axiPot",
",",
"R",
",",
"sigmar",
",",
"nonaxiPot",
"=",
"None",
",",
"k",
"=",
"None",
",",
"m",
"=",
"None",
",",
"OmegaP",
"=",
"None",
")",
":",
"axiPot",
"=",
"flatten",
"(",
"axiPot",
")",
"from",
"galpy",
... | 30.320755 | 26.811321 |
def save(self):
"""
Save environment settings into environment directory, overwriting
any existing configuration and discarding site config
"""
task.save_new_environment(self.name, self.datadir, self.target,
self.ckan_version, self.deploy_target, self.always_prod) | [
"def",
"save",
"(",
"self",
")",
":",
"task",
".",
"save_new_environment",
"(",
"self",
".",
"name",
",",
"self",
".",
"datadir",
",",
"self",
".",
"target",
",",
"self",
".",
"ckan_version",
",",
"self",
".",
"deploy_target",
",",
"self",
".",
"always... | 44.285714 | 19.714286 |
def read(self, handle):
'''Read and parse binary header data from a file handle.
This method reads exactly 512 bytes from the beginning of the given file
handle.
Parameters
----------
handle : file handle
The given handle will be reset to 0 using `seek` and ... | [
"def",
"read",
"(",
"self",
",",
"handle",
")",
":",
"handle",
".",
"seek",
"(",
"0",
")",
"(",
"self",
".",
"parameter_block",
",",
"magic",
",",
"self",
".",
"point_count",
",",
"self",
".",
"analog_count",
",",
"self",
".",
"first_frame",
",",
"se... | 29.777778 | 23 |
def _get_all_headers(self, method, endpoint, request_bytes, custom_headers):
"""
:type method: str
:type endpoint: str
:type request_bytes: bytes
:type custom_headers: dict[str, str]
:rtype: dict[str, str]
"""
headers = self._get_default_headers()
... | [
"def",
"_get_all_headers",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"request_bytes",
",",
"custom_headers",
")",
":",
"headers",
"=",
"self",
".",
"_get_default_headers",
"(",
")",
"headers",
".",
"update",
"(",
"custom_headers",
")",
"if",
"self",
... | 30.75 | 19 |
def list_files(self, id=None, path="/"):
""" List files in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-ls.html
arguments:
- id
- path
returns: list
raises:
- nomad.api.exceptions.Bas... | [
"def",
"list_files",
"(",
"self",
",",
"id",
"=",
"None",
",",
"path",
"=",
"\"/\"",
")",
":",
"if",
"id",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")"... | 34.058824 | 20.941176 |
def clean_attribute(attribute):
'''
Normalize attribute names for shorthand and work arounds for limitations
in Python's syntax
'''
# Shorthand
attribute = {
'cls': 'class',
'className': 'class',
'class_name': 'class',
'fr': 'for',
'html_for': 'for',
'htmlFor... | [
"def",
"clean_attribute",
"(",
"attribute",
")",
":",
"# Shorthand",
"attribute",
"=",
"{",
"'cls'",
":",
"'class'",
",",
"'className'",
":",
"'class'",
",",
"'class_name'",
":",
"'class'",
",",
"'fr'",
":",
"'for'",
",",
"'html_for'",
":",
"'for'",
",",
"... | 26.275862 | 22.137931 |
def incr(self, field, by=1):
""" :see::meth:RedisMap.incr """
return self._client.hincrby(self.key_prefix, field, by) | [
"def",
"incr",
"(",
"self",
",",
"field",
",",
"by",
"=",
"1",
")",
":",
"return",
"self",
".",
"_client",
".",
"hincrby",
"(",
"self",
".",
"key_prefix",
",",
"field",
",",
"by",
")"
] | 43.666667 | 11.666667 |
def download_file(url, suffix=''):
"""Download attached file as temporary file.
Parameters
----------
url : string
SCO-API download Url
suffix : string, optional
If suffix is specified, the name of the downloaded file will end with
that suffix, otherwise there will be no suf... | [
"def",
"download_file",
"(",
"url",
",",
"suffix",
"=",
"''",
")",
":",
"r",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"# Save attached file in temp file and return path to temp file",
"fd",
",",
"f_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
... | 28.090909 | 19.227273 |
def local_score(self, variable, parents):
"Computes a score that measures how much a \
given variable is \"influenced\" by a given list of potential parents."
var_states = self.state_names[variable]
var_cardinality = len(var_states)
state_counts = self.state_counts(variable, par... | [
"def",
"local_score",
"(",
"self",
",",
"variable",
",",
"parents",
")",
":",
"var_states",
"=",
"self",
".",
"state_names",
"[",
"variable",
"]",
"var_cardinality",
"=",
"len",
"(",
"var_states",
")",
"state_counts",
"=",
"self",
".",
"state_counts",
"(",
... | 43.5 | 26.5 |
def potential_from_grid(self, grid):
"""
Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
eta =... | [
"def",
"potential_from_grid",
"(",
"self",
",",
"grid",
")",
":",
"eta",
"=",
"(",
"1.0",
"/",
"self",
".",
"scale_radius",
")",
"*",
"self",
".",
"grid_to_grid_radii",
"(",
"grid",
")",
"+",
"0j",
"return",
"np",
".",
"real",
"(",
"2.0",
"*",
"self"... | 42.454545 | 25.181818 |
def delete_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
'''
Deletes a given apiKey
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.delete_api_key apikeystring
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | [
"def",
"delete_api_key",
"(",
"apiKey",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key... | 28.470588 | 27.529412 |
def add_device(self, path):
"Add a device to the daemon's internal search list."
if self.__get_control_socket():
self.sock.sendall("+%s\r\n\x00" % path)
self.sock.recv(12)
self.sock.close() | [
"def",
"add_device",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"__get_control_socket",
"(",
")",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"\"+%s\\r\\n\\x00\"",
"%",
"path",
")",
"self",
".",
"sock",
".",
"recv",
"(",
"12",
")",
"se... | 39.333333 | 11 |
def _md5(path: pathlib.PurePath):
"""
Calculate the MD5 checksum of a file.
:param path: The path of the file whose checksum to calculate.
:return: The lowercase hex representation of the file's MD5
checksum, exactly 32 chars long.
"""
hash_ = hashlib... | [
"def",
"_md5",
"(",
"path",
":",
"pathlib",
".",
"PurePath",
")",
":",
"hash_",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"re... | 36.692308 | 12.846154 |
def from_code(cls, code_object):
"""
Disassemble a Python code object and make a Code object from the bits.
This is the expected way to make a Code instance. But you are welcome
to call Code() directly if you wish.
"""
# It's an annoyance to keep having to add ".__code__"... | [
"def",
"from_code",
"(",
"cls",
",",
"code_object",
")",
":",
"# It's an annoyance to keep having to add \".__code__\" to a function",
"# name, so let's automate that when needed.",
"if",
"isinstance",
"(",
"code_object",
",",
"types",
".",
"FunctionType",
")",
":",
"code_obj... | 45.242424 | 22.866667 |
def validate_distribution_parameters(distribution, params):
"""Ensures that necessary parameters for a distribution are present and that all parameters are sensical.
If parameters necessary to construct a distribution are missing or invalid, this function raises ValueError\
with an informative descri... | [
"def",
"validate_distribution_parameters",
"(",
"distribution",
",",
"params",
")",
":",
"norm_msg",
"=",
"\"norm distributions require 0 parameters and optionally 'mean', 'std_dev'.\"",
"beta_msg",
"=",
"\"beta distributions require 2 positive parameters 'alpha', 'beta' and optionally 'lo... | 43.888889 | 26.15873 |
def length(text, maxval=None, encoding=None):
'''
Count the length of a str the way Twitter does,
double-counting "wide" characters (e.g. ideographs, emoji)
Args:
text (str): Text to count. Must be a unicode string in Python 2
maxval (int): The maximum encoding that will be counted as 1... | [
"def",
"length",
"(",
"text",
",",
"maxval",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"maxval",
"=",
"maxval",
"or",
"4351",
"try",
":",
"assert",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"binary_type",
")",
"except",
"AssertionEr... | 36.368421 | 27.210526 |
def aggregate_per_prefix(self, start_time, end_time, limit=0, net_masks='', exclude_net_masks=False, filter_proto=None):
""" Given a time range aggregates bytes per prefix.
Args:
start_time: A string representing the starting time of the time range
end_time: A string... | [
"def",
"aggregate_per_prefix",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"limit",
"=",
"0",
",",
"net_masks",
"=",
"''",
",",
"exclude_net_masks",
"=",
"False",
",",
"filter_proto",
"=",
"None",
")",
":",
"if",
"net_masks",
"==",
"''",
":",
"... | 42.387755 | 23.653061 |
def mnemonic(self, index):
"""Make a nice mnemonic
"""
i,c,d0 = self.splitSymbol(index)
iLower, _ = i.code.span(i.index)
iExtra = i.extraBits()
cLower, _ = c.code.span(c.index)
cExtra = c.extraBits()
return 'I{}{}{}C{}{}{}{}'.format(
iLower,
... | [
"def",
"mnemonic",
"(",
"self",
",",
"index",
")",
":",
"i",
",",
"c",
",",
"d0",
"=",
"self",
".",
"splitSymbol",
"(",
"index",
")",
"iLower",
",",
"_",
"=",
"i",
".",
"code",
".",
"span",
"(",
"i",
".",
"index",
")",
"iExtra",
"=",
"i",
"."... | 34.75 | 9 |
def raw_cmd(self, *args, **kwargs):
'''adb command. return the subprocess.Popen object.'''
cmds = [self.adb_path()] + self._host_port_args + list(args)
kwargs['stdout'] = kwargs.get('stdout', subprocess.PIPE)
kwargs['stderr'] = kwargs.get('stderr', subprocess.PIPE)
# if os.name !... | [
"def",
"raw_cmd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmds",
"=",
"[",
"self",
".",
"adb_path",
"(",
")",
"]",
"+",
"self",
".",
"_host_port_args",
"+",
"list",
"(",
"args",
")",
"kwargs",
"[",
"'stdout'",
"]",
"=",... | 51.444444 | 15 |
async def _get_input_dialog(self, dialog):
"""
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'Input... | [
"async",
"def",
"_get_input_dialog",
"(",
"self",
",",
"dialog",
")",
":",
"try",
":",
"if",
"dialog",
".",
"SUBCLASS_OF_ID",
"==",
"0xa21c9795",
":",
"# crc32(b'InputDialogPeer')",
"dialog",
".",
"peer",
"=",
"await",
"self",
".",
"get_input_entity",
"(",
"di... | 41.9375 | 21.0625 |
def send_raw(self, string):
"""Send raw string to the server.
The string will be padded with appropriate CR LF.
"""
if self.socket is None:
raise ServerNotConnectedError("Not connected.")
sender = getattr(self.socket, 'write', self.socket.send)
try:
... | [
"def",
"send_raw",
"(",
"self",
",",
"string",
")",
":",
"if",
"self",
".",
"socket",
"is",
"None",
":",
"raise",
"ServerNotConnectedError",
"(",
"\"Not connected.\"",
")",
"sender",
"=",
"getattr",
"(",
"self",
".",
"socket",
",",
"'write'",
",",
"self",
... | 35.5 | 15.071429 |
def atanh(wave):
r"""
Return the hyperbolic arc tangent of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions docu... | [
"def",
"atanh",
"(",
"wave",
")",
":",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"ValueError",
",",
"\"Math domain error\"",
",",
"bool",
"(",
"(",
"min",
"(",
"wave",
".",
"_dep_vector",
")",
"<",
"-",
"1",
")",
"or",
"(",
"max",
"(",
"wave",
".",
... | 26.076923 | 21.576923 |
def _get_values(self, data_blob, dtype_enum, shape_string):
"""Obtains values for histogram data given blob and dtype enum.
Args:
data_blob: The blob obtained from the database.
dtype_enum: The enum representing the dtype.
shape_string: A comma-separated string of numbers denoting shape.
R... | [
"def",
"_get_values",
"(",
"self",
",",
"data_blob",
",",
"dtype_enum",
",",
"shape_string",
")",
":",
"buf",
"=",
"np",
".",
"frombuffer",
"(",
"data_blob",
",",
"dtype",
"=",
"tf",
".",
"DType",
"(",
"dtype_enum",
")",
".",
"as_numpy_dtype",
")",
"retu... | 49 | 20.272727 |
def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader:
"Returns appropriate `Dataset` for validation, training, or test (`ds_type`)."
#TODO: refactor
return (self.train_dl if ds_type == DatasetType.Train else
self.test_dl if ds_type == DatasetType.Test else
... | [
"def",
"dl",
"(",
"self",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
")",
"->",
"DeviceDataLoader",
":",
"#TODO: refactor",
"return",
"(",
"self",
".",
"train_dl",
"if",
"ds_type",
"==",
"DatasetType",
".",
"Train",
"else",
"self",... | 58.875 | 26.125 |
def AddWarning(self, warning):
"""Adds a warnings.
Args:
warning (ExtractionWarning): warning.
Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.
"""
self._RaiseIfNotWritable()
warning = self._PrepareAttributeContainer(warning)
... | [
"def",
"AddWarning",
"(",
"self",
",",
"warning",
")",
":",
"self",
".",
"_RaiseIfNotWritable",
"(",
")",
"warning",
"=",
"self",
".",
"_PrepareAttributeContainer",
"(",
"warning",
")",
"self",
".",
"_warnings",
".",
"append",
"(",
"warning",
")",
"self",
... | 23.1875 | 18.0625 |
def get_field_values_list(self, d):
"""
Iterate over a (possibly nested) dict, and return a list
of all children queries, as a dict of the following structure:
{
'field': 'some_field__iexact',
'value': 'some_value',
'value_from': 'optional_range_val1',... | [
"def",
"get_field_values_list",
"(",
"self",
",",
"d",
")",
":",
"fields",
"=",
"[",
"]",
"children",
"=",
"d",
".",
"get",
"(",
"'children'",
",",
"[",
"]",
")",
"for",
"child",
"in",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"dict",
... | 36.774194 | 15.548387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.