text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def connect(
self, host: str = '127.0.0.1', port: int = 7497,
clientId: int = 1, timeout: float = 2):
"""
Connect to a running TWS or IB gateway application.
After the connection is made the client is fully synchronized
and ready to serve requests.
This m... | [
"def",
"connect",
"(",
"self",
",",
"host",
":",
"str",
"=",
"'127.0.0.1'",
",",
"port",
":",
"int",
"=",
"7497",
",",
"clientId",
":",
"int",
"=",
"1",
",",
"timeout",
":",
"float",
"=",
"2",
")",
":",
"return",
"self",
".",
"_run",
"(",
"self",... | 42.857143 | 0.002174 |
def create_signed_bundle(self, sign_alg='RS256', iss_list=None):
"""
Create a signed JWT containing a dictionary with Issuer IDs as keys
and JWKSs as values. If iss_list is empty then all available issuers are
included.
:param sign_alg: Which algorithm to use when signin... | [
"def",
"create_signed_bundle",
"(",
"self",
",",
"sign_alg",
"=",
"'RS256'",
",",
"iss_list",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"dict",
"(",
"iss_list",
")",
"_jwt",
"=",
"JWT",
"(",
"self",
".",
"sign_keys",
",",
"iss",
"=",
"self",
"... | 43.857143 | 0.009569 |
def temperature(self):
"""
Returns the current CPU temperature in degrees celsius.
"""
with io.open(self.sensor_file, 'r') as f:
return float(f.readline().strip()) / 1000 | [
"def",
"temperature",
"(",
"self",
")",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"sensor_file",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"float",
"(",
"f",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
")",
"/",
"1000"
] | 34.833333 | 0.009346 |
def transaction(self,implicit = False):
"""
This returns a context guard which will automatically open and close a transaction
"""
class TransactionManager(object):
def __init__(self,backend,implicit = False):
self.backend = backend
self.impl... | [
"def",
"transaction",
"(",
"self",
",",
"implicit",
"=",
"False",
")",
":",
"class",
"TransactionManager",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"backend",
",",
"implicit",
"=",
"False",
")",
":",
"self",
".",
"backend",
"=",
"b... | 41.333333 | 0.02014 |
def plot_dom_parameters(
data,
detector,
filename,
label,
title,
vmin=0.0,
vmax=10.0,
cmap='RdYlGn_r',
under='deepskyblue',
over='deeppink',
underfactor=1.0,
overfactor=1.0,
missing='lightgray',
hide_limits=F... | [
"def",
"plot_dom_parameters",
"(",
"data",
",",
"detector",
",",
"filename",
",",
"label",
",",
"title",
",",
"vmin",
"=",
"0.0",
",",
"vmax",
"=",
"10.0",
",",
"cmap",
"=",
"'RdYlGn_r'",
",",
"under",
"=",
"'deepskyblue'",
",",
"over",
"=",
"'deeppink'"... | 24.650485 | 0.000379 |
def numparser(strict=False):
"""Return a function that will attempt to parse the value as a number,
trying :func:`int`, :func:`long`, :func:`float` and :func:`complex` in
that order. If all fail, return the value as-is, unless ``strict=True``,
in which case raise the underlying exception.
"""
... | [
"def",
"numparser",
"(",
"strict",
"=",
"False",
")",
":",
"def",
"f",
"(",
"v",
")",
":",
"try",
":",
"return",
"int",
"(",
"v",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"return",
"long",
"(",
"v",
")",
... | 26.137931 | 0.001272 |
def send_command_return(self, command, *arguments):
""" Send command and wait for single line output. """
return self.api.send_command_return(self, command, *arguments) | [
"def",
"send_command_return",
"(",
"self",
",",
"command",
",",
"*",
"arguments",
")",
":",
"return",
"self",
".",
"api",
".",
"send_command_return",
"(",
"self",
",",
"command",
",",
"*",
"arguments",
")"
] | 60.666667 | 0.01087 |
def _build_date_time_time_zone(self, date_time):
""" Converts a datetime to a dateTimeTimeZone resource """
timezone = date_time.tzinfo.zone if date_time.tzinfo is not None else None
return {
self._cc('dateTime'): date_time.strftime('%Y-%m-%dT%H:%M:%S'),
self._cc('timeZon... | [
"def",
"_build_date_time_time_zone",
"(",
"self",
",",
"date_time",
")",
":",
"timezone",
"=",
"date_time",
".",
"tzinfo",
".",
"zone",
"if",
"date_time",
".",
"tzinfo",
"is",
"not",
"None",
"else",
"None",
"return",
"{",
"self",
".",
"_cc",
"(",
"'dateTim... | 54.142857 | 0.01039 |
def authenticate(self, auth_url=None, **kwargs):
"""Authenticates a user via the Keystone Identity API."""
LOG.debug('Beginning user authentication')
if not auth_url:
auth_url = settings.OPENSTACK_KEYSTONE_URL
auth_url, url_fixed = utils.fix_auth_url_version_prefix(auth_url... | [
"def",
"authenticate",
"(",
"self",
",",
"auth_url",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"'Beginning user authentication'",
")",
"if",
"not",
"auth_url",
":",
"auth_url",
"=",
"settings",
".",
"OPENSTACK_KEYSTONE_URL",
"... | 47.915385 | 0.000315 |
def GroupSensorsFind(self, group_id, parameters, filters, namespace = None):
"""
Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in... | [
"def",
"GroupSensorsFind",
"(",
"self",
",",
"group_id",
",",
"parameters",
",",
"filters",
",",
"namespace",
"=",
"None",
")",
":",
"ns",
"=",
"\"default\"",
"if",
"namespace",
"is",
"None",
"else",
"namespace",
"parameters",
"[",
"'namespace'",
"]",
"=",
... | 55.166667 | 0.012871 |
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 | 0.001007 |
def assign_issue(issue_key,
assignee,
server=None,
username=None,
password=None):
'''
Assign the issue to an existing user. Return ``True`` when the issue has
been properly assigned.
issue_key
The JIRA ID of the ticket to manip... | [
"def",
"assign_issue",
"(",
"issue_key",
",",
"assignee",
",",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"jira_",
"=",
"_get_jira",
"(",
"server",
"=",
"server",
",",
"username",
"=",
"username",
",",
... | 27 | 0.00149 |
def makeSequenceRelative(absVSequence):
'''
Puts every value in a list on a continuum between 0 and 1
Also returns the min and max values (to reverse the process)
'''
if len(absVSequence) < 2 or len(set(absVSequence)) == 1:
raise RelativizeSequenceException(absVSequence)
minV = min(ab... | [
"def",
"makeSequenceRelative",
"(",
"absVSequence",
")",
":",
"if",
"len",
"(",
"absVSequence",
")",
"<",
"2",
"or",
"len",
"(",
"set",
"(",
"absVSequence",
")",
")",
"==",
"1",
":",
"raise",
"RelativizeSequenceException",
"(",
"absVSequence",
")",
"minV",
... | 30.6 | 0.002114 |
def add(self, module, **kwargs):
"""Add a module to the chain.
Parameters
----------
module : BaseModule
The new module to add.
kwargs : ``**keywords``
All the keyword arguments are saved as meta information
for the added module. The currently... | [
"def",
"add",
"(",
"self",
",",
"module",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_modules",
".",
"append",
"(",
"module",
")",
"# a sanity check to avoid typo",
"for",
"key",
"in",
"kwargs",
":",
"assert",
"key",
"in",
"self",
".",
"_meta_keys"... | 32.26087 | 0.001308 |
def fs_obj_remove(self, path):
"""Removes a file system object (file, symlink, etc) in the guest. Will
not work on directories, use :py:func:`IGuestSession.directory_remove`
to remove directories.
This method will remove symbolic links in the final path
component, not ... | [
"def",
"fs_obj_remove",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"path can only be an instance of type basestring\"",
")",
"self",
".",
"_call",
"(",
"\"fsObjRemove\"",
... | 38.32 | 0.010183 |
def debug_process(pid):
"""Interrupt a running process and debug it."""
os.kill(pid, signal.SIGUSR1) # Signal process.
pipe = NamedPipe(pipename(pid), 1)
try:
while pipe.is_open():
txt=raw_input(pipe.get()) + '\n'
pipe.put(txt)
except EOFError:
pass # Exit.
... | [
"def",
"debug_process",
"(",
"pid",
")",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGUSR1",
")",
"# Signal process.",
"pipe",
"=",
"NamedPipe",
"(",
"pipename",
"(",
"pid",
")",
",",
"1",
")",
"try",
":",
"while",
"pipe",
".",
"is_ope... | 29.545455 | 0.008955 |
def digest_auth(realm, auth_func):
"""A decorator used to protect methods with HTTP Digest authentication.
"""
def digest_auth_decorator(func):
def func_replacement(self, *args, **kwargs):
# 'self' here is the RequestHandler object, which is inheriting
# from DigestAuthMixin... | [
"def",
"digest_auth",
"(",
"realm",
",",
"auth_func",
")",
":",
"def",
"digest_auth_decorator",
"(",
"func",
")",
":",
"def",
"func_replacement",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# 'self' here is the RequestHandler object, which... | 43.25 | 0.001887 |
def get_events(environment, start_response, headers):
"""
Retrieve events
POST body should contain a JSON encoded version of:
{ namespace: namespace_name (optional),
stream : stream_name,
start_time : starting_time_as_kronos_time,
end_time : ending_time_as_kronos_time,
start_id : only_... | [
"def",
"get_events",
"(",
"environment",
",",
"start_response",
",",
"headers",
")",
":",
"request_json",
"=",
"environment",
"[",
"'json'",
"]",
"try",
":",
"stream",
"=",
"request_json",
"[",
"'stream'",
"]",
"validate_stream",
"(",
"stream",
")",
"except",
... | 34.203125 | 0.008881 |
def read_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None):
""" Reads data selection if small enough.
"""
self.container.read_data(f_start=f_start, f_stop=f_stop,t_start=t_start, t_stop=t_stop)
self.__load_data() | [
"def",
"read_data",
"(",
"self",
",",
"f_start",
"=",
"None",
",",
"f_stop",
"=",
"None",
",",
"t_start",
"=",
"None",
",",
"t_stop",
"=",
"None",
")",
":",
"self",
".",
"container",
".",
"read_data",
"(",
"f_start",
"=",
"f_start",
",",
"f_stop",
"=... | 36.285714 | 0.019231 |
def regulartype(prompt_template="default"):
"""Echo each character typed. Unlike magictype, this echos the characters the
user is pressing.
Returns: command_string | The command to be passed to the shell to run. This is
| typed by the user.
"""
echo_prompt(prompt_templ... | [
"def",
"regulartype",
"(",
"prompt_template",
"=",
"\"default\"",
")",
":",
"echo_prompt",
"(",
"prompt_template",
")",
"command_string",
"=",
"\"\"",
"cursor_position",
"=",
"0",
"with",
"raw_mode",
"(",
")",
":",
"while",
"True",
":",
"in_char",
"=",
"getcha... | 37.842105 | 0.002034 |
def CreateFlowArgs(self, flow_name=None):
"""Creates flow arguments object for a flow with a given name."""
if not self._flow_descriptors:
self._flow_descriptors = {}
result = self._context.SendRequest("ListFlowDescriptors", None)
for item in result.items:
self._flow_descriptors[item.... | [
"def",
"CreateFlowArgs",
"(",
"self",
",",
"flow_name",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_flow_descriptors",
":",
"self",
".",
"_flow_descriptors",
"=",
"{",
"}",
"result",
"=",
"self",
".",
"_context",
".",
"SendRequest",
"(",
"\"ListFlow... | 34.733333 | 0.011215 |
def search_meta_tag(html_doc, prefix, code):
"""
Checks whether the html_doc contains a meta matching the prefix & code
"""
regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>'.format(prefix, code)
meta = re.compile(regex, flags=re.MUL... | [
"def",
"search_meta_tag",
"(",
"html_doc",
",",
"prefix",
",",
"code",
")",
":",
"regex",
"=",
"'<meta\\s+(?:name=([\\'\\\"]){0}\\\\1\\s+content=([\\'\\\"]){1}\\\\2|content=([\\'\\\"]){1}\\\\3\\s+name=([\\'\\\"]){0}\\\\4)\\s*/?>'",
".",
"format",
"(",
"prefix",
",",
"code",
")"... | 43.916667 | 0.011152 |
def loadinfofont(self):
"""Auxiliary method to load font if not yet done."""
if self.infofont == None:
self.infofont = imft.load_path(os.path.join(fontsdir, "courR10.pil")) | [
"def",
"loadinfofont",
"(",
"self",
")",
":",
"if",
"self",
".",
"infofont",
"==",
"None",
":",
"self",
".",
"infofont",
"=",
"imft",
".",
"load_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fontsdir",
",",
"\"courR10.pil\"",
")",
")"
] | 49.25 | 0.02 |
def check_issues(issues, after=None):
"""Checks issues for BEP 1 compliance."""
issues = closed_issues(issues, after) if after else all_issues(issues)
issues = sorted(issues, key=ISSUES_SORT_KEY)
have_warnings = False
for section, issue_group in groupby(issues, key=ISSUES_BY_SECTION):
for ... | [
"def",
"check_issues",
"(",
"issues",
",",
"after",
"=",
"None",
")",
":",
"issues",
"=",
"closed_issues",
"(",
"issues",
",",
"after",
")",
"if",
"after",
"else",
"all_issues",
"(",
"issues",
")",
"issues",
"=",
"sorted",
"(",
"issues",
",",
"key",
"=... | 34.25 | 0.00237 |
def construct_reference_system(
symbols,
candidates=None,
options=None,
):
"""Take a list of symbols and construct gas phase
references system, when possible avoiding O2.
Candidates can be rearranged, where earlier candidates
get higher preference than later candidates
assume symbols so... | [
"def",
"construct_reference_system",
"(",
"symbols",
",",
"candidates",
"=",
"None",
",",
"options",
"=",
"None",
",",
")",
":",
"if",
"hasattr",
"(",
"options",
",",
"'no_hydrogen'",
")",
"and",
"options",
".",
"no_hydrogen",
":",
"add_hydrogen",
"=",
"Fals... | 32.974684 | 0.000745 |
def orig_py_exe(exe): # pragma: no cover (platform specific)
"""A -mvenv virtualenv made from a -mvirtualenv virtualenv installs
packages to the incorrect location. Attempt to find the _original_ exe
and invoke `-mvenv` from there.
See:
- https://github.com/pre-commit/pre-commit/issues/755
- ... | [
"def",
"orig_py_exe",
"(",
"exe",
")",
":",
"# pragma: no cover (platform specific)",
"try",
":",
"prefix_script",
"=",
"'import sys; print(sys.real_prefix)'",
"_",
",",
"prefix",
",",
"_",
"=",
"cmd_output",
"(",
"exe",
",",
"'-c'",
",",
"prefix_script",
")",
"pr... | 32.851852 | 0.001095 |
def load_df_from_file(file_path, sep=",", header=0):
"""Wrapper around pandas' read_csv."""
with tf.gfile.Open(file_path) as infile:
df = pd.read_csv(infile, sep=sep, header=header)
return df | [
"def",
"load_df_from_file",
"(",
"file_path",
",",
"sep",
"=",
"\",\"",
",",
"header",
"=",
"0",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"file_path",
")",
"as",
"infile",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"infile",
",",
"s... | 39.4 | 0.0199 |
def process_node(e):
"""
Process a node element entry into a dict suitable for going into
a Pandas DataFrame.
Parameters
----------
e : dict
Returns
-------
node : dict
"""
uninteresting_tags = {
'source',
'source_ref',
'source:ref',
'history... | [
"def",
"process_node",
"(",
"e",
")",
":",
"uninteresting_tags",
"=",
"{",
"'source'",
",",
"'source_ref'",
",",
"'source:ref'",
",",
"'history'",
",",
"'attribution'",
",",
"'created_by'",
",",
"'tiger:tlid'",
",",
"'tiger:upload_uuid'",
",",
"}",
"node",
"=",
... | 17.666667 | 0.00149 |
def publictypes(self):
""" get all public types """
for t in self.wsdl.schema.types.values():
if t in self.params: continue
if t in self.types: continue
item = (t, t)
self.types.append(item)
tc = lambda x,y: cmp(x[0].name, y[0].name)
self.t... | [
"def",
"publictypes",
"(",
"self",
")",
":",
"for",
"t",
"in",
"self",
".",
"wsdl",
".",
"schema",
".",
"types",
".",
"values",
"(",
")",
":",
"if",
"t",
"in",
"self",
".",
"params",
":",
"continue",
"if",
"t",
"in",
"self",
".",
"types",
":",
... | 36.555556 | 0.017804 |
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
'--vmssname', '-n', required=True, action='store', help='VMSS Name')
arg_parser.add_argument('--rgname', '-g', required=True, action='store',
... | [
"def",
"main",
"(",
")",
":",
"# validate command line arguments",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"arg_parser",
".",
"add_argument",
"(",
"'--vmssname'",
",",
"'-n'",
",",
"required",
"=",
"True",
",",
"action",
"=",
"'store'",
... | 36.880952 | 0.001258 |
def rmtree(path):
"""A version of rmtree that can deal with read-only files and directories.
Needed because the stock shutil.rmtree() fails with an access error
when there are read-only files in the directory on Windows, or when the
directory itself is read-only on Unix.
"""
def onerror(func, p... | [
"def",
"rmtree",
"(",
"path",
")",
":",
"def",
"onerror",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"# Did you know what on Python 3.3 on Windows os.remove() and",
"# os.unlink() are distinct functions?",
"if",
"func",
"is",
"os",
".",
"remove",
"or",
"fu... | 41.555556 | 0.001307 |
def on_setexceptionbreakpoints_request(self, py_db, request):
'''
:param SetExceptionBreakpointsRequest request:
'''
# : :type arguments: SetExceptionBreakpointsArguments
arguments = request.arguments
filters = arguments.filters
exception_options = arguments.excep... | [
"def",
"on_setexceptionbreakpoints_request",
"(",
"self",
",",
"py_db",
",",
"request",
")",
":",
"# : :type arguments: SetExceptionBreakpointsArguments",
"arguments",
"=",
"request",
".",
"arguments",
"filters",
"=",
"arguments",
".",
"filters",
"exception_options",
"=",... | 38.988889 | 0.001668 |
def optimize_wsgi_processes(self):
"""
Based on the number of sites per server and the number of resources on the server,
calculates the optimal number of processes that should be allocated for each WSGI site.
"""
r = self.local_renderer
#r.env.wsgi_processes = 5
... | [
"def",
"optimize_wsgi_processes",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"#r.env.wsgi_processes = 5",
"r",
".",
"env",
".",
"wsgi_server_memory_gb",
"=",
"8",
"verbose",
"=",
"self",
".",
"verbose",
"all_sites",
"=",
"list",
"(",
"self... | 38.083333 | 0.012821 |
def update_user(self, email, first_name, last_name, password, metadata={}):
"""
Update an existing user
:type email: str
:param email: User's email
:type first_name: str
:param first_name: User's first name
:type last_name: str
:param last_name: User's ... | [
"def",
"update_user",
"(",
"self",
",",
"email",
",",
"first_name",
",",
"last_name",
",",
"password",
",",
"metadata",
"=",
"{",
"}",
")",
":",
"data",
"=",
"{",
"'email'",
":",
"email",
",",
"'firstName'",
":",
"first_name",
",",
"'lastName'",
":",
"... | 26.709677 | 0.002331 |
def read(self, **keys):
"""
read a data from an ascii table HDU
By default, all rows are read. Send rows= to select subsets of the
data. Table data are read into a recarray for multiple columns,
plain array for a single column.
parameters
----------
co... | [
"def",
"read",
"(",
"self",
",",
"*",
"*",
"keys",
")",
":",
"rows",
"=",
"keys",
".",
"get",
"(",
"'rows'",
",",
"None",
")",
"columns",
"=",
"keys",
".",
"get",
"(",
"'columns'",
",",
"None",
")",
"# if columns is None, returns all. Guaranteed to be uni... | 38.961538 | 0.000481 |
def disconnect(self):
""" Disconnect from chassis and server. """
if self.root.ref is not None:
self.api.disconnect()
self.root = None | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"root",
".",
"ref",
"is",
"not",
"None",
":",
"self",
".",
"api",
".",
"disconnect",
"(",
")",
"self",
".",
"root",
"=",
"None"
] | 33.2 | 0.011765 |
def get_name_from_name_consensus_hash( self, name_consensus_hash, sender_script_pubkey, block_id ):
"""
Find the name.ns_id from hash( name.ns_id, consensus_hash ), given the sender and
block_id, and assuming that name.ns_id is already registered.
There are only a small number of values... | [
"def",
"get_name_from_name_consensus_hash",
"(",
"self",
",",
"name_consensus_hash",
",",
"sender_script_pubkey",
",",
"block_id",
")",
":",
"import",
"virtualchain_hooks",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"names",
"=",
"namedb_get_names_by_se... | 45.421053 | 0.014748 |
def __compute_edges_nd(label_image):
"""
Computes the region neighbourhood defined by a star shaped n-dimensional structuring
element (as returned by scipy.ndimage.generate_binary_structure(ndim, 1)) for the
supplied region/label image.
Note The returned set contains neither duplicates, nor self-ref... | [
"def",
"__compute_edges_nd",
"(",
"label_image",
")",
":",
"Er",
"=",
"set",
"(",
")",
"def",
"append",
"(",
"v1",
",",
"v2",
")",
":",
"if",
"v1",
"!=",
"v2",
":",
"Er",
".",
"update",
"(",
"[",
"(",
"min",
"(",
"v1",
",",
"v2",
")",
",",
"m... | 37.178571 | 0.008427 |
def services(self):
"Returns a list of Service objects available in this folder"
return [self._get_subfolder("%s/%s/" %
(s['name'].rstrip('/').split('/')[-1], s['type']),
self._service_type_mapping.get(s['type'], Service)) for s
in self._json_struct.get(... | [
"def",
"services",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_get_subfolder",
"(",
"\"%s/%s/\"",
"%",
"(",
"s",
"[",
"'name'",
"]",
".",
"rstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
",",
"s",
"[",
"'ty... | 55.166667 | 0.011905 |
def _write_images(self, iteration:int)->None:
"Writes model generated, original and real images to Tensorboard."
trainer = self.learn.gan_trainer
#TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way?
gen_mode = trainer.g... | [
"def",
"_write_images",
"(",
"self",
",",
"iteration",
":",
"int",
")",
"->",
"None",
":",
"trainer",
"=",
"self",
".",
"learn",
".",
"gan_trainer",
"#TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way?",
"g... | 61.1 | 0.017742 |
def FindSolFile(shot=0, t=0, Dt=None, Mesh='Rough1', Deg=2, Deriv='D2N2', Sep=True, Pos=True, OutPath='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/src/Outputs_AUG/'):
""" Identify the good Sol2D saved file in a given folder (OutPath), based on key ToFu criteria
When trying to load a Sol2D object (i.e.: s... | [
"def",
"FindSolFile",
"(",
"shot",
"=",
"0",
",",
"t",
"=",
"0",
",",
"Dt",
"=",
"None",
",",
"Mesh",
"=",
"'Rough1'",
",",
"Deg",
"=",
"2",
",",
"Deriv",
"=",
"'D2N2'",
",",
"Sep",
"=",
"True",
",",
"Pos",
"=",
"True",
",",
"OutPath",
"=",
"... | 50.714286 | 0.009326 |
def dca(x, f, g, niter, callback=None):
r"""Subgradient DCA of Tao and An.
This algorithm solves a problem of the form ::
min_x f(x) - g(x),
where ``f`` and ``g`` are proper, convex and lower semicontinuous
functions.
Parameters
----------
x : `LinearSpaceElement`
Initial... | [
"def",
"dca",
"(",
"x",
",",
"f",
",",
"g",
",",
"niter",
",",
"callback",
"=",
"None",
")",
":",
"space",
"=",
"f",
".",
"domain",
"if",
"g",
".",
"domain",
"!=",
"space",
":",
"raise",
"ValueError",
"(",
"'`f.domain` and `g.domain` need to be equal, bu... | 30.32 | 0.000426 |
def allconcat_ring(xs, devices, concat_axis):
"""Concatenate all Tensors everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of n strings
concat_axis: an integer
Returns:
a list of n Tensors
"""
n = len(xs)
if n == 1:
return xs
... | [
"def",
"allconcat_ring",
"(",
"xs",
",",
"devices",
",",
"concat_axis",
")",
":",
"n",
"=",
"len",
"(",
"xs",
")",
"if",
"n",
"==",
"1",
":",
"return",
"xs",
"# [target, source]",
"parts",
"=",
"[",
"[",
"xs",
"[",
"target",
"]",
"if",
"target",
"=... | 32.166667 | 0.014085 |
def play_bootstrap_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays a Bootstrap tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]);
// Initialize the tour
... | [
"def",
"play_bootstrap_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"in... | 34.409639 | 0.00034 |
def opt_width(self, width):
""" Set width of output ('auto' will auto-detect terminal width) """
if width != "auto":
width = int(width)
self.conf["width"] = width | [
"def",
"opt_width",
"(",
"self",
",",
"width",
")",
":",
"if",
"width",
"!=",
"\"auto\"",
":",
"width",
"=",
"int",
"(",
"width",
")",
"self",
".",
"conf",
"[",
"\"width\"",
"]",
"=",
"width"
] | 38.8 | 0.010101 |
def is_valid(self):
"""returns `True` if the report should be sent."""
if not self.total:
return False
if not self.contributor.freelanceprofile.is_freelance:
return False
return True | [
"def",
"is_valid",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"total",
":",
"return",
"False",
"if",
"not",
"self",
".",
"contributor",
".",
"freelanceprofile",
".",
"is_freelance",
":",
"return",
"False",
"return",
"True"
] | 33.142857 | 0.008403 |
def compute_eigh(self):
"""
Compute the two horizontal eigenvalues of the tensor (eigh1, and
eigh2), as well as the combined maximum absolute value of the two
(eighh).
"""
self.eigh1 = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
... | [
"def",
"compute_eigh",
"(",
"self",
")",
":",
"self",
".",
"eigh1",
"=",
"_SHGrid",
".",
"from_array",
"(",
"_np",
".",
"zeros_like",
"(",
"self",
".",
"vxx",
".",
"data",
")",
",",
"grid",
"=",
"'DH'",
")",
"self",
".",
"eigh2",
"=",
"_SHGrid",
".... | 39.62069 | 0.001699 |
def runtime_from_date(start_date, years, months, days, seconds, caltype):
"""
Get the number of seconds from start date to start date + date_delta.
Ignores Feb 29 for caltype == NOLEAP.
"""
end_date = start_date + relativedelta(years=years, months=months,
... | [
"def",
"runtime_from_date",
"(",
"start_date",
",",
"years",
",",
"months",
",",
"days",
",",
"seconds",
",",
"caltype",
")",
":",
"end_date",
"=",
"start_date",
"+",
"relativedelta",
"(",
"years",
"=",
"years",
",",
"months",
"=",
"months",
",",
"days",
... | 32.266667 | 0.002008 |
def uri(self, value):
"""Set new uri value in record.
It will not change the location of the underlying file!
"""
jsonpointer.set_pointer(self.record, self.pointer, value) | [
"def",
"uri",
"(",
"self",
",",
"value",
")",
":",
"jsonpointer",
".",
"set_pointer",
"(",
"self",
".",
"record",
",",
"self",
".",
"pointer",
",",
"value",
")"
] | 33.166667 | 0.009804 |
def load_allconfig(kconf, filename):
"""
Helper for all*config. Loads (merges) the configuration file specified by
KCONFIG_ALLCONFIG, if any. See Documentation/kbuild/kconfig.txt in the
Linux kernel.
Disables warnings for duplicated assignments within configuration files for
the duration of the... | [
"def",
"load_allconfig",
"(",
"kconf",
",",
"filename",
")",
":",
"def",
"std_msg",
"(",
"e",
")",
":",
"# \"Upcasts\" a _KconfigIOError to an IOError, removing the custom",
"# __str__() message. The standard message is better here.",
"return",
"IOError",
"(",
"e",
".",
"er... | 39.222222 | 0.000461 |
def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(
description='Makes UCL PHAS results better')
parser.add_argument('--input', '-i',
type=str, help="csv file to import")
parser.add_argument('--f... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Makes UCL PHAS results better'",
")",
... | 42.352941 | 0.002037 |
def fetch_request_token(self, url, realm=None, **request_kwargs):
r"""Fetch a request token.
This is the first step in the OAuth 1 workflow. A request token is
obtained by making a signed post request to url. The token is then
parsed from the application/x-www-form-urlencoded response a... | [
"def",
"fetch_request_token",
"(",
"self",
",",
"url",
",",
"realm",
"=",
"None",
",",
"*",
"*",
"request_kwargs",
")",
":",
"self",
".",
"_client",
".",
"client",
".",
"realm",
"=",
"\" \"",
".",
"join",
"(",
"realm",
")",
"if",
"realm",
"else",
"No... | 46.15625 | 0.001989 |
def signature(self, node, frame, extra_kwargs=None):
"""Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments shou... | [
"def",
"signature",
"(",
"self",
",",
"node",
",",
"frame",
",",
"extra_kwargs",
"=",
"None",
")",
":",
"# if any of the given keyword arguments is a python keyword",
"# we have to make sure that no invalid call is created.",
"kwarg_workaround",
"=",
"False",
"for",
"kwarg",
... | 38.211538 | 0.000981 |
def tabulate(g, ncol=1, headers=True, offset='', ndecimal=None):
""" Tabulate contents of an array or dictionary of |GVar|\s.
Given an array ``g`` of |GVar|\s or a dictionary whose values are
|GVar|\s or arrays of |GVar|\s, ``gvar.tabulate(g)`` returns a
string containing a table of the values of ``g``... | [
"def",
"tabulate",
"(",
"g",
",",
"ncol",
"=",
"1",
",",
"headers",
"=",
"True",
",",
"offset",
"=",
"''",
",",
"ndecimal",
"=",
"None",
")",
":",
"entries",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"g",
",",
"'keys'",
")",
":",
"if",
"headers",
"i... | 40.016667 | 0.001626 |
def _spec_trace(trace, cmap=None, wlen=0.4, log=False, trc='k',
tralpha=0.9, size=(10, 2.5), axes=None, title=None):
"""
Function to plot a trace over that traces spectrogram.
Uses obspys spectrogram routine.
:type trace: obspy.core.trace.Trace
:param trace: trace to plot
:type... | [
"def",
"_spec_trace",
"(",
"trace",
",",
"cmap",
"=",
"None",
",",
"wlen",
"=",
"0.4",
",",
"log",
"=",
"False",
",",
"trc",
"=",
"'k'",
",",
"tralpha",
"=",
"0.9",
",",
"size",
"=",
"(",
"10",
",",
"2.5",
")",
",",
"axes",
"=",
"None",
",",
... | 34.54902 | 0.000552 |
def semilocal_linear_trend_transition_matrix(autoregressive_coef):
"""Build the transition matrix for a semi-local linear trend model."""
# We want to write the following 2 x 2 matrix:
# [[1., 1., ], # level(t+1) = level(t) + slope(t)
# [0., ar_coef], # slope(t+1) = ar_coef * slope(t)
# but it's slightl... | [
"def",
"semilocal_linear_trend_transition_matrix",
"(",
"autoregressive_coef",
")",
":",
"# We want to write the following 2 x 2 matrix:",
"# [[1., 1., ], # level(t+1) = level(t) + slope(t)",
"# [0., ar_coef], # slope(t+1) = ar_coef * slope(t)",
"# but it's slightly tricky to properly incorp... | 50.478261 | 0.01268 |
def normalized(self):
'归一化'
res = self.groupby('code').apply(lambda x: x / x.iloc[0])
return res | [
"def",
"normalized",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"groupby",
"(",
"'code'",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
"/",
"x",
".",
"iloc",
"[",
"0",
"]",
")",
"return",
"res"
] | 29.25 | 0.016667 |
def make_qscan_plot(workflow, ifo, trig_time, out_dir, injection_file=None,
data_segments=None, time_window=100, tags=None):
""" Generate a make_qscan node and add it to workflow.
This function generates a single node of the singles_timefreq executable
and adds it to the current workflo... | [
"def",
"make_qscan_plot",
"(",
"workflow",
",",
"ifo",
",",
"trig_time",
",",
"out_dir",
",",
"injection_file",
"=",
"None",
",",
"data_segments",
"=",
"None",
",",
"time_window",
"=",
"100",
",",
"tags",
"=",
"None",
")",
":",
"tags",
"=",
"[",
"]",
"... | 43.869565 | 0.000727 |
def cursor_position(self, line=None, column=None):
"""Set the cursor to a specific `line` and `column`.
Cursor is allowed to move out of the scrolling region only when
:data:`~pyte.modes.DECOM` is reset, otherwise -- the position
doesn't change.
:param int line: line number to ... | [
"def",
"cursor_position",
"(",
"self",
",",
"line",
"=",
"None",
",",
"column",
"=",
"None",
")",
":",
"column",
"=",
"(",
"column",
"or",
"1",
")",
"-",
"1",
"line",
"=",
"(",
"line",
"or",
"1",
")",
"-",
"1",
"# If origin mode (DECOM) is set, line nu... | 36.461538 | 0.002055 |
def version():
"""Output version of gcdt tools and plugins."""
log.info('gcdt version %s' % __version__)
tools = get_plugin_versions('gcdttool10')
if tools:
log.info('gcdt tools:')
for p, v in tools.items():
log.info(' * %s version %s' % (p, v))
log.info('gcdt plugins:')
... | [
"def",
"version",
"(",
")",
":",
"log",
".",
"info",
"(",
"'gcdt version %s'",
"%",
"__version__",
")",
"tools",
"=",
"get_plugin_versions",
"(",
"'gcdttool10'",
")",
"if",
"tools",
":",
"log",
".",
"info",
"(",
"'gcdt tools:'",
")",
"for",
"p",
",",
"v"... | 37.8125 | 0.001613 |
def request(http, uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Make an HTTP request with an HTTP object and arguments.
Args:
http: httplib2.Http, an http object to be used to make requests.
uri: string... | [
"def",
"request",
"(",
"http",
",",
"uri",
",",
"method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"redirections",
"=",
"httplib2",
".",
"DEFAULT_MAX_REDIRECTS",
",",
"connection_type",
"=",
"None",
")",
":",
"# NOTE: Allow... | 48.758621 | 0.000693 |
def get_modules() -> Mapping:
"""Get all Bio2BEL modules."""
modules = {}
for entry_point in iter_entry_points(group='bio2bel', name=None):
entry = entry_point.name
try:
modules[entry] = entry_point.load()
except VersionConflict as exc:
log.warning('Version ... | [
"def",
"get_modules",
"(",
")",
"->",
"Mapping",
":",
"modules",
"=",
"{",
"}",
"for",
"entry_point",
"in",
"iter_entry_points",
"(",
"group",
"=",
"'bio2bel'",
",",
"name",
"=",
"None",
")",
":",
"entry",
"=",
"entry_point",
".",
"name",
"try",
":",
"... | 31.3 | 0.00155 |
def print_table(self, stream=sys.stdout, filter_function=None):
"""
A pretty ASCII printer for the periodic table, based on some filter_function.
Args:
stream: file-like object
filter_function:
A filtering function that take a Pseudo as input and returns ... | [
"def",
"print_table",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"filter_function",
"=",
"None",
")",
":",
"print",
"(",
"self",
".",
"to_table",
"(",
"filter_function",
"=",
"filter_function",
")",
",",
"file",
"=",
"stream",
")"
] | 47.25 | 0.008651 |
def applyByNode(requestContext, seriesList, nodeNum, templateFunction,
newName=None):
"""
Takes a seriesList and applies some complicated function (described by
a string), replacing templates with unique prefixes of keys from the
seriesList (the key is all nodes up to the index given as ... | [
"def",
"applyByNode",
"(",
"requestContext",
",",
"seriesList",
",",
"nodeNum",
",",
"templateFunction",
",",
"newName",
"=",
"None",
")",
":",
"from",
".",
"app",
"import",
"evaluateTarget",
"prefixes",
"=",
"set",
"(",
")",
"for",
"series",
"in",
"seriesLi... | 40.486486 | 0.000652 |
def write_segment(buff, segment, ver, ver_range, eci=False):
"""\
Writes a segment.
:param buff: The byte buffer.
:param _Segment segment: The segment to serialize.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param ver_rang... | [
"def",
"write_segment",
"(",
"buff",
",",
"segment",
",",
"ver",
",",
"ver_range",
",",
"eci",
"=",
"False",
")",
":",
"mode",
"=",
"segment",
".",
"mode",
"append_bits",
"=",
"buff",
".",
"append_bits",
"# Write ECI header if requested",
"if",
"eci",
"and",... | 43.192308 | 0.001742 |
def _extract_hunt_results(self, output_file_path):
"""Open a hunt output archive and extract files.
Args:
output_file_path: The path where the hunt archive is downloaded to.
Returns:
list: tuples containing:
str: The name of the client from where the files were downloaded.
... | [
"def",
"_extract_hunt_results",
"(",
"self",
",",
"output_file_path",
")",
":",
"# Extract items from archive by host for processing",
"collection_paths",
"=",
"[",
"]",
"client_ids",
"=",
"set",
"(",
")",
"client_id_to_fqdn",
"=",
"{",
"}",
"hunt_dir",
"=",
"None",
... | 35.364865 | 0.009665 |
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 | 0.002075 |
def login_server(self):
"""
Login to server
"""
local('ssh -i {0} {1}@{2}'.format(
env.key_filename, env.user, env.host_string
)) | [
"def",
"login_server",
"(",
"self",
")",
":",
"local",
"(",
"'ssh -i {0} {1}@{2}'",
".",
"format",
"(",
"env",
".",
"key_filename",
",",
"env",
".",
"user",
",",
"env",
".",
"host_string",
")",
")"
] | 25 | 0.01105 |
def cast_to_a1_notation(method):
"""
Decorator function casts wrapped arguments to A1 notation
in range method calls.
"""
@wraps(method)
def wrapper(self, *args, **kwargs):
try:
if len(args):
int(args[0])
# Convert to A1 notation
range... | [
"def",
"cast_to_a1_notation",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"len",
"(",
"args",
")",
":",
"int",
"(",
"args",
"[",
... | 25.826087 | 0.001623 |
def make_snapshot_from_ops_hash( cls, record_root_hash, prev_consensus_hashes ):
"""
Generate the consensus hash from the hash over the current ops, and
all previous required consensus hashes.
"""
# mix into previous consensus hashes...
all_hashes = prev_consensus_hashes... | [
"def",
"make_snapshot_from_ops_hash",
"(",
"cls",
",",
"record_root_hash",
",",
"prev_consensus_hashes",
")",
":",
"# mix into previous consensus hashes...",
"all_hashes",
"=",
"prev_consensus_hashes",
"[",
":",
"]",
"+",
"[",
"record_root_hash",
"]",
"all_hashes",
".",
... | 44 | 0.017123 |
def shell_context_processor(self, fn):
"""
Registers a shell context processor function.
"""
self._defer(lambda app: app.shell_context_processor(fn))
return fn | [
"def",
"shell_context_processor",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"shell_context_processor",
"(",
"fn",
")",
")",
"return",
"fn"
] | 32.333333 | 0.01005 |
def close(self):
"""
Close the current |stream|.
"""
if self.stream is None:
return
try:
self.stream.isatty()
if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]:
return
except AttributeError:
pass
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
"is",
"None",
":",
"return",
"try",
":",
"self",
".",
"stream",
".",
"isatty",
"(",
")",
"if",
"self",
".",
"stream",
".",
"name",
"in",
"[",
"\"<stdin>\"",
",",
"\"<stdout>\"",
",... | 26.347826 | 0.002387 |
async def store_their_did(wallet_handle: int,
identity_json: str) -> None:
"""
Saves their DID for a pairwise connection in a secured Wallet,
so that it can be used to verify transaction.
:param wallet_handle: wallet handler (created by open_wallet).
:param identity_json: ... | [
"async",
"def",
"store_their_did",
"(",
"wallet_handle",
":",
"int",
",",
"identity_json",
":",
"str",
")",
"->",
"None",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"store_their_did: >>> wallet_handle: %... | 37.388889 | 0.001448 |
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
"""
if arg is not None:
return formatter(value, filter_name=arg)
return formatter(value) | [
"def",
"apply_markup",
"(",
"value",
",",
"arg",
"=",
"None",
")",
":",
"if",
"arg",
"is",
"not",
"None",
":",
"return",
"formatter",
"(",
"value",
",",
"filter_name",
"=",
"arg",
")",
"return",
"formatter",
"(",
"value",
")"
] | 26 | 0.011152 |
def sample_from_posterior(self, A: pd.DataFrame) -> None:
""" Run Bayesian inference - sample from the posterior distribution."""
self.sample_from_proposal(A)
self.set_latent_state_sequence(A)
self.update_log_prior(A)
self.update_log_likelihood()
candidate_log_joint_prob... | [
"def",
"sample_from_posterior",
"(",
"self",
",",
"A",
":",
"pd",
".",
"DataFrame",
")",
"->",
"None",
":",
"self",
".",
"sample_from_proposal",
"(",
"A",
")",
"self",
".",
"set_latent_state_sequence",
"(",
"A",
")",
"self",
".",
"update_log_prior",
"(",
"... | 41.272727 | 0.002153 |
def _unpackb3(s, **options):
"""
Deserialize MessagePack bytes into a Python object.
Args:
s: a 'bytes' or 'bytearray' containing serialized MessagePack bytes
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext
type to a callable th... | [
"def",
"_unpackb3",
"(",
"s",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"packed data must be type 'bytes' or 'bytearray'\"",
")",
"return",
"_unpa... | 41.6 | 0.000522 |
def to_hdf(self, place, name):
'IO --> hdf5'
self.data.to_hdf(place, name)
return place, name | [
"def",
"to_hdf",
"(",
"self",
",",
"place",
",",
"name",
")",
":",
"self",
".",
"data",
".",
"to_hdf",
"(",
"place",
",",
"name",
")",
"return",
"place",
",",
"name"
] | 28.5 | 0.017094 |
def download(name, filenames):
'''
Download a file from the virtual folder to the current working directory.
The files with the same names will be overwirtten.
\b
NAME: Name of a virtual folder.
FILENAMES: Paths of the files to be uploaded.
'''
with Session() as session:
try:
... | [
"def",
"download",
"(",
"name",
",",
"filenames",
")",
":",
"with",
"Session",
"(",
")",
"as",
"session",
":",
"try",
":",
"session",
".",
"VFolder",
"(",
"name",
")",
".",
"download",
"(",
"filenames",
",",
"show_progress",
"=",
"True",
")",
"print_do... | 30.625 | 0.00198 |
def __extract_directory(self, path, files, destination):
"""Extracts a single directory to the specified directory on disk.
Args:
path (str):
Relative (to the root of the archive) path of the directory
to extract.
files (dict):
A ... | [
"def",
"__extract_directory",
"(",
"self",
",",
"path",
",",
"files",
",",
"destination",
")",
":",
"# assures the destination directory exists",
"destination_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"path",
")",
"if",
"not",
"os",
... | 31.8 | 0.001744 |
def update_menu(self):
"""Update context menu"""
self.menu.clear()
add_actions(self.menu, self.create_context_menu_actions()) | [
"def",
"update_menu",
"(",
"self",
")",
":",
"self",
".",
"menu",
".",
"clear",
"(",
")",
"add_actions",
"(",
"self",
".",
"menu",
",",
"self",
".",
"create_context_menu_actions",
"(",
")",
")"
] | 37.25 | 0.013158 |
def legacy_learning_rate_schedule(hparams):
"""Backwards-compatible learning-rate schedule."""
step_num = _global_step(hparams)
warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps)
if hparams.learning_rate_decay_scheme == "noam":
ret = 5000.0 * hparams.hidden_size**-0.5 * tf.minimum(
(step... | [
"def",
"legacy_learning_rate_schedule",
"(",
"hparams",
")",
":",
"step_num",
"=",
"_global_step",
"(",
"hparams",
")",
"warmup_steps",
"=",
"tf",
".",
"to_float",
"(",
"hparams",
".",
"learning_rate_warmup_steps",
")",
"if",
"hparams",
".",
"learning_rate_decay_sch... | 53.333333 | 0.011057 |
def source_decode(sourcecode, verbose=0):
"""Decode operator source and import operator class.
Parameters
----------
sourcecode: string
a string of operator source (e.g 'sklearn.feature_selection.RFE')
verbose: int, optional (default: 0)
How much information TPOT communicates while ... | [
"def",
"source_decode",
"(",
"sourcecode",
",",
"verbose",
"=",
"0",
")",
":",
"tmp_path",
"=",
"sourcecode",
".",
"split",
"(",
"'.'",
")",
"op_str",
"=",
"tmp_path",
".",
"pop",
"(",
")",
"import_str",
"=",
"'.'",
".",
"join",
"(",
"tmp_path",
")",
... | 32.875 | 0.002216 |
def projection(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5)):
"""Optical path difference projection of a dielectric sphere
Parameters
----------
radius: float
Radius of the sphere [... | [
"def",
"projection",
"(",
"radius",
"=",
"5e-6",
",",
"sphere_index",
"=",
"1.339",
",",
"medium_index",
"=",
"1.333",
",",
"wavelength",
"=",
"550e-9",
",",
"pixel_size",
"=",
"1e-7",
",",
"grid_size",
"=",
"(",
"80",
",",
"80",
")",
",",
"center",
"=... | 32.568627 | 0.000584 |
def choose_location_ids(gtfs, stop_ids=None):
"""Chooses a set of location ids (stations and their children) for
rendering a pathway graph.
If stop_ids is None, then all stations that have pathways are chosen.
If stop_ids is not None, then the station with this stop_id (or
with a child with this s... | [
"def",
"choose_location_ids",
"(",
"gtfs",
",",
"stop_ids",
"=",
"None",
")",
":",
"if",
"not",
"stop_ids",
":",
"# Select locations that are involved in pathway graph.",
"return",
"[",
"location",
".",
"gtfs_id",
"for",
"location",
"in",
"gtfs",
".",
"locations",
... | 38.361111 | 0.000706 |
def __generate(results):
"""
Static method which generates the Junit xml string from results
:param results: Results as ResultList object.
:return: Junit xml format string.
"""
doc, tag, text = Doc().tagtext()
# Counters for testsuite tag info
count = 0
... | [
"def",
"__generate",
"(",
"results",
")",
":",
"doc",
",",
"tag",
",",
"text",
"=",
"Doc",
"(",
")",
".",
"tagtext",
"(",
")",
"# Counters for testsuite tag info",
"count",
"=",
"0",
"fails",
"=",
"0",
"errors",
"=",
"0",
"skips",
"=",
"0",
"for",
"r... | 36.938462 | 0.002028 |
def clear(self):
"""
Remove all cache entries.
"""
db = sqlite3.connect(self.path)
c = db.cursor()
c.execute("DELETE FROM dirhashcache")
db.commit()
db.close() | [
"def",
"clear",
"(",
"self",
")",
":",
"db",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"path",
")",
"c",
"=",
"db",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"DELETE FROM dirhashcache\"",
")",
"db",
".",
"commit",
"(",
")",
"db",... | 23.888889 | 0.008969 |
def _initialize_pop(self, pop_size):
"""Assigns indices to individuals in population."""
self.toolbox.register("individual", self._generate)
self.toolbox.register("population", tools.initRepeat,
list, self.toolbox.individual)
self.population = self.toolbox.p... | [
"def",
"_initialize_pop",
"(",
"self",
",",
"pop_size",
")",
":",
"self",
".",
"toolbox",
".",
"register",
"(",
"\"individual\"",
",",
"self",
".",
"_generate",
")",
"self",
".",
"toolbox",
".",
"register",
"(",
"\"population\"",
",",
"tools",
".",
"initRe... | 47.5 | 0.002294 |
def checkedItems( self ):
"""
Returns the checked items for this combobox.
:return [<str>, ..]
"""
if not self.isCheckable():
return []
return [nativestring(self.itemText(i)) for i in self.checkedIndexes()] | [
"def",
"checkedItems",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isCheckable",
"(",
")",
":",
"return",
"[",
"]",
"return",
"[",
"nativestring",
"(",
"self",
".",
"itemText",
"(",
"i",
")",
")",
"for",
"i",
"in",
"self",
".",
"checkedIndexes"... | 27.9 | 0.020833 |
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle'... | [
"def",
"evaluate_all",
"(",
"ctx",
",",
"model",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.evaluate_all'",
")",
"click",
".",
"echo",
"(",
"'Model: %s'",
"%",
"model",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_w... | 80.125 | 0.010023 |
def get_attribute(self, instance):
"""
Given the *outgoing* object instance, return the primitive value
that should be used for this field.
"""
try:
return get_attribute(instance, self.source_attrs)
except (KeyError, AttributeError) as exc:
if not ... | [
"def",
"get_attribute",
"(",
"self",
",",
"instance",
")",
":",
"try",
":",
"return",
"get_attribute",
"(",
"instance",
",",
"self",
".",
"source_attrs",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"exc",
":",
"if",
"not",
"self",
"... | 43.583333 | 0.001871 |
def getdict(self, key):
"""Convert a multi values header to a case-insensitive dict:
.. code-block:: python
>>> resp = Message({
... 'Response': 'Success',
... 'ChanVariable': [
... 'FROM_DID=', 'SIPURI=sip:42@10.10.10.1:4242'],
... | [
"def",
"getdict",
"(",
"self",
",",
"key",
")",
":",
"values",
"=",
"self",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"{0} must be a list. got {1}\"",
".",
"f... | 35.875 | 0.002262 |
def delete_backup(path, backup_id):
'''
.. versionadded:: 0.17.0
Delete a previous version of a file that was backed up using Salt's
:ref:`file state backup <file-state-backups>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the backup yo... | [
"def",
"delete_backup",
"(",
"path",
",",
"backup_id",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"ret",
"=",
"{",
"'result'",
":",
"False",
",",
"'comment'",
":",
"'Invalid backup_id \\'{0}\\''",
".",
"format",
"(",
"... | 31 | 0.00139 |
def getItem(self, index, altItem=None):
""" Returns the TreeItem for the given index. Returns the altItem if the index is invalid.
"""
if index.isValid():
item = index.internalPointer()
if item:
return item
#return altItem if altItem is not None e... | [
"def",
"getItem",
"(",
"self",
",",
"index",
",",
"altItem",
"=",
"None",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"item",
"=",
"index",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"return",
"item",
"#return altItem if altItem is ... | 37.5 | 0.013021 |
def load_wdhistory(self, workdir=None):
"""Load history from a text file in user home directory"""
if osp.isfile(self.LOG_PATH):
wdhistory, _ = encoding.readlines(self.LOG_PATH)
wdhistory = [name for name in wdhistory if os.path.isdir(name)]
else:
if wor... | [
"def",
"load_wdhistory",
"(",
"self",
",",
"workdir",
"=",
"None",
")",
":",
"if",
"osp",
".",
"isfile",
"(",
"self",
".",
"LOG_PATH",
")",
":",
"wdhistory",
",",
"_",
"=",
"encoding",
".",
"readlines",
"(",
"self",
".",
"LOG_PATH",
")",
"wdhistory",
... | 42.9 | 0.009132 |
def rewrite_stack_variables(self,
max_combined_variable_size=2 ** 30,
max_combined_slice_size=2 ** 27,
mesh_to_impl=None):
"""Rewrite the current graph to combine variables.
This helps speed up graph construction times in... | [
"def",
"rewrite_stack_variables",
"(",
"self",
",",
"max_combined_variable_size",
"=",
"2",
"**",
"30",
",",
"max_combined_slice_size",
"=",
"2",
"**",
"27",
",",
"mesh_to_impl",
"=",
"None",
")",
":",
"# pylint: disable=protected-access",
"all_variables",
"=",
"sel... | 44.068376 | 0.008725 |
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key... | [
"def",
"get_group_id",
"(",
"name",
",",
"vpc_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"reg... | 41.0625 | 0.001488 |
def cmd(send, msg, args):
"""Checks if a website is up.
Syntax: {command} <website>
"""
if not msg:
send("What are you trying to get to?")
return
nick = args['nick']
isup = get("http://isup.me/%s" % msg).text
if "looks down from here" in isup:
send("%s: %s is down" ... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"What are you trying to get to?\"",
")",
"return",
"nick",
"=",
"args",
"[",
"'nick'",
"]",
"isup",
"=",
"get",
"(",
"\"http://isup.me/%s\"",
"%",
"msg"... | 27.941176 | 0.002037 |
def is_alive(self):
"""
Test Function to check WHAT IF servers are up and running.
"""
u = urllib.urlopen("http://wiws.cmbi.ru.nl/rest/TestEmpty/id/1crn/")
x = xml.dom.minidom.parse(u)
self.alive = len(x.getElementsByTagName("TestEmptyResponse"))
return ... | [
"def",
"is_alive",
"(",
"self",
")",
":",
"u",
"=",
"urllib",
".",
"urlopen",
"(",
"\"http://wiws.cmbi.ru.nl/rest/TestEmpty/id/1crn/\"",
")",
"x",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parse",
"(",
"u",
")",
"self",
".",
"alive",
"=",
"len",
"(",... | 32.1 | 0.009091 |
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
... | [
"def",
"__dump_compose_file",
"(",
"path",
",",
"compose_result",
",",
"success_msg",
",",
"already_existed",
")",
":",
"ret",
"=",
"__dump_docker_compose",
"(",
"path",
",",
"compose_result",
"[",
"'compose_content'",
"]",
",",
"already_existed",
")",
"if",
"isin... | 36.125 | 0.001686 |
def yank_pop(event):
"""
Rotate the kill ring, and yank the new top. Only works following yank or
yank-pop.
"""
buff = event.current_buffer
doc_before_paste = buff.document_before_paste
clipboard = event.cli.clipboard
if doc_before_paste is not None:
buff.document = doc_before_p... | [
"def",
"yank_pop",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"doc_before_paste",
"=",
"buff",
".",
"document_before_paste",
"clipboard",
"=",
"event",
".",
"cli",
".",
"clipboard",
"if",
"doc_before_paste",
"is",
"not",
"None",
":",
... | 31.071429 | 0.002232 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.