text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def execute(helper, config, args):
"""
dump command dumps things
"""
env = parse_env_config(config, args.environment)
option_settings = env.get('option_settings', {})
settings = parse_option_settings(option_settings)
for setting in settings:
out(str(setting)) | [
"def",
"execute",
"(",
"helper",
",",
"config",
",",
"args",
")",
":",
"env",
"=",
"parse_env_config",
"(",
"config",
",",
"args",
".",
"environment",
")",
"option_settings",
"=",
"env",
".",
"get",
"(",
"'option_settings'",
",",
"{",
"}",
")",
"settings... | 31.888889 | 0.00339 |
def create(self, dataset_id):
""" Create a dataset in Google BigQuery
Parameters
----------
dataset : str
Name of dataset to be written
"""
from google.cloud.bigquery import Dataset
if self.exists(dataset_id):
raise DatasetCreationError(
... | [
"def",
"create",
"(",
"self",
",",
"dataset_id",
")",
":",
"from",
"google",
".",
"cloud",
".",
"bigquery",
"import",
"Dataset",
"if",
"self",
".",
"exists",
"(",
"dataset_id",
")",
":",
"raise",
"DatasetCreationError",
"(",
"\"Dataset {0} already \"",
"\"exis... | 27.541667 | 0.002924 |
def add_content(self, content):
"""
Add content to this fragment.
`content` is a Unicode string, HTML to append to the body of the
fragment. It must not contain a ``<body>`` tag, or otherwise assume
that it is the only content on the page.
"""
assert isinstance(... | [
"def",
"add_content",
"(",
"self",
",",
"content",
")",
":",
"assert",
"isinstance",
"(",
"content",
",",
"six",
".",
"text_type",
")",
"self",
".",
"content",
"+=",
"content"
] | 36.6 | 0.005333 |
def compute_score_threshold(average_window_readcount,
island_enriched_threshold,
gap_contribution, boundary_contribution,
genome_length_in_bins):
# type: (float, int, float, float, float) -> float
"""
What does island_expect... | [
"def",
"compute_score_threshold",
"(",
"average_window_readcount",
",",
"island_enriched_threshold",
",",
"gap_contribution",
",",
"boundary_contribution",
",",
"genome_length_in_bins",
")",
":",
"# type: (float, int, float, float, float) -> float",
"required_p_value",
"=",
"poisso... | 39.586207 | 0.000425 |
def show_xys(self, xs, ys)->None:
"Show the `xs` (inputs) and `ys` (targets)."
from IPython.display import display, HTML
items,names = [], xs[0].names + ['target']
for i, (x,y) in enumerate(zip(xs,ys)):
res = []
cats = x.cats if len(x.cats.size()) > 0 else []
... | [
"def",
"show_xys",
"(",
"self",
",",
"xs",
",",
"ys",
")",
"->",
"None",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
",",
"HTML",
"items",
",",
"names",
"=",
"[",
"]",
",",
"xs",
"[",
"0",
"]",
".",
"names",
"+",
"[",
"'target'",... | 48.375 | 0.012674 |
def do_thaw(client, args):
"""Execute the thaw operation, pulling in an actual Vault
client if neccesary"""
vault_client = None
if args.gpg_pass_path:
vault_client = client.connect(args)
aomi.filez.thaw(vault_client, args.icefile, args)
sys.exit(0) | [
"def",
"do_thaw",
"(",
"client",
",",
"args",
")",
":",
"vault_client",
"=",
"None",
"if",
"args",
".",
"gpg_pass_path",
":",
"vault_client",
"=",
"client",
".",
"connect",
"(",
"args",
")",
"aomi",
".",
"filez",
".",
"thaw",
"(",
"vault_client",
",",
... | 30.333333 | 0.003559 |
def periodogram(self):
"""An alias to :class:`~spectrum.periodogram.Periodogram`
The parameters are extracted from the attributes. Relevant attributes
ares :attr:`window`, attr:`sampling`, attr:`NFFT`, attr:`scale_by_freq`,
:attr:`detrend`.
.. plot::
:width: 80%
... | [
"def",
"periodogram",
"(",
"self",
")",
":",
"from",
".",
"periodogram",
"import",
"speriodogram",
"psd",
"=",
"speriodogram",
"(",
"self",
".",
"data",
",",
"window",
"=",
"self",
".",
"window",
",",
"sampling",
"=",
"self",
".",
"sampling",
",",
"NFFT"... | 38.136364 | 0.00814 |
def from_progression_shorthand(self, shorthand, key='C'):
"""Empty the container and add the notes described in the progressions
shorthand (eg. 'IIm6', 'V7', etc).
See mingus.core.progressions for all the recognized format.
Example:
>>> NoteContainer().from_progression_shorthan... | [
"def",
"from_progression_shorthand",
"(",
"self",
",",
"shorthand",
",",
"key",
"=",
"'C'",
")",
":",
"self",
".",
"empty",
"(",
")",
"chords",
"=",
"progressions",
".",
"to_chords",
"(",
"shorthand",
",",
"key",
")",
"# warning Throw error, not a valid shorthan... | 32 | 0.003195 |
def lines(start=None, end=None, reverse=False, selection=False):
"""Iterate lines in range.
Args:
start: Starting address, start of IDB if `None`.
end: End address, end of IDB if `None`.
reverse: Set to true to iterate in reverse order.
selection: If set to True, replaces start ... | [
"def",
"lines",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"selection",
"=",
"False",
")",
":",
"if",
"selection",
":",
"start",
",",
"end",
"=",
"get_selection",
"(",
")",
"else",
":",
"start",
",",
"end... | 28.931034 | 0.002307 |
def apply_filters(stopwords, language):
"""
Apply registered filters to stopwords
:param stopwords: list
:param language: string
:return: filtered stopwords
"""
if language in _filters:
for func in _filters[language]:
stopwords = func(stopwords)
for func in _filters[... | [
"def",
"apply_filters",
"(",
"stopwords",
",",
"language",
")",
":",
"if",
"language",
"in",
"_filters",
":",
"for",
"func",
"in",
"_filters",
"[",
"language",
"]",
":",
"stopwords",
"=",
"func",
"(",
"stopwords",
")",
"for",
"func",
"in",
"_filters",
"[... | 25.333333 | 0.002538 |
def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone):
"""
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_a... | [
"def",
"fast_group_adder",
"(",
"wires_to_add",
",",
"reducer",
"=",
"wallace_reducer",
",",
"final_adder",
"=",
"kogge_stone",
")",
":",
"import",
"math",
"longest_wire_len",
"=",
"max",
"(",
"len",
"(",
"w",
")",
"for",
"w",
"in",
"wires_to_add",
")",
"res... | 39.36 | 0.003968 |
def get_viewer(self, v_id, viewer_class=None, width=512, height=512,
force_new=False):
"""
Get an existing viewer by viewer id. If the viewer does not yet
exist, make a new one.
"""
if not force_new:
try:
return self.viewers[v_id]
... | [
"def",
"get_viewer",
"(",
"self",
",",
"v_id",
",",
"viewer_class",
"=",
"None",
",",
"width",
"=",
"512",
",",
"height",
"=",
"512",
",",
"force_new",
"=",
"False",
")",
":",
"if",
"not",
"force_new",
":",
"try",
":",
"return",
"self",
".",
"viewers... | 33.909091 | 0.003911 |
def find_library_darwin(cls):
"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in... | [
"def",
"find_library_darwin",
"(",
"cls",
")",
":",
"dll",
"=",
"Library",
".",
"JLINK_SDK_NAME",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'/'",
",",
"'Applications'",
",",
"'SEGGER'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
... | 43.021277 | 0.000967 |
def write_zip(file_path, data, properties):
"""
Write custom zip file to the file path
:param file_path: the file to which to write the zip file
:param data: the data to write to the file; may be None
:param properties: the properties to write to the file; may be None
The p... | [
"def",
"write_zip",
"(",
"file_path",
",",
"data",
",",
"properties",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"\"w+b\"",
")",
"as",
"fp",
":",
"write_zip_fp",
"(",
"fp",
",",
"data",
",",
"properties",
")"
] | 35.933333 | 0.001808 |
def global_request(self, kind, data=None, wait=True):
"""
Make a global request to the remote host. These are normally
extensions to the SSH2 protocol.
:param str kind: name of the request.
:param tuple data:
an optional tuple containing additional data to attach to... | [
"def",
"global_request",
"(",
"self",
",",
"kind",
",",
"data",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"wait",
":",
"self",
".",
"completion_event",
"=",
"threading",
".",
"Event",
"(",
")",
"m",
"=",
"Message",
"(",
")",
"m",
".",
... | 36.055556 | 0.0015 |
def validate(self, object):
"""Validate an object against the schema.
This function just passes if the schema matches the object.
If the object does not match the schema, a ValidationException is raised.
This error allows debugging.
"""
resolver=self.get_resolver()
... | [
"def",
"validate",
"(",
"self",
",",
"object",
")",
":",
"resolver",
"=",
"self",
".",
"get_resolver",
"(",
")",
"jsonschema",
".",
"validate",
"(",
"object",
",",
"self",
".",
"get_schema",
"(",
")",
",",
"resolver",
"=",
"resolver",
")"
] | 42.222222 | 0.010309 |
def add_toc_entry(self, title, level, slide_number):
""" Adds a new entry to current presentation Table of Contents.
"""
self.__toc.append({'title': title, 'number': slide_number,
'level': level}) | [
"def",
"add_toc_entry",
"(",
"self",
",",
"title",
",",
"level",
",",
"slide_number",
")",
":",
"self",
".",
"__toc",
".",
"append",
"(",
"{",
"'title'",
":",
"title",
",",
"'number'",
":",
"slide_number",
",",
"'level'",
":",
"level",
"}",
")"
] | 48.6 | 0.008097 |
def gcc_checker(code, filename_suffix, arguments, working_directory):
"""Return checker."""
run = run_in_subprocess(code,
filename_suffix,
arguments + ['-pedantic', '-fsyntax-only'],
working_directory=working_directory)
def... | [
"def",
"gcc_checker",
"(",
"code",
",",
"filename_suffix",
",",
"arguments",
",",
"working_directory",
")",
":",
"run",
"=",
"run_in_subprocess",
"(",
"code",
",",
"filename_suffix",
",",
"arguments",
"+",
"[",
"'-pedantic'",
",",
"'-fsyntax-only'",
"]",
",",
... | 35.65 | 0.001366 |
def create_cert_signed_certificate(self, sign_cert_str, sign_key_str,
request_cert_str, hash_alg="sha256",
valid_from=0, valid_to=315360000, sn=1,
passphrase=None):
"""
Will sign a certi... | [
"def",
"create_cert_signed_certificate",
"(",
"self",
",",
"sign_cert_str",
",",
"sign_key_str",
",",
"request_cert_str",
",",
"hash_alg",
"=",
"\"sha256\"",
",",
"valid_from",
"=",
"0",
",",
"valid_to",
"=",
"315360000",
",",
"sn",
"=",
"1",
",",
"passphrase",
... | 55.016667 | 0.001488 |
def add_item(self, host, key, value, clock=None, state=0):
"""
Add a single item into DataContainer
:host: hostname to which item will be linked to
:key: item key as defined in Zabbix
:value: item value
:clock: timestemp as integer. If not provided self.clock()) will be ... | [
"def",
"add_item",
"(",
"self",
",",
"host",
",",
"key",
",",
"value",
",",
"clock",
"=",
"None",
",",
"state",
"=",
"0",
")",
":",
"if",
"clock",
"is",
"None",
":",
"clock",
"=",
"self",
".",
"clock",
"if",
"self",
".",
"_config",
".",
"data_typ... | 43.272727 | 0.004111 |
def dedent(text):
"""Equivalent of textwrap.dedent that ignores unindented first line.
This means it will still dedent strings like:
'''foo
is a bar
'''
For use in wrap_paragraphs.
"""
if text.startswith('\n'):
# text starts with blank line, don't ignore the first line
... | [
"def",
"dedent",
"(",
"text",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"'\\n'",
")",
":",
"# text starts with blank line, don't ignore the first line",
"return",
"textwrap",
".",
"dedent",
"(",
"text",
")",
"# split first line",
"splits",
"=",
"text",
".",
... | 24.2 | 0.00318 |
def authenticate(org):
"""
Authenticate with GitHub via SSH if possible
Otherwise authenticate via HTTPS
Returns an authenticated User
"""
with ProgressBar(_("Authenticating")) as progress_bar:
user = _authenticate_ssh(org)
progress_bar.stop()
if user is None:
... | [
"def",
"authenticate",
"(",
"org",
")",
":",
"with",
"ProgressBar",
"(",
"_",
"(",
"\"Authenticating\"",
")",
")",
"as",
"progress_bar",
":",
"user",
"=",
"_authenticate_ssh",
"(",
"org",
")",
"progress_bar",
".",
"stop",
"(",
")",
"if",
"user",
"is",
"N... | 30.533333 | 0.002119 |
def saveWallet(self, wallet, fpath):
"""Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fp... | [
"def",
"saveWallet",
"(",
"self",
",",
"wallet",
",",
"fpath",
")",
":",
"if",
"not",
"fpath",
":",
"raise",
"ValueError",
"(",
"\"empty path\"",
")",
"_fpath",
"=",
"self",
".",
"_normalize",
"(",
"fpath",
")",
"_dpath",
"=",
"_fpath",
".",
"parent",
... | 34.181818 | 0.001293 |
def _apply_Create(self, change):
'''A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
'''
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_... | [
"def",
"_apply_Create",
"(",
"self",
",",
"change",
")",
":",
"ar",
"=",
"_AzureRecord",
"(",
"self",
".",
"_resource_group",
",",
"change",
".",
"new",
")",
"create",
"=",
"self",
".",
"_dns_client",
".",
"record_sets",
".",
"create_or_update",
"create",
... | 35.222222 | 0.003072 |
def catch_raise_api_exception():
"""Context manager that translates upstream API exceptions."""
try:
yield
except _ApiException as exc:
detail = None
fields = None
if exc.body:
try:
# pylint: disable=no-member
data = json.loads(exc... | [
"def",
"catch_raise_api_exception",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_ApiException",
"as",
"exc",
":",
"detail",
"=",
"None",
"fields",
"=",
"None",
"if",
"exc",
".",
"body",
":",
"try",
":",
"# pylint: disable=no-member",
"data",
"=",
"json",
... | 28.363636 | 0.003101 |
def smeft_evolve(C_in, scale_in, scale_out, newphys=True, **kwargs):
"""Solve the SMEFT RGEs by numeric integration.
Input C_in and output C_out are dictionaries of arrays."""
sol = _smeft_evolve(C_in, scale_in, scale_out, newphys=newphys, **kwargs)
return C_array2dict(sol.y[:, -1].view(complex)) | [
"def",
"smeft_evolve",
"(",
"C_in",
",",
"scale_in",
",",
"scale_out",
",",
"newphys",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"sol",
"=",
"_smeft_evolve",
"(",
"C_in",
",",
"scale_in",
",",
"scale_out",
",",
"newphys",
"=",
"newphys",
",",
"*"... | 51.5 | 0.003185 |
def set_sleep(minutes):
'''
Sets the amount of idle time until the machine sleeps. Sets the same value
for Computer, Display, and Hard Disk. Pass "Never" or "Off" for computers
that should never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
... | [
"def",
"set_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setsleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
... | 28.166667 | 0.001144 |
def load_child_sections_for_section(context, section, count=None):
'''
Returns all child sections
If the `locale_code` in the context is not the main language, it will
return the translations of the live articles.
'''
page = section.get_main_language_page()
locale = context.get('locale_code'... | [
"def",
"load_child_sections_for_section",
"(",
"context",
",",
"section",
",",
"count",
"=",
"None",
")",
":",
"page",
"=",
"section",
".",
"get_main_language_page",
"(",
")",
"locale",
"=",
"context",
".",
"get",
"(",
"'locale_code'",
")",
"qs",
"=",
"Secti... | 32.6 | 0.001988 |
def str_(name):
"""Return the string representation of the given 'name'.
If it is a bytes object, it will be converted into str.
If it is a str object, it will simply be resurned."""
if isinstance(name, bytes) and not isinstance(name, str):
return name.decode('utf8')
else:
return name | [
"def",
"str_",
"(",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"bytes",
")",
"and",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"return",
"name",
".",
"decode",
"(",
"'utf8'",
")",
"else",
":",
"return",
"name"
] | 37 | 0.013201 |
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[f... | [
"def",
"_file_lines",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"return",
"self",
".",
"_file_lines_cache",
"[",
"filename",
"]",
"except",
"KeyError",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"with",
"open",
"(... | 39 | 0.004175 |
def append(self, cb):
"""Adds a callback."""
self.callbacks.append(cb.callb)
self.monitor = self.monitor | cb.callb.bit
yield from self.pi._pigpio_aio_command(_PI_CMD_NB, self.handle,
self.monitor) | [
"def",
"append",
"(",
"self",
",",
"cb",
")",
":",
"self",
".",
"callbacks",
".",
"append",
"(",
"cb",
".",
"callb",
")",
"self",
".",
"monitor",
"=",
"self",
".",
"monitor",
"|",
"cb",
".",
"callb",
".",
"bit",
"yield",
"from",
"self",
".",
"pi"... | 38.714286 | 0.00722 |
def cli_parse(file_path, sa, nameservers, dns_timeout, parallel=False):
"""Separated this function for multiprocessing"""
try:
file_results = parse_report_file(file_path,
nameservers=nameservers,
dns_timeout=dns_timeout,
... | [
"def",
"cli_parse",
"(",
"file_path",
",",
"sa",
",",
"nameservers",
",",
"dns_timeout",
",",
"parallel",
"=",
"False",
")",
":",
"try",
":",
"file_results",
"=",
"parse_report_file",
"(",
"file_path",
",",
"nameservers",
"=",
"nameservers",
",",
"dns_timeout"... | 42.333333 | 0.001541 |
def render_to_response(self, context, **response_kwargs):
"""
Overloaded to deal with _format arguments.
"""
# should we actually render in json?
if '_format' in self.request.GET and self.request.GET['_format'] == 'json':
return JsonResponse(self.as_json(context), saf... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"# should we actually render in json?",
"if",
"'_format'",
"in",
"self",
".",
"request",
".",
"GET",
"and",
"self",
".",
"request",
".",
"GET",
"[",
"'_format... | 40 | 0.006667 |
def add_dashboard_panel(self, dashboard, name, panel_type, metrics, scope=None, sort_by=None, limit=None, layout=None):
"""**Description**
Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel.
**Arguments**
- **dashboard... | [
"def",
"add_dashboard_panel",
"(",
"self",
",",
"dashboard",
",",
"name",
",",
"panel_type",
",",
"metrics",
",",
"scope",
"=",
"None",
",",
"sort_by",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"layout",
"=",
"None",
")",
":",
"panel_configuration",
"... | 49.457143 | 0.00269 |
def _CheckType(value, check_type, name, allow_none=True):
"""Check that the type of an object is acceptable.
Args:
value: The object whose type is to be checked.
check_type: The type that the object must be an instance of.
name: Name of the object, to be placed in any error messages.
allow_none: Tr... | [
"def",
"_CheckType",
"(",
"value",
",",
"check_type",
",",
"name",
",",
"allow_none",
"=",
"True",
")",
":",
"if",
"value",
"is",
"None",
"and",
"allow_none",
":",
"return",
"if",
"not",
"isinstance",
"(",
"value",
",",
"check_type",
")",
":",
"raise",
... | 35.5 | 0.006861 |
def copies(self):
""" All test case copies created by the user """
import nitrate
if self._copies is None:
log.info(u"Searching for cases copied by {0}".format(self.user))
self._copies = [
case for case in nitrate.TestCase.search(
autho... | [
"def",
"copies",
"(",
"self",
")",
":",
"import",
"nitrate",
"if",
"self",
".",
"_copies",
"is",
"None",
":",
"log",
".",
"info",
"(",
"u\"Searching for cases copied by {0}\"",
".",
"format",
"(",
"self",
".",
"user",
")",
")",
"self",
".",
"_copies",
"=... | 44.583333 | 0.003663 |
def evaluateCommand(self, cmd):
""" cppcheck always return 0, unless a special parameter is given """
for msg in self.flunkingIssues:
if self.counts[msg] != 0:
return FAILURE
if self.getProperty('cppcheck-total') != 0:
return WARNINGS
return SUCCES... | [
"def",
"evaluateCommand",
"(",
"self",
",",
"cmd",
")",
":",
"for",
"msg",
"in",
"self",
".",
"flunkingIssues",
":",
"if",
"self",
".",
"counts",
"[",
"msg",
"]",
"!=",
"0",
":",
"return",
"FAILURE",
"if",
"self",
".",
"getProperty",
"(",
"'cppcheck-to... | 39.25 | 0.006231 |
def log_config(verbose: bool) -> dict:
"""
Setup default config. for dictConfig.
:param verbose: level: DEBUG if True, INFO if False
:return: dict suitable for ``logging.config.dictConfig``
"""
log_level = 'DEBUG' if verbose else 'INFO'
return {
'version': 1,
'disable_existin... | [
"def",
"log_config",
"(",
"verbose",
":",
"bool",
")",
"->",
"dict",
":",
"log_level",
"=",
"'DEBUG'",
"if",
"verbose",
"else",
"'INFO'",
"return",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
":",
"{",
... | 32.27027 | 0.000406 |
def format_citations(zid, url='https://zenodo.org/', hits=10, tag_prefix='v'):
"""Query and format a citations page from Zenodo entries
Parameters
----------
zid : `int`, `str`
the Zenodo ID of the target record
url : `str`, optional
the base URL of the Zenodo host, defaults to ``h... | [
"def",
"format_citations",
"(",
"zid",
",",
"url",
"=",
"'https://zenodo.org/'",
",",
"hits",
"=",
"10",
",",
"tag_prefix",
"=",
"'v'",
")",
":",
"# query for metadata",
"url",
"=",
"(",
"'{url}/api/records/?'",
"'page=1&'",
"'size={hits}&'",
"'q=conceptrecid:\"{id}... | 30.4 | 0.000708 |
def get_schemas(cls, schema_types=None, sort=True):
"""
Get schemas by type. If ``schema_type`` is None, return all schemas
:param schema_types: list of schema types
:type schema_types: list or None
:param bool sort: sort by name
:return: list of schemas
:rtype: ... | [
"def",
"get_schemas",
"(",
"cls",
",",
"schema_types",
"=",
"None",
",",
"sort",
"=",
"True",
")",
":",
"result",
"=",
"filter",
"(",
"lambda",
"x",
":",
"not",
"x",
".",
"is_inline_array",
",",
"cls",
".",
"_schemas",
".",
"values",
"(",
")",
")",
... | 37.625 | 0.003241 |
def p_class_name(p):
'''class_name : namespace_name
| NS_SEPARATOR namespace_name
| NAMESPACE NS_SEPARATOR namespace_name'''
if len(p) == 2:
p[0] = p[1]
elif len(p) == 3:
p[0] = p[1] + p[2]
else:
p[0] = p[1] + p[2] + p[3] | [
"def",
"p_class_name",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"elif",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"p",
... | 28.8 | 0.003367 |
def sigStrToKwArgsDict(checkFuncSig):
""" Take a check function signature (string), and parse it to get a dict
of the keyword args and their values. """
p1 = checkFuncSig.find('(')
p2 = checkFuncSig.rfind(')')
assert p1 > 0 and p2 > 0 and p2 > p1, "Invalid signature: "+checkFuncSig
argParts ... | [
"def",
"sigStrToKwArgsDict",
"(",
"checkFuncSig",
")",
":",
"p1",
"=",
"checkFuncSig",
".",
"find",
"(",
"'('",
")",
"p2",
"=",
"checkFuncSig",
".",
"rfind",
"(",
"')'",
")",
"assert",
"p1",
">",
"0",
"and",
"p2",
">",
"0",
"and",
"p2",
">",
"p1",
... | 46.956522 | 0.008167 |
def media_new_callbacks(self, open_cb, read_cb, seek_cb, close_cb, opaque):
'''Create a media with custom callbacks to read the data from.
@param open_cb: callback to open the custom bitstream input media.
@param read_cb: callback to read data (must not be NULL).
@param seek_cb: callback... | [
"def",
"media_new_callbacks",
"(",
"self",
",",
"open_cb",
",",
"read_cb",
",",
"seek_cb",
",",
"close_cb",
",",
"opaque",
")",
":",
"return",
"libvlc_media_new_callbacks",
"(",
"self",
",",
"open_cb",
",",
"read_cb",
",",
"seek_cb",
",",
"close_cb",
",",
"o... | 108.272727 | 0.003331 |
def _load_pretrained_tok2vec(nlp, loc):
"""Load pre-trained weights for the 'token-to-vector' part of the component
models, which is typically a CNN. See 'spacy pretrain'. Experimental.
"""
with loc.open("rb") as file_:
weights_data = file_.read()
loaded = []
for name, component in nlp.p... | [
"def",
"_load_pretrained_tok2vec",
"(",
"nlp",
",",
"loc",
")",
":",
"with",
"loc",
".",
"open",
"(",
"\"rb\"",
")",
"as",
"file_",
":",
"weights_data",
"=",
"file_",
".",
"read",
"(",
")",
"loaded",
"=",
"[",
"]",
"for",
"name",
",",
"component",
"i... | 41.833333 | 0.001949 |
def ensure_mingw_drive(win32_path):
r""" replaces windows drives with mingw style drives
Args:
win32_path (str):
CommandLine:
python -m utool.util_path --test-ensure_mingw_drive
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> win32_... | [
"def",
"ensure_mingw_drive",
"(",
"win32_path",
")",
":",
"win32_drive",
",",
"_path",
"=",
"splitdrive",
"(",
"win32_path",
")",
"mingw_drive",
"=",
"'/'",
"+",
"win32_drive",
"[",
":",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"mingw_path",
"=",
"mingw_driv... | 28.904762 | 0.001595 |
def OnClose(self, event):
"""Program exit event handler"""
# If changes have taken place save of old grid
if undo.stack().haschanged():
save_choice = self.interfaces.get_save_request_from_user()
if save_choice is None:
# Cancelled close operation
... | [
"def",
"OnClose",
"(",
"self",
",",
"event",
")",
":",
"# If changes have taken place save of old grid",
"if",
"undo",
".",
"stack",
"(",
")",
".",
"haschanged",
"(",
")",
":",
"save_choice",
"=",
"self",
".",
"interfaces",
".",
"get_save_request_from_user",
"("... | 28.175 | 0.001715 |
def n_neurites(neurites, neurite_type=NeuriteType.all):
'''Number of neurites in a collection of neurites'''
return sum(1 for _ in iter_neurites(neurites, filt=is_type(neurite_type))) | [
"def",
"n_neurites",
"(",
"neurites",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"return",
"sum",
"(",
"1",
"for",
"_",
"in",
"iter_neurites",
"(",
"neurites",
",",
"filt",
"=",
"is_type",
"(",
"neurite_type",
")",
")",
")"
] | 63 | 0.005236 |
def device_type_from_string(cl_device_type_str):
"""Converts values like ``gpu`` to a pyopencl device type string.
Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned.
Args:
cl_device_type_str (str): The string we want to convert to a device t... | [
"def",
"device_type_from_string",
"(",
"cl_device_type_str",
")",
":",
"cl_device_type_str",
"=",
"cl_device_type_str",
".",
"upper",
"(",
")",
"if",
"hasattr",
"(",
"cl",
".",
"device_type",
",",
"cl_device_type_str",
")",
":",
"return",
"getattr",
"(",
"cl",
"... | 37.4 | 0.005217 |
def new_geom(geom_type, size, pos=(0, 0, 0), rgba=RED, group=0, **kwargs):
"""
Creates a geom element with attributes specified by @**kwargs.
Args:
geom_type (str): type of the geom.
see all types here: http://mujoco.org/book/modeling.html#geom
size: geom size parameters.
... | [
"def",
"new_geom",
"(",
"geom_type",
",",
"size",
",",
"pos",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"rgba",
"=",
"RED",
",",
"group",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"type\"",
"]",
"=",
"str",
"(",
"geom_t... | 39.7 | 0.00123 |
def geo(self):
"""
General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`
"""
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
... | [
"def",
"geo",
"(",
"self",
")",
":",
"out",
"=",
"dict",
"(",
"zip",
"(",
"[",
"'xmin'",
",",
"'xres'",
",",
"'rotation_x'",
",",
"'ymax'",
",",
"'rotation_y'",
",",
"'yres'",
"]",
",",
"self",
".",
"raster",
".",
"GetGeoTransform",
"(",
")",
")",
... | 33.75 | 0.009009 |
def send_direct_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
"""
Direct operate a set of commands
:param command_set: set of command headers
:param callback: c... | [
"def",
"send_direct_operate_command_set",
"(",
"self",
",",
"command_set",
",",
"callback",
"=",
"asiodnp3",
".",
"PrintingCommandCallback",
".",
"Get",
"(",
")",
",",
"config",
"=",
"opendnp3",
".",
"TaskConfig",
"(",
")",
".",
"Default",
"(",
")",
")",
":"... | 56.3 | 0.012238 |
def create_event_subscription(self, instance, on_data, timeout=60):
"""
Create a new subscription for receiving events of an instance.
This method returns a future, then returns immediately. Stop the
subscription by canceling the future.
:param str instance: A Yamcs instance na... | [
"def",
"create_event_subscription",
"(",
"self",
",",
"instance",
",",
"on_data",
",",
"timeout",
"=",
"60",
")",
":",
"manager",
"=",
"WebSocketSubscriptionManager",
"(",
"self",
",",
"resource",
"=",
"'events'",
")",
"# Represent subscription as a future",
"subscr... | 34.676471 | 0.00165 |
def _copytree(src, dst):
"""Similar to shutils.copytree, except that dst is already there
"""
try:
os.makedirs(dst)
except OSError:
pass # It must already exist
for file in os.listdir(src):
try:
shutil.copy2('%s/%s' % (src, file), '%s/%s' % (dst, file))
e... | [
"def",
"_copytree",
"(",
"src",
",",
"dst",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dst",
")",
"except",
"OSError",
":",
"pass",
"# It must already exist",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"src",
")",
":",
"try",
":",
"shuti... | 34.266667 | 0.001894 |
def get_gce_driver(self):
"""Determine the GCE authorization settings and return a
libcloud driver.
"""
# Attempt to get GCE params from a configuration file, if one
# exists.
secrets_path = self.config.get('gce', 'libcloud_secrets')
secrets_found = False
... | [
"def",
"get_gce_driver",
"(",
"self",
")",
":",
"# Attempt to get GCE params from a configuration file, if one",
"# exists.",
"secrets_path",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'gce'",
",",
"'libcloud_secrets'",
")",
"secrets_found",
"=",
"False",
"try",
":... | 40.25 | 0.003032 |
def _operator_count(self, individual):
"""Count the number of pipeline operators as a measure of pipeline complexity.
Parameters
----------
individual: list
A grown tree with leaves at possibly different depths
dependending on the condition function.
Ret... | [
"def",
"_operator_count",
"(",
"self",
",",
"individual",
")",
":",
"operator_count",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"individual",
")",
")",
":",
"node",
"=",
"individual",
"[",
"i",
"]",
"if",
"type",
"(",
"node",
")",
"is",
... | 32.55 | 0.004478 |
def append(self, P0, P1, itemsize=None, **kwargs):
"""
Append a new set of segments to the collection.
For kwargs argument, n is the number of vertices (local) or the number
of item (shared)
Parameters
----------
P : np.array
Vertices positions of t... | [
"def",
"append",
"(",
"self",
",",
"P0",
",",
"P1",
",",
"itemsize",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"itemsize",
"=",
"itemsize",
"or",
"1",
"itemcount",
"=",
"len",
"(",
"P0",
")",
"/",
"itemsize",
"V",
"=",
"np",
".",
"empty",
... | 27.319149 | 0.001504 |
def drop_extension(name,
if_exists=None,
restrict=None,
cascade=None,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None... | [
"def",
"drop_extension",
"(",
"name",
",",
"if_exists",
"=",
"None",
",",
"restrict",
"=",
"None",
",",
"cascade",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"pa... | 30.666667 | 0.000554 |
def follow(user, obj):
""" Make a user follow an object """
follow, created = Follow.objects.get_or_create(user, obj)
return follow | [
"def",
"follow",
"(",
"user",
",",
"obj",
")",
":",
"follow",
",",
"created",
"=",
"Follow",
".",
"objects",
".",
"get_or_create",
"(",
"user",
",",
"obj",
")",
"return",
"follow"
] | 35 | 0.006993 |
def cont_discr_kalman_filter(cls, F, L, Qc, p_H, p_R, P_inf, X, Y, index = None,
m_init=None, P_init=None,
p_kalman_filter_type='regular',
calc_log_likelihood=False,
calc_grad_log_likeliho... | [
"def",
"cont_discr_kalman_filter",
"(",
"cls",
",",
"F",
",",
"L",
",",
"Qc",
",",
"p_H",
",",
"p_R",
",",
"P_inf",
",",
"X",
",",
"Y",
",",
"index",
"=",
"None",
",",
"m_init",
"=",
"None",
",",
"P_init",
"=",
"None",
",",
"p_kalman_filter_type",
... | 45.747212 | 0.006999 |
def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True):
""" filters leaf nodes of nested dictionary
Parameters
----------
d : dict
vals : list
values to filter by
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy valu... | [
"def",
"filter_values",
"(",
"d",
",",
"vals",
"=",
"None",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"vals",
"=",
"[",
"]",
"if",
"vals",
"is",
"None",
"else",
"vals",
"list_of_dicts",
"=",
"'__list__'",
"if",
"list_o... | 24.558824 | 0.001152 |
def damping(self):
"""Strain-compatible damping."""
try:
value = self._damping.value
except AttributeError:
value = self._damping
return value | [
"def",
"damping",
"(",
"self",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_damping",
".",
"value",
"except",
"AttributeError",
":",
"value",
"=",
"self",
".",
"_damping",
"return",
"value"
] | 27.428571 | 0.010101 |
def _set_portfast(self, v, load=False):
"""
Setter method for portfast, mapped from YANG variable /interface/port_channel/spanning_tree/portfast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_portfast is considered as a private
method. Backends looking t... | [
"def",
"_set_portfast",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | 83.227273 | 0.0054 |
def ensure_secret():
"""Check if secret key to encryot sessions exists,
generate it otherwise."""
home_dir = os.environ['HOME']
file_name = home_dir + "/.ipcamweb"
if os.path.exists(file_name):
with open(file_name, "r") as s_file:
secret = s_file.readline()
else:
secr... | [
"def",
"ensure_secret",
"(",
")",
":",
"home_dir",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"file_name",
"=",
"home_dir",
"+",
"\"/.ipcamweb\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_name",
")",
":",
"with",
"open",
"(",
"file_name",
... | 33.615385 | 0.002227 |
def unload_module(self, path):
'''Unload a loaded shared library.
Call this function to remove a shared library (e.g. a component) that
was previously loaded.
@param path The path to the shared library.
@raises FailedToUnloadModuleError
'''
with self._mutex:
... | [
"def",
"unload_module",
"(",
"self",
",",
"path",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"_obj",
".",
"unload_module",
"(",
"path",
")",
"!=",
"RTC",
".",
"RTC_OK",
":",
"raise",
"FailedToUnloadModuleError",
"(",
"path",
")"
] | 32.230769 | 0.00464 |
def render(self, display):
"""Render basicly the text."""
# to handle changing objects / callable
if self.text != self._last_text:
self._render()
display.blit(self._surface, (self.topleft, self.size)) | [
"def",
"render",
"(",
"self",
",",
"display",
")",
":",
"# to handle changing objects / callable",
"if",
"self",
".",
"text",
"!=",
"self",
".",
"_last_text",
":",
"self",
".",
"_render",
"(",
")",
"display",
".",
"blit",
"(",
"self",
".",
"_surface",
",",... | 34.142857 | 0.008163 |
def _run_cplusplus(work_bam_a, work_bam_b, out_dir, aligner, prefix, items):
"""Run third party disambiguation script, resolving into single set of calls.
"""
ngs_disambiguate = config_utils.get_program("ngs_disambiguate", items[0]["config"])
cmd = [ngs_disambiguate, "--no-sort", "--prefix", prefix, "--... | [
"def",
"_run_cplusplus",
"(",
"work_bam_a",
",",
"work_bam_b",
",",
"out_dir",
",",
"aligner",
",",
"prefix",
",",
"items",
")",
":",
"ngs_disambiguate",
"=",
"config_utils",
".",
"get_program",
"(",
"\"ngs_disambiguate\"",
",",
"items",
"[",
"0",
"]",
"[",
... | 62.285714 | 0.00905 |
def indicator_associations_types(
self, indicator_type, api_entity=None, api_branch=None, params=None
):
"""
Gets the indicator association from a Indicator/Group/Victim
Args:
indicator_type:
api_entity:
api_branch:
params:
Re... | [
"def",
"indicator_associations_types",
"(",
"self",
",",
"indicator_type",
",",
"api_entity",
"=",
"None",
",",
"api_branch",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"sel... | 26.09375 | 0.003464 |
def copyWithoutMathSubObjects(self):
"""
return a new MathGlyph containing all data except:
contours
components
anchors
guidelines
this is used mainly for internal glyph math.
"""
n = MathGlyph(None)
n.name = self.name
if self.unic... | [
"def",
"copyWithoutMathSubObjects",
"(",
"self",
")",
":",
"n",
"=",
"MathGlyph",
"(",
"None",
")",
"n",
".",
"name",
"=",
"self",
".",
"name",
"if",
"self",
".",
"unicodes",
"is",
"not",
"None",
":",
"n",
".",
"unicodes",
"=",
"list",
"(",
"self",
... | 26.789474 | 0.003795 |
def rotation_from_axes(x_axis, y_axis, z_axis):
"""Convert specification of axis in target frame to
a rotation matrix from source to target frame.
Parameters
----------
x_axis : :obj:`numpy.ndarray` of float
A normalized 3-vector for the target frame's x-axis.
... | [
"def",
"rotation_from_axes",
"(",
"x_axis",
",",
"y_axis",
",",
"z_axis",
")",
":",
"return",
"np",
".",
"hstack",
"(",
"(",
"x_axis",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"y_axis",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"z_axis",... | 36.5 | 0.007282 |
def copy(source, destination):
"""Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(source):
... | [
"def",
"copy",
"(",
"source",
",",
"destination",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
":",
"return",
"__copytree",
"(",
"source",
",",
"destination",
")",
"else",
":",
"return",
"__copyfile2",
"(",
"source",
",",
"desti... | 28.928571 | 0.002392 |
def join(self, network):
"""
Join a zerotier network
:param network: network id to join
:return:
"""
args = {'network': network}
self._network_chk.check(args)
response = self._client.raw('zerotier.join', args)
result = response.get()
if r... | [
"def",
"join",
"(",
"self",
",",
"network",
")",
":",
"args",
"=",
"{",
"'network'",
":",
"network",
"}",
"self",
".",
"_network_chk",
".",
"check",
"(",
"args",
")",
"response",
"=",
"self",
".",
"_client",
".",
"raw",
"(",
"'zerotier.join'",
",",
"... | 29.785714 | 0.006977 |
def course_register_user(self, course, username=None, password=None, force=False):
"""
Register a user to the course
:param course: a Course object
:param username: The username of the user that we want to register. If None, uses self.session_username()
:param password: Password ... | [
"def",
"course_register_user",
"(",
"self",
",",
"course",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"username",
"is",
"None",
":",
"username",
"=",
"self",
".",
"session_username",
"(",
")",
... | 50.888889 | 0.00857 |
def match_best_pdb_chains(pdb1, pdb1_name, pdb2, pdb2_name, cut_off = 60.0, use_seqres_sequences_if_possible = True):
'''A wrapper function for match_pdb_chains. This function only takes the best match. The return
value is a dict mapping
chain_id_in_pdb1 -> None or a tuple (chain_id_in_pdb_2, pe... | [
"def",
"match_best_pdb_chains",
"(",
"pdb1",
",",
"pdb1_name",
",",
"pdb2",
",",
"pdb2_name",
",",
"cut_off",
"=",
"60.0",
",",
"use_seqres_sequences_if_possible",
"=",
"True",
")",
":",
"d",
"=",
"match_pdb_chains",
"(",
"pdb1",
",",
"pdb1_name",
",",
"pdb2",... | 67.4 | 0.021962 |
def __dbfHeader(self):
"""Writes the dbf header and field descriptors."""
f = self.__getFileObj(self.dbf)
f.seek(0)
version = 3
year, month, day = time.localtime()[:3]
year -= 1900
# Remove deletion flag placeholder from fields
for field in self.fi... | [
"def",
"__dbfHeader",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"__getFileObj",
"(",
"self",
".",
"dbf",
")",
"f",
".",
"seek",
"(",
"0",
")",
"version",
"=",
"3",
"year",
",",
"month",
",",
"day",
"=",
"time",
".",
"localtime",
"(",
")",
"... | 41.515152 | 0.00214 |
def _import(self, name):
''' Import namespace package '''
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | [
"def",
"_import",
"(",
"self",
",",
"name",
")",
":",
"mod",
"=",
"__import__",
"(",
"name",
")",
"components",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"for",
"comp",
"in",
"components",
"[",
"1",
":",
"]",
":",
"mod",
"=",
"getattr",
"(",
"m... | 31.285714 | 0.008889 |
def wave_units(self, units):
"""
A setter for the wavelength units
Parameters
----------
units: str, astropy.units.core.PrefixUnit
The wavelength units
"""
# Make sure it's length units
if not units.is_equivalent(q.m):
raise ValueE... | [
"def",
"wave_units",
"(",
"self",
",",
"units",
")",
":",
"# Make sure it's length units",
"if",
"not",
"units",
".",
"is_equivalent",
"(",
"q",
".",
"m",
")",
":",
"raise",
"ValueError",
"(",
"units",
",",
"\": New wavelength units must be a length.\"",
")",
"#... | 42.607143 | 0.001639 |
def tokens(self):
""" Return a list of (type, value) tokens. """
if not self._tokens:
self._tokens = list(self.tokenise(self.route))
return self._tokens | [
"def",
"tokens",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_tokens",
":",
"self",
".",
"_tokens",
"=",
"list",
"(",
"self",
".",
"tokenise",
"(",
"self",
".",
"route",
")",
")",
"return",
"self",
".",
"_tokens"
] | 36.8 | 0.010638 |
def convert_softmax(node, **kwargs):
"""Map MXNet's softmax operator attributes to onnx's Softmax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("axis", -1))
softmax_node = onnx.helper.make_node(
"Softmax",
inp... | [
"def",
"convert_softmax",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"axis",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"\"axis\"",
",",
"-",
"1",
")... | 23.470588 | 0.00241 |
def get_or_set_hash(uri,
length=8,
chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'):
'''
Perform a one-time generation of a hash and write it to sdb.
If that value has already been set return the value instead.
This is useful for generating passwords or keys that are specific... | [
"def",
"get_or_set_hash",
"(",
"uri",
",",
"length",
"=",
"8",
",",
"chars",
"=",
"'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'",
")",
":",
"return",
"salt",
".",
"utils",
".",
"sdb",
".",
"sdb_get_or_set_hash",
"(",
"uri",
",",
"__opts__",
",",
"length"... | 32.794118 | 0.006969 |
def get_ip(request):
"""
Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy w... | [
"def",
"get_ip",
"(",
"request",
")",
":",
"# if neither header contain a value, just use local loopback",
"ip_address",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_FORWARDED_FOR'",
",",
"request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
",",
"'127... | 39.766667 | 0.000818 |
def size(self, destination):
"""
Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int}
"""
if not destination in... | [
"def",
"size",
"(",
"self",
",",
"destination",
")",
":",
"if",
"not",
"destination",
"in",
"self",
".",
"queue_metadata",
":",
"return",
"0",
"else",
":",
"return",
"len",
"(",
"self",
".",
"queue_metadata",
"[",
"destination",
"]",
"[",
"'frames'",
"]"... | 30.714286 | 0.006772 |
def update_sg(self, context, sg, rule_id, action):
"""Begins the async update process."""
db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE)
if not db_sg:
return None
with context.session.begin():
job_body = dict(action="%s sg rule %s" % (action,... | [
"def",
"update_sg",
"(",
"self",
",",
"context",
",",
"sg",
",",
"rule_id",
",",
"action",
")",
":",
"db_sg",
"=",
"db_api",
".",
"security_group_find",
"(",
"context",
",",
"id",
"=",
"sg",
",",
"scope",
"=",
"db_api",
".",
"ONE",
")",
"if",
"not",
... | 47.222222 | 0.002307 |
def filter(self, **search_args):
"""
Get a filtered list of resources
:param search_args: To be translated into ?arg1=value1&arg2=value2...
:return: A list of resources
"""
search_args = search_args or {}
raw_resources = []
for url, paginator_params in se... | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"search_args",
")",
":",
"search_args",
"=",
"search_args",
"or",
"{",
"}",
"raw_resources",
"=",
"[",
"]",
"for",
"url",
",",
"paginator_params",
"in",
"self",
".",
"paginator",
".",
"get_urls",
"(",
"self",
... | 41.884615 | 0.004488 |
def run(self,
ipyclient=None,
):
"""
Run a batch of dstat tests on a list of tests, where each test is
a dictionary mapping sample names to {p1 - p4} (and sometimes p5).
Parameters modifying the behavior of the run, such as the number
of bootstrap replicates (n... | [
"def",
"run",
"(",
"self",
",",
"ipyclient",
"=",
"None",
",",
")",
":",
"self",
".",
"results_table",
",",
"self",
".",
"results_boots",
"=",
"batch",
"(",
"self",
",",
"ipyclient",
")",
"## skip this for 5-part test results",
"if",
"not",
"isinstance",
"("... | 41.714286 | 0.008929 |
def collect(self):
"""
Collector Passenger stats
"""
if not os.access(self.config["bin"], os.X_OK):
self.log.error("Path %s does not exist or is not executable",
self.config["bin"])
return {}
dict_stats = self.get_passenger_memo... | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"self",
".",
"config",
"[",
"\"bin\"",
"]",
",",
"os",
".",
"X_OK",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Path %s does not exist or is not executable\"",
",",
... | 40.666667 | 0.001456 |
def open(filename):
"""Open a file in read only mode using the encoding detected by
detect_encoding().
"""
buffer = _builtin_open(filename, 'rb')
try:
encoding, lines = detect_encoding(buffer.readline)
buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True)
text.mode = 'r'
return text
... | [
"def",
"open",
"(",
"filename",
")",
":",
"buffer",
"=",
"_builtin_open",
"(",
"filename",
",",
"'rb'",
")",
"try",
":",
"encoding",
",",
"lines",
"=",
"detect_encoding",
"(",
"buffer",
".",
"readline",
")",
"buffer",
".",
"seek",
"(",
"0",
")",
"text"... | 24.285714 | 0.042493 |
def allow_client_outgoing(self, application_sid, **kwargs):
"""
Allow the user of this token to make outgoing connections. Keyword arguments are passed
to the application.
:param str application_sid: Application to contact
"""
scope = ScopeURI('client', 'outgoing', {'app... | [
"def",
"allow_client_outgoing",
"(",
"self",
",",
"application_sid",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"ScopeURI",
"(",
"'client'",
",",
"'outgoing'",
",",
"{",
"'appSid'",
":",
"application_sid",
"}",
")",
"if",
"kwargs",
":",
"scope",
".",... | 39.166667 | 0.006237 |
def checkKey(self, key=None):
'''
Checks that an API key is valid.
:param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization.
:returns: If the key is valid, this method will return ``True``.
:rtype: `bool`
:ra... | [
"def",
"checkKey",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"# Get site",
"url",
"=",
"Client",
".",
"ENDPOINT",
".",
"format",
"(",
"'checkKey'",
")",
"if",
"not",
"key",
":",
"key",
"=",
"self",
".",
"apiKey",
"params",
"=",
"{",
"'apiKey'",... | 34.166667 | 0.005931 |
def verifyUpdatewcs(fname):
"""
Verify the existence of WCSNAME in the file. If it is not present,
report this to the user and raise an exception. Returns True if WCSNAME
was found in all SCI extensions.
"""
updated = True
numsci,extname = count_sci_extensions(fname)
for n in range(1,n... | [
"def",
"verifyUpdatewcs",
"(",
"fname",
")",
":",
"updated",
"=",
"True",
"numsci",
",",
"extname",
"=",
"count_sci_extensions",
"(",
"fname",
")",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"numsci",
"+",
"1",
")",
":",
"hdr",
"=",
"fits",
".",
"geth... | 35.071429 | 0.005952 |
def get_album(self, id):
"""Return information about this album."""
url = self._base_url + "/3/album/{0}".format(id)
json = self._send_request(url)
return Album(json, self) | [
"def",
"get_album",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"self",
".",
"_base_url",
"+",
"\"/3/album/{0}\"",
".",
"format",
"(",
"id",
")",
"json",
"=",
"self",
".",
"_send_request",
"(",
"url",
")",
"return",
"Album",
"(",
"json",
",",
"self... | 40 | 0.009804 |
def _set_format_scope(self, fmt):
"""
Opens the format scope.
"""
self._prev_fmt = QtGui.QTextCharFormat(fmt)
self._prev_fmt_closed = False | [
"def",
"_set_format_scope",
"(",
"self",
",",
"fmt",
")",
":",
"self",
".",
"_prev_fmt",
"=",
"QtGui",
".",
"QTextCharFormat",
"(",
"fmt",
")",
"self",
".",
"_prev_fmt_closed",
"=",
"False"
] | 29 | 0.011173 |
def _merge_list_of_keys_into_dict(cls, data, keys, value, index=0):
"""Recursively merge list of keys that points to the given value into data.
Will override a primitive value with another primitive value, but will not
override a primitive with a dictionary.
For example:
Given the dictionary {'a':... | [
"def",
"_merge_list_of_keys_into_dict",
"(",
"cls",
",",
"data",
",",
"keys",
",",
"value",
",",
"index",
"=",
"0",
")",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
"or",
"index",
"<",
"0",
"or",
"index",
">=",
"len",
"(",
"keys",
")",
":",
"r... | 49.512821 | 0.009142 |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_content = properties.get("ipConfiguration", None)
if raw_content is not None:
resource = Resource.from_raw_data(raw_content)
prop... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
"raw_content",
"=",
"properties",
".",
"get",
"(",
"\"ipConfiguration\"",
",",
"None",
")",
"if",
"raw_c... | 42 | 0.004662 |
def _bbvi_fit(self, optimizer='RMSProp', iterations=1000, print_progress=True,
start_diffuse=False, **kwargs):
""" Performs Black Box Variational Inference
Parameters
----------
posterior : method
Hands bbvi_fit a posterior object
optimizer : string
... | [
"def",
"_bbvi_fit",
"(",
"self",
",",
"optimizer",
"=",
"'RMSProp'",
",",
"iterations",
"=",
"1000",
",",
"print_progress",
"=",
"True",
",",
"start_diffuse",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"model_name2",
"in",
"[",
... | 38.013514 | 0.0149 |
def _requirements_to_dict(rs):
"""Convert supported requirements into dictionary for output.
"""
out = []
added = set([])
for r in rs:
if r["class"] == "DockerRequirement" and "docker" not in added:
added.add("docker")
out.append({"requirement_type": "docker", "value"... | [
"def",
"_requirements_to_dict",
"(",
"rs",
")",
":",
"out",
"=",
"[",
"]",
"added",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"r",
"in",
"rs",
":",
"if",
"r",
"[",
"\"class\"",
"]",
"==",
"\"DockerRequirement\"",
"and",
"\"docker\"",
"not",
"in",
"added... | 46.85 | 0.004184 |
def init_app(self, app, sqla, namespace='api', route_prefix='/api'):
"""
Initialize the adapter if it hasn't already been initialized.
:param app: Flask application
:param sqla: Flask-SQLAlchemy instance
:param namespace: Prefixes all generated routes
:param route_prefix... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"sqla",
",",
"namespace",
"=",
"'api'",
",",
"route_prefix",
"=",
"'/api'",
")",
":",
"self",
".",
"app",
"=",
"app",
"self",
".",
"sqla",
"=",
"sqla",
"self",
".",
"_setup_adapter",
"(",
"namespace",
... | 35.538462 | 0.004219 |
def _analyze_func_string(func_string):
"""
Analyze given functiion string an extract:
* function name
* function arguments
* function keyword arguments
All given arguments must by of type string, int/float or list.
:param func_string: string of the function
:return: function name, arg... | [
"def",
"_analyze_func_string",
"(",
"func_string",
")",
":",
"func",
"=",
"ast",
".",
"parse",
"(",
"func_string",
")",
"try",
":",
"func_call",
"=",
"func",
".",
"body",
"[",
"0",
"]",
".",
"value",
"func_name",
"=",
"func_call",
".",
"func",
".",
"id... | 34.206349 | 0.000902 |
def evaluate_call_args(self, calculator):
"""Interpreting this literal as a function call, return a 2-tuple of
``(args, kwargs)``.
"""
args = []
kwargs = OrderedDict() # Sass kwargs preserve order
for var_node, value_node in self.argpairs:
value = value_node.... | [
"def",
"evaluate_call_args",
"(",
"self",
",",
"calculator",
")",
":",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"OrderedDict",
"(",
")",
"# Sass kwargs preserve order",
"for",
"var_node",
",",
"value_node",
"in",
"self",
".",
"argpairs",
":",
"value",
"=",
"val... | 37.478261 | 0.002262 |
def start(self, wait=False):
"""Start a task.
This function depends on the underlying implementation of _start, which
any subclass of ``Task`` should implement.
Args:
wait (bool): Whether or not to wait on the task to finish before
returning from this functi... | [
"def",
"start",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"if",
"self",
".",
"_status",
"is",
"not",
"TaskStatus",
".",
"IDLE",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot start %s in state %s\"",
"%",
"(",
"self",
",",
"self",
".",
"_status",
"... | 32.12 | 0.002418 |
def undecorate(func):
"""Returns the decorator and the undecorated function of given object."""
orig_call_wrapper = lambda x: x
for call_wrapper, unwrap in SUPPORTED_DECORATOR.items():
if isinstance(func, call_wrapper):
func = unwrap(func)
orig_call_wrapper = call_wrapper
... | [
"def",
"undecorate",
"(",
"func",
")",
":",
"orig_call_wrapper",
"=",
"lambda",
"x",
":",
"x",
"for",
"call_wrapper",
",",
"unwrap",
"in",
"SUPPORTED_DECORATOR",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"call_wrapper",
")",
":",
... | 40.111111 | 0.00542 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.