code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if updater is None:
updater = Adam()
# Make sure we aren't using a recycled updater
updater.reset()
N = _len_data(data)
x = np.array(x0, copy=True, dtype=float)
D = x.shape[0]
# Make sure we have a valid batch size
batch_size = min(batch_size, N)
# Process bounds
... | def sgd(fun, x0, data, args=(), bounds=None, batch_size=10, maxiter=5000,
updater=None, eval_obj=False, random_state=None) | Stochastic Gradient Descent.
Parameters
----------
fun : callable
the function to *minimize*, this must have the signature ``[obj,]``
grad = fun(x, data, ...)`, where the ``eval_obj`` argument tells
``sgd`` if an objective function value is going to be returned by
``fun``.
... | 3.362072 | 3.074405 | 1.093568 |
perms = endless_permutations(_len_data(data), random_state)
it = 0
while it < maxiter:
it += 1
ind = np.array([next(perms) for _ in range(batch_size)])
yield _split_data(data, ind) | def gen_batch(data, batch_size, maxiter=np.inf, random_state=None) | Create random batches for Stochastic gradients.
Batch index generator for SGD that will yeild random batches for a
a defined number of iterations, which can be infinite. This generator makes
consecutive passes through the data, drawing without replacement on each
pass.
Parameters
----------
... | 4.133041 | 6.573346 | 0.628758 |
min_, max_ = bound
if min_ is None:
min_ = -float('inf')
if max_ is None:
max_ = float('inf')
return min_, max_ | def normalize_bound(bound) | Replace ``None`` with + or - inf in bound tuples.
Examples
--------
>>> normalize_bound((2.6, 7.2))
(2.6, 7.2)
>>> normalize_bound((None, 7.2))
(-inf, 7.2)
>>> normalize_bound((2.6, None))
(2.6, inf)
>>> normalize_bound((None, None))
(-inf, inf)
This operation is idempot... | 2.447755 | 4.117688 | 0.594449 |
self.__init__(self.alpha, self.beta1, self.beta2, self.epsilon) | def reset(self) | Reset the state of this updater for a new optimisation problem. | 5.747675 | 4.988354 | 1.152219 |
if isinstance(obj, (basestring)):
lst = obj.split(sep)
if strip:
lst = [v.strip() for v in lst]
return lst
elif isinstance(obj, (list, tuple)):
return obj
elif obj is None:
return []
else:
return [obj] | def aslist(obj, sep=None, strip=True) | Returns given string separated by sep as list
:param obj:
:param sep:
:param strip: | 1.942963 | 2.304857 | 0.842986 |
try:
val = int(val)
except (ValueError, TypeError):
val = default
return val | def safe_int(val, default=None) | Returns int() of val if val is not convertable to int use default
instead
:param val:
:param default: | 3.265316 | 3.521322 | 0.927298 |
if isinstance(str_, unicode):
return str_
if not from_encoding:
from vcs.conf import settings
from_encoding = settings.DEFAULT_ENCODINGS
if not isinstance(from_encoding, (list, tuple)):
from_encoding = [from_encoding]
try:
return unicode(str_)
except U... | def safe_unicode(str_, from_encoding=None) | safe unicode function. Does few trick to turn str_ into unicode
In case of UnicodeDecode error we try to return it with encoding detected
by chardet library if it fails fallback to unicode with errors replaced
:param str_: string to decode
:rtype: unicode
:returns: unicode object | 2.210646 | 2.344377 | 0.942957 |
# if it's not basestr cast to str
if not isinstance(unicode_, basestring):
return str(unicode_)
if isinstance(unicode_, str):
return unicode_
if not to_encoding:
from vcs.conf import settings
to_encoding = settings.DEFAULT_ENCODINGS
if not isinstance(to_encod... | def safe_str(unicode_, to_encoding=None) | safe str function. Does few trick to turn unicode_ into string
In case of UnicodeEncodeError we try to return it with encoding detected
by chardet library if it fails fallback to string with errors replaced
:param unicode_: unicode to encode
:rtype: str
:returns: str object | 2.535754 | 2.546795 | 0.995665 |
import re
r = author.find('>')
l = author.find('<')
if l == -1 or r == -1:
# fallback to regex match of email out of a string
email_re = re.compile(r
r
r
r, re.IGNORECASE)
m = re.finda... | def author_email(author) | returns email address of given author.
If any of <,> sign are found, it fallbacks to regex findall()
and returns first found result or empty string
Regex taken from http://www.regular-expressions.info/email.html | 4.963288 | 4.53609 | 1.094178 |
if not '@' in author:
return author
else:
return author.replace(author_email(author), '').replace('<', '')\
.replace('>', '').strip() | def author_name(author) | get name of author, or else username.
It'll try to find an email in the author string and just cut it off
to get the username | 5.518517 | 4.78812 | 1.152544 |
X, y = check_X_y(X, y)
self.obj_ = -np.inf
# Make list of parameters and decorate optimiser to undestand this
params = [self.var, self.basis.regularizer, self.basis.params]
nmin = structured_minimizer(logtrick_minimizer(minimize))
# Close over objective and le... | def fit(self, X, y) | Learn the hyperparameters of a Bayesian linear regressor.
Parameters
----------
X : ndarray
(N, d) array input dataset (N samples, d dimensions).
y : ndarray
(N,) array targets (N samples)
Returns
-------
self
Notes
-----... | 6.372311 | 6.327409 | 1.007096 |
check_is_fitted(self, ['var_', 'regularizer_', 'weights_',
'covariance_', 'hypers_'])
X = check_array(X)
Phi = self.basis.transform(X, *atleast_list(self.hypers_))
Ey = Phi.dot(self.weights_)
Vf = (Phi.dot(self.covariance_) * Phi).sum(axis... | def predict_moments(self, X) | Full predictive distribution from Bayesian linear regression.
Parameters
----------
X : ndarray
(N*,d) array query input dataset (N* samples, d dimensions).
Returns
-------
Ey : ndarray
The expected value of y* for the query inputs, X* of shape (... | 5.305782 | 6.11789 | 0.867257 |
r'''Takes an iterator of strings, and attempts to wrap them in whole chunks
to fit within width. Takes an optional preamble which is prepended before
the first line, and an optional per-line prefix (which is appended to every
line but the first). If return_gen is true, this function returns a
genera... | def linewrap(chunks, width=None, sep=' ', preamble='', line_prefix='') | r'''Takes an iterator of strings, and attempts to wrap them in whole chunks
to fit within width. Takes an optional preamble which is prepended before
the first line, and an optional per-line prefix (which is appended to every
line but the first). If return_gen is true, this function returns a
generator ... | 3.992369 | 2.19922 | 1.815357 |
'''Fetches the IANA link relation registry'''
text = requests.get(rels_url).text.encode('ascii', 'ignore')
xml = objectify.fromstring(text)
iana_rels = {str(rec.value): str(rec.description)
for rec in xml.registry.record}
keys = sorted(iana_rels)
print('# IANA link relation regi... | def emit_iana_rels(rels_url) | Fetches the IANA link relation registry | 3.387547 | 3.197841 | 1.059323 |
for path in paths:
head = path
while head:
head, tail = os.path.split(head)
if head:
yield head
else:
# We don't need to yield empty path
break | def get_dirs_for_path(*paths) | Returns list of directories, including intermediate. | 4.108202 | 3.660168 | 1.122408 |
self.cursor.execute(
'SELECT name FROM sqlite_master WHERE type="table"'
)
return set(x[0] for x in self.cursor.fetchall()) | def get_tables(self) | Get all table names.
Returns
-------
`set` of `str` | 3.03013 | 3.191097 | 0.949558 |
while True:
self.cursor.execute(
'SELECT id FROM nodes WHERE value=?',
(value,)
)
node = self.cursor.fetchone()
if node is not None:
return node[0]
self.cursor.execute(
'INSERT IN... | def get_node(self, value) | Get node ID by value.
If a node with the specified value does not exist,
create it and return its ID.
Parameters
----------
value : `str`
Node value.
Returns
-------
`int`
Node ID. | 2.198899 | 2.2654 | 0.970645 |
data = (json.dumps(self.settings),)
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS main (
settings TEXT NOT NULL DEFAULT "{}"
)
''')
self.cursor.execute('SELECT * FROM main')
if self.cursor.fetchall() == []:
self.cu... | def update_main_table(self) | Write generator settings to database. | 2.800603 | 2.617778 | 1.06984 |
self.cursor.execute('PRAGMA foreign_keys=1')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS datasets (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL
)
''')
self.cursor.execute('''
CREATE T... | def create_node_tables(self) | Create node and link tables if they don't exist. | 2.078806 | 2.008508 | 1.035 |
if fp is not None:
raise NotImplementedError()
self.update_main_table()
self.db.commit() | def do_save(self, fp=None) | Save.
Parameters
----------
fp : `None`, optional | 8.366817 | 15.269437 | 0.547945 |
try:
vimrc = create_module('vcsrc', settings.VCSRC_PATH)
except IOError:
self.stderr.write("No module or package at %s\n"
% settings.VCSRC_PATH)
vimrc = None
return vimrc | def get_vcsrc(self) | Returns in-memory created module pointing at user's configuration
and extra code/commands. By default tries to create module from
:setting:`VCSRC_PATH`. | 8.724419 | 4.931238 | 1.769215 |
argv = [a for a in self.argv]
argv.insert(0, self.prog_name)
return argv | def get_argv_for_command(self) | Returns stripped arguments that would be passed into the command. | 4.605053 | 4.457567 | 1.033087 |
self.autocomplete()
if len(self.argv):
cmd = self.argv[0]
cmd_argv = self.get_argv_for_command()
self.run_command(cmd, cmd_argv)
else:
self.show_help() | def execute(self) | Executes whole process of parsing and running command. | 4.276392 | 3.90072 | 1.096309 |
try:
cmdpath = self.registry[cmd]
except KeyError:
raise CommandError("No such command %r" % cmd)
if isinstance(cmdpath, basestring):
Command = import_class(cmdpath)
else:
Command = cmdpath
return Command | def get_command_class(self, cmd) | Returns command class from the registry for a given ``cmd``.
:param cmd: command to run (key at the registry) | 3.258869 | 3.491818 | 0.933287 |
try:
Command = self.get_command_class(cmd)
except CommandError, e:
self.stderr.write(str(e) + '\n')
self.show_help()
sys.exit(-1)
command = Command(stdout=self.stdout, stderr=self.stderr)
command.run_from_argv(argv) | def run_command(self, cmd, argv) | Runs command.
:param cmd: command to run (key at the registry)
:param argv: arguments passed to the command | 2.752014 | 3.068562 | 0.896842 |
output = [
'Usage %s subcommand [options] [args]' % self.prog_name,
'',
'Available commands:',
'',
]
for cmd in self.get_commands():
output.append(' %s' % cmd)
output += ['', '']
self.stdout.write(u'\n'.join(ou... | def show_help(self) | Prints help text about available commands. | 3.380622 | 3.259921 | 1.037026 |
usage = ' '.join(['%prog', subcommand, '[options]'])
if self.args:
usage = '%s %s' % (usage, str(self.args))
return usage | def usage(self, subcommand) | Returns *how to use command* text. | 3.860039 | 3.736086 | 1.033177 |
parser = OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=sorted(self.get_option_list()))
return parser | def get_parser(self, prog_name, subcommand) | Returns parser for given ``prog_name`` and ``subcommand``.
:param prog_name: vcs main script name
:param subcommand: command name | 3.607656 | 4.176126 | 0.863876 |
parser = self.get_parser(prog_name, subcommand)
parser.print_help() | def print_help(self, prog_name, subcommand) | Prints parser's help.
:param prog_name: vcs main script name
:param subcommand: command name | 2.606125 | 3.167596 | 0.822745 |
parser = self.get_parser(argv[0], argv[1])
options, args = parser.parse_args(argv[2:])
self.execute(*args, **options.__dict__) | def run_from_argv(self, argv) | Runs command for given arguments.
:param argv: arguments | 2.97529 | 3.806428 | 0.781649 |
try:
self.handle(*args, **options)
except CommandError, e:
if options['debug']:
try:
import ipdb
ipdb.set_trace()
except ImportError:
import pdb
pdb.set_trace(... | def execute(self, *args, **options) | Executes whole process of parsing arguments, running command and
trying to catch errors. | 2.163405 | 2.168493 | 0.997654 |
self.pre_process(self.repo)
self.handle_repo(self.repo, *args, **options)
self.post_process(self.repo, **options) | def handle(self, *args, **options) | Runs ``pre_process``, ``handle_repo`` and ``post_process`` methods, in
that order. | 4.179545 | 2.642649 | 1.581574 |
branch_name = None
if not options.get('all', None):
branch_name = options.get('branch') or repo.workdir.get_branch()
if options.get('start_date'):
options['start_date'] = parse_datetime(options['start_date'])
if options.get('end_date'):
option... | def get_changesets(self, repo, **options) | Returns generator of changesets from given ``repo`` for given
``options``.
:param repo: repository instance. Same as ``self.repo``.
**Available options**
* ``start_date``: only changesets not older than this parameter would be
generated
* ``end_date``: only changeset... | 2.232808 | 2.174587 | 1.026773 |
progressbar = ColoredProgressBar(total)
progressbar.steps_label = 'Commit'
progressbar.elements += ['eta', 'time']
return progressbar | def get_progressbar(self, total, **options) | Returns progress bar instance for a given ``total`` number of clicks
it should do. | 12.086481 | 12.406469 | 0.974208 |
cid = options.get('changeset_id', None)
return self.repo.get_changeset(cid) | def get_changeset(self, **options) | Returns changeset for given ``options``. | 4.455136 | 4.533382 | 0.98274 |
if isinstance(data, dict):
print('{')
new_indent = indent + 4
space = ' ' * new_indent
keys = list(sorted(data.keys()))
for i, k in enumerate(keys):
print(space, json.dumps(k), ': ', sep='', end='')
pprint(data[k], new_indent,
e... | def pprint(data, indent=0, end='\n') | Pretty print JSON data.
Parameters
----------
data
JSON data.
indent : `int`, optional
Indent level in characters (default: 0).
end : `str`, optional
String to print after the data (default: '\\\\n'). | 1.737631 | 1.755742 | 0.989685 |
if args.type == JSON:
if fname.endswith('.bz2'):
open_ = bz2.open
else:
open_ = open
if args.progress:
print('Loading JSON data...')
with open_(fname, 'rt') as fp:
storage = JsonStorage.load(fp)
else:
storage = Sqlit... | def load(cls, fname, args) | Load a generator.
Parameters
----------
cls : `type`
Generator class.
fname : `str`
Input file path.
args : `argparse.Namespace`
Command arguments.
Returns
-------
`cls` | 3.961889 | 4.34915 | 0.910957 |
if isinstance(markov.storage, JsonStorage):
if fname is None:
markov.save(sys.stdout)
else:
if fname.endswith('.bz2'):
open_ = bz2.open
else:
open_ = open
if args.progress:
print('Saving JSON data...... | def save(markov, fname, args) | Save a generator.
Parameters
----------
markov : `markovchain.Markov`
Generator to save.
fname : `str`
Output file path.
args : `argparse.Namespace`
Command arguments. | 3.145426 | 3.543624 | 0.88763 |
_, ext = os.path.splitext(fname)
ext = ext[1:] or 'png'
with open(fname, 'wb') as fp:
img.save(fp, ext) | def save_image(img, fname) | Save an image.
Parameters
----------
img : `PIL.Image`
Image to save.
fname : `str`
File path. | 2.736345 | 2.744501 | 0.997028 |
try:
if args.output is sys.stdout and args.progress:
raise ValueError('args.output is stdout and args.progress')
except AttributeError:
pass
try:
fname = '.' + args.type
except AttributeError:
try:
fname = args.state
except AttributeE... | def set_args(args) | Set computed command arguments.
Parameters
----------
args : `argparse.Namespace`
Command arguments.
base : `iterable` of `type`
Generator mixins.
Raises
------
ValueError
If output file is stdout and progress bars are enabled. | 3.46345 | 3.383402 | 1.023659 |
if nfiles < 0:
raise ValueError('Invalid file count: ' + str(nfiles))
if nfiles == 1:
return
try:
fmt % nfiles
except TypeError as err:
raise ValueError(''.join(
('Invalid file format string: ', fmt, ': ', str(err))
)) | def check_output_format(fmt, nfiles) | Validate file format string.
Parameters
----------
fmt : `str`
File format string.
nfiles : `int`
Number of files.
Raises
------
ValueError
If nfiles < 0 or format string is invalid. | 3.859567 | 3.931852 | 0.981616 |
if progress:
if fnames:
fnames = tqdm(fnames, desc='Loading', unit='file',
bar_format=BAR_FORMAT,
leave=leave, dynamic_ncols=True)
else:
progress = False
yield fnames
if progress:
fnames.close() | def infiles(fnames, progress, leave=True) | Get input file paths.
Parameters
----------
fnames : `list` of `str`
File paths.
progress : `bool`
Show progress bar.
leave : `bool`, optional
Leave progress bar (default: True).
Returns
-------
`generator` of `str`
Input file paths. | 3.654688 | 4.582959 | 0.797452 |
if nfiles > 1:
fnames = (fmt % i for i in range(nfiles))
elif nfiles == 1:
fnames = (fmt,)
else:
raise ValueError('output file count <= 0')
if progress:
fnames = tqdm(fnames, total=nfiles,
desc='Generating', unit='file',
b... | def outfiles(fmt, nfiles, progress, leave=True) | Get output file paths.
Parameters
----------
fmt : `str`
File path format string.
nfiles : `int`
Number of files.
progress : `bool`
Show progress bars.
leave : `bool`, optional
Leave progress bar (default: True).
Raises
------
ValueError
If n... | 2.689398 | 2.817505 | 0.954532 |
if args.type == SQLITE:
storage = SqliteStorage
else:
storage = JsonStorage
storage = storage.load(args.state)
data = storage.settings
try:
del data['markov']['nodes']
except KeyError:
pass
pprint(data) | def cmd_settings(args) | Print generator settings.
Parameters
----------
args : `argparse.Namespace`
Command arguments. | 7.057846 | 7.988542 | 0.883496 |
if not cls.warning:
cls.warning = True
print('Can\'t create progress bar:', str(TQDM_IMPORT_ERROR),
file=sys.stderr) | def print_warning(cls) | Print a missing progress bar warning if it was not printed. | 9.849134 | 6.807102 | 1.446891 |
links = self.parser(self.scanner(data, part), part, dataset)
self.storage.add_links(links) | def data(self, data, part=False, dataset='') | Parse data and update links.
Parameters
----------
data
Data to parse.
part : `bool`, optional
True if data is partial (default: `False`).
dataset : `str`, optional
Dataset key prefix (default: ''). | 9.821223 | 14.446115 | 0.679852 |
if state_size is None:
try:
state_size = next(iter(self.parser.state_sizes))
except StopIteration:
return
#elif (self.parser is not None
# and state_size not in self.parser.state_sizes):
# raise ValueError('invalid ... | def generate(self, state_size=None, start=(), dataset='', backward=False) | Generate a sequence.
Parameters
----------
state_size : `int`, optional
State size (default: parser.state_sizes[0]).
start : `str` or `iterable` of `str`, optional
Initial state (default: ()).
dataset : `str`, optional
Dataset key prefix.
... | 3.418255 | 3.40245 | 1.004645 |
return {
'scanner': None if self.scanner is None else self.scanner.save(),
'parser': None if self.parser is None else self.parser.save()
} | def get_settings_json(self) | Convert generator settings to JSON.
Returns
-------
`dict`
JSON data. | 4.416219 | 5.297047 | 0.833713 |
self.storage.settings['markov'] = self.get_settings_json()
self.storage.save(fp) | def save(self, fp=None) | Save to file.
Parameters
----------
fp : `file`, optional
Output file. | 10.281782 | 15.220227 | 0.675534 |
args = dict(storage.settings.get('markov', {}))
args['storage'] = storage
return cls(**args) | def from_storage(cls, storage) | Load from storage.
Parameters
----------
storage : `markovchain.storage.Storage`
Returns
-------
`markovchain.Markov` | 8.400887 | 8.663898 | 0.969643 |
if storage is None:
storage = cls.DEFAULT_STORAGE
return cls.from_storage(storage.load(fp)) | def from_file(cls, fp, storage=None) | Load from file.
Parameters
----------
fp : `str` or `file`
File or path.
storage : `type`, optional
Storage class (default: cls.DEFAULT_STORAGE)
Returns
-------
`markovchain.Markov` | 4.001319 | 4.62855 | 0.864487 |
if storage is None:
storage = cls.DEFAULT_STORAGE
return cls.from_storage(storage(settings=settings)) | def from_settings(cls, settings=None, storage=None) | Create from settings.
Parameters
----------
settings : `dict`, optional
Settings (default: None).
storage : `type`, optional
Storage class (default: cls.DEFAULT_STORAGE)
Returns
-------
`markovchain.Markov` | 4.253462 | 4.975647 | 0.854856 |
img_width, img_height = img.size
if self.resize:
width, height = self.resize
scale = min(width / img_width, height / img_height)
img = img.resize((floor(img_width * scale),
floor(img_height * scale)))
img_width, img_... | def input(self, img) | Resize input image if necessary.
Parameters
----------
img : `PIL.Image`
Input image.
Raises
------
ValueError
If input image is too small.
Returns
-------
`PIL.Image`
Resized image or input image. | 2.17008 | 2.190155 | 0.990834 |
if level < self.levels - 1:
width, height = img.size
scale = reduce(lambda x, y: x * y,
islice(self.level_scale, level, self.levels))
img = img.resize((width // scale, height // scale), self.scale)
return img | def level(self, img, level) | Get image level.
Parameters
----------
img : `PIL.Image`
Input image.
level : `int`
Level number.
Returns
-------
`PIL.Image`
Converted image. | 4.237888 | 4.400754 | 0.962991 |
if level == 0:
width, height = img.size
else:
width, height = prev.size
tr = self.traversal[0](width, height, ends=(level == 0))
if level == 0:
for xy in tr:
if xy is None:
yield self.END
el... | def _scan_level(self, level, prev, img) | Scan a level.
Parameters
----------
level : `int`
Level number.
prev : `PIL.Image` or None
Previous level image or None if level == 0.
img : `PIL.Image`
Current level image.
Returns
-------
`generator` of (`str` or `ma... | 3.408278 | 3.155722 | 1.080031 |
data = super().save()
data['resize'] = list(self.resize) if self.resize is not None else None
data['traversal'] = [t.save() for t in self.traversal]
data['levels'] = self.levels
data['level_scale'] = self.level_scale
data['scale'] = self.scale
return data | def save(self) | Convert to JSON.
Returns
-------
`dict`
JSON data. | 3.669294 | 3.789818 | 0.968198 |
N = y_true.shape[0]
return ((y_true - y_pred)**2).sum() / (N * y_true.var()) | def smse(y_true, y_pred) | Standardised mean squared error.
Parameters
----------
y_true: ndarray
vector of true targets
y_pred: ndarray
vector of predicted targets
Returns
-------
float:
SMSE of predictions vs truth (scalar)
Example
-------
>>> y_true = np.random.randn(100)
... | 2.981835 | 3.610709 | 0.825831 |
return - norm.logpdf(y_true, loc=y_pred, scale=np.sqrt(y_var)).mean() | def mll(y_true, y_pred, y_var) | Mean log loss under a Gaussian distribution.
Parameters
----------
y_true: ndarray
vector of true targets
y_pred: ndarray
vector of predicted targets
y_var: float or ndarray
predicted variances
Returns
-------
float:
The mean negative log loss (negative ... | 3.101278 | 3.758264 | 0.825189 |
var = y_train.var()
mu = y_train.mean()
ll_naive = norm.logpdf(y_true, loc=mu, scale=np.sqrt(var))
ll_mod = norm.logpdf(y_true, loc=y_pred, scale=np.sqrt(y_var))
return - (ll_mod - ll_naive).mean() | def msll(y_true, y_pred, y_var, y_train) | Mean standardised log loss under a Gaussian distribution.
Parameters
----------
y_true: ndarray
vector of true targets
y_pred: ndarray
vector of predicted targets
y_var: float or ndarray
predicted variances
y_train: ndarray
vector of *training* targets by which t... | 2.452141 | 2.783356 | 0.881001 |
t = y_true.mean()
p = y_pred.mean()
St = y_true.var()
Sp = y_pred.var()
Spt = np.mean((y_true - t) * (y_pred - p))
return 2 * Spt / (St + Sp + (t - p)**2) | def lins_ccc(y_true, y_pred) | Lin's Concordance Correlation Coefficient.
See https://en.wikipedia.org/wiki/Concordance_correlation_coefficient
Parameters
----------
y_true: ndarray
vector of true targets
y_pred: ndarray
vector of predicted targets
Returns
-------
float:
1.0 for a perfect ma... | 3.316806 | 3.39372 | 0.977337 |
last_good_request = self.request
middleware_result = None
try:
last_good_request, middleware_result = self.program.execute_input_middleware_stream(self.request, self)
except GiottoException as exc:
# save this exception so it can be re-raised from within
... | def get_response(self) | High level function for getting a response. This is what the concrete
controller should call. Returns a controller specific response. | 5.483545 | 5.388804 | 1.017581 |
if self.middleware_interrupt_exc:
## the middleware raised an exception, re-raise it here so
## get_concrete_response (defined in subclasses) can catch it.
raise self.middleware_interrupt_exc
if self.middleware_control:
## this redirect object ca... | def get_data_response(self) | Execute the model and view, and handle the cache.
Returns controller-agnostic response data. | 5.24341 | 4.943329 | 1.060704 |
kwargs_from_invocation = self.get_raw_data()
args_from_invocation = deque(self.path_args)
defaults = kwargs
values = args + list(kwargs.keys())
output = {}
raw = False
for i, field in enumerate(values):
## going through each bit of data tha... | def get_data_for_model(self, args, kwargs) | In comes args and kwargs expected for the model. Out comes the data from
this invocation that will go to the model.
In other words, this function does the "data negotiation" between the
controller and the model. | 6.419893 | 6.389879 | 1.004697 |
def wrapped(func):
param_name = inflection.underscore(func.__name__)
options.setdefault('name', param_name)
if 'flags' in options:
if isinstance(options['flags'], set):
options['flags'].add('Virtual')
options['flags'].add('ReadOnly')
... | def virtual(cls, **options) | Allows for defining virtual columns and collectors on models -- these
are objects that are defined in code and not directly in a data store.
:param cls:
:param options:
:return: | 3.621823 | 3.645222 | 0.993581 |
while node:
node = node.parent
if isinstance(node, scoped_nodes.FunctionDef):
return True
return False | def _isInner(node) | Determine whether the given node is, at any point in its syntactic
parentage, defined within a function.
@param node: The node to inspect.
@type node: L{logilab.astng.bases.NodeNG}
@return: a boolean indicating if the given node is defined as an inner
class or inner function. | 4.997619 | 6.182285 | 0.808377 |
# For setter properties pylint fails so we use a custom code.
decorators = []
if not node.decorators:
return decorators
for decorator in node.decorators.nodes:
decorators.append(decorator.as_string())
return decorators | def _getDecoratorsName(node) | Return a list with names of decorators attached to this node.
@param node: current node of pylint | 8.082035 | 8.706291 | 0.928298 |
if node_type not in ['function', 'method']:
return False
for name in _getDecoratorsName(node):
if '.setter' in name:
return True
return False | def _isSetter(node_type, node) | Determine whether the given node is a setter property.
@param node_type: The type of the node to inspect.
@param node: The L{logilab.astng.bases.NodeNG} to inspect.
@return: a boolean indicating if the given node is a setter. | 5.289604 | 6.504585 | 0.813212 |
docstringStriped = node.as_string().strip()
linenoDocstring = (node.lineno + docstringStriped
.count("\n", 0, docstringStriped.index('"""')))
if node_type == "module":
# Module starts from line 0.
linenoDocstring += 1
return lin... | def _getDocstringLineno(self, node_type, node) | Get line number of the docstring.
@param node_type: type of node_type
@param node: node of currently checking
@return: line number | 6.026716 | 6.492765 | 0.92822 |
docstring = node.doc
if docstring is None:
# The node does not have a docstring.
if _isInner(node):
# Do not check things inside a function or method.
return
if _isSetter(node_type, node):
# Setters don't need ... | def _check_docstring(self, node_type, node, report_missing=True,
confidence=None) | Check whether the opening and the closing of docstring
on a line by themselves.
Then check for epytext markups for function or method.
@param node_type: type of node
@param node: current node of pylint | 3.911573 | 3.883596 | 1.007204 |
indentDocstring = node.col_offset and node.col_offset or 0
indentDocstring += len(re.findall(r'\n( *)"""',
node.as_string())[0])
linesDocstring = node.doc.lstrip("\n").split("\n")
for nline, lineDocstring in enumerate(linesDocstring):
... | def _checkIndentationIssue(self, node, node_type, linenoDocstring) | Check whether a docstring have consistent indentations.
@param node: the node currently checks by pylint
@param node_type: type of given node
@param linenoDocstring: line number the docstring begins | 3.565072 | 3.561437 | 1.001021 |
# Check the opening/closing of docstring.
docstringStrippedSpaces = node.doc.strip(" ")
if (not docstringStrippedSpaces.startswith("\n")
or not docstringStrippedSpaces.endswith("\n")):
# If the docstring is in one line, then do not check indentations.
... | def _checkDocstringFormat(self, node_type, node, linenoDocstring) | Check opening/closing of docstring.
@param node_type: type of node
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring | 6.722776 | 6.455116 | 1.041465 |
returnFound = False
for subnode in node.body:
if type(subnode) == node_classes.Return and subnode.value:
returnFound = True
break
return returnFound | def _hasReturnValue(self, node) | Determine whether the given method or function has a return statement.
@param node: the node currently checks | 4.824824 | 6.294965 | 0.766458 |
if node_type not in ['function', 'method']:
return
# Check for arguments.
# If current node is method,
# then first argument could not have a epytext markup.
# The first argument usually named 'self'.
argnames = (node.argnames()[1:] if node_type == 'm... | def _checkEpytext(self, node_type, node, linenoDocstring) | Check epytext of docstring.
@param node_type: type of node
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring | 4.230907 | 4.236824 | 0.998604 |
# Getter properties don't need to document their return value,
# but then need to have a return value.
if 'property' in _getDecoratorsName(node):
if self._hasReturnValue(node):
# Getter properties don't need a docstring.
return
# Chec... | def _checkReturnValueEpytext(self, node, linenoDocstring) | Check if return value is documented.
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring | 4.521864 | 4.58059 | 0.98718 |
# Check whether there is a blank line before epytext markups.
patternEpytext = (r"\n *@(param|type|return|returns|rtype|ivar|cvar"
r"|raises|raise)"
r"\s*[a-zA-Z0-9_]*\s*\:")
matchedEpytext = re.search(patternEpytext, node.doc)
... | def _checkBlankLineBeforeEpytext(self, node_type, node, linenoDocstring) | Check whether there is a blank line before epytext.
@param node_type: type of node
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring | 4.309217 | 4.18926 | 1.028635 |
if isinstance(serializer, string_types):
try:
app_label, serializer_name = serializer.split('.')
app_package = get_application(app_label)
serializer_module = import_module('%s.serializers' % app_package)
serializer = getattr(serializer_module, serializer_... | def get_serializer(serializer) | Load a serializer. | 2.30794 | 2.280632 | 1.011974 |
def is_modelperms():
return 'ModelPermissionsSerializer' in [
ser.__name__ for ser in cls.__bases__
]
is_serializer = type(cls).__name__ == 'SerializerMetaclass'
return inspect.isclass(cls) and is_serializer and is_modelperms() | def inherits_modelpermissions_serializer(cls) | Verify that serializer is a :py:class:`~rest_framework_fine_permissions.serializers.ModelPermissionsSerializer`. | 4.675235 | 4.608003 | 1.01459 |
model_name = self.Meta.model.__name__.lower()
app_label = self.Meta.model._meta.app_label
full_model_name = '%s.%s' % (app_label, model_name)
permissions = self.cached_allowed_fields.get(full_model_name)
if not permissions:
permissions = FieldPermission.obje... | def _get_user_allowed_fields(self) | Retrieve all allowed field names ofr authenticated user. | 2.362357 | 2.229552 | 1.059565 |
ret = OrderedDict()
# no rights to see anything
if not self.user:
return ret
# all fields that can be accessed through serializer
fields = super(ModelPermissionsSerializer, self).get_fields()
# superuser can see all the fields
if self.user.... | def get_fields(self) | Calculate fields that can be accessed by authenticated user. | 5.132159 | 4.677932 | 1.0971 |
return (
[model_info.pk.name] +
list(declared_fields.keys()) +
list(model_info.fields.keys()) +
list(model_info.relations.keys())
) | def _get_default_field_names(self, declared_fields, model_info) | Return default field names for serializer. | 3.012692 | 2.588232 | 1.163996 |
class NestedModelPermissionSerializer(ModelPermissionsSerializer):
class Meta:
model = relation_info.related_model
depth = nested_depth - 1
nested_context = self.context
fields = '__all__'
return NestedM... | def _get_nested_class(self, nested_depth, relation_info) | Define the serializer class for a relational field. | 6.389112 | 4.91767 | 1.299215 |
out = {}
for i, col in enumerate(cursor.description):
out[col[0]] = row[i]
return out | def dict_factory(cursor, row) | Converts the cursor information from a SQLite query to a dictionary.
:param cursor | <sqlite3.Cursor>
row | <sqlite3.Row>
:return {<str> column: <variant> value, ..} | 2.501384 | 3.606242 | 0.693626 |
if data is None:
data = {}
# check to make sure the connection hasn't been reset or lost
cursor = native.cursor()
# determine if we're executing multiple statements at once
commands = [cmd for cmd in command.split(';') if cmd]
if len(commands) > 1:
... | def _execute(self,
native,
command,
data=None,
returning=True,
mapper=dict) | Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
autoCommit | <bool> | commit database changes immediately
autoClose | <bool> | closes connections immediate... | 3.473504 | 3.516795 | 0.98769 |
if not sqlite:
raise orb.errors.BackendNotFound('sqlite is not installed.')
dbname = db.name()
try:
sqlite_db = sqlite.connect(dbname)
sqlite_db.create_function('REGEXP', 2, matches)
sqlite_db.row_factory = dict_factory
sqlit... | def _open(self, db, writeAccess=False) | Handles simple, SQL specific connection creation. This will not
have to manage thread information as it is already managed within
the main open method for the SQLBase class.
:param db | <orb.Database>
:return <variant> | backend specific database connection | 4.730272 | 4.586402 | 1.031369 |
if password != password2:
raise InvalidInput(password={'message': "Passwords do not match"},
username={'value': username})
user = User.objects.create_user(username, password)
return create_session(user.username, password) | def basic_register(username, password, password2) | Register a user and session, and then return the session_key and user. | 5.535073 | 5.02775 | 1.100905 |
user = User.objects.get_user_by_password(username, password)
auth_session_engine = get_config('auth_session_engine')
if not user:
raise InvalidInput('Username or password incorrect')
session_key = random_string(15)
while auth_session_engine.get(session_key):
session_key = random... | def create_session(username, password) | Create a session for the user, and then return the key. | 2.994236 | 2.880372 | 1.039531 |
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
... | def check(codeString, filename, reporter=None) | Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where error... | 3.764292 | 3.790668 | 0.993042 |
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.py'):
yield os.path.join(dirpath, filename)
else:
yield path | def iterSourceCode(paths) | Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is. | 1.554644 | 1.660815 | 0.936073 |
warnings = 0
for sourcePath in iterSourceCode(paths):
if re.search(RE_EXCLUDE, sourcePath):
continue
warnings += checkPath(sourcePath, reporter)
return warnings | def checkRecursive(paths, reporter) | Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found. | 6.101122 | 6.099043 | 1.000341 |
if isinstance(db_value, (str, unicode)) and db_value.startswith('{'):
try:
db_value = projex.text.safe_eval(db_value)
except StandardError:
log.exception('Invalid reference found')
raise orb.errors.OrbError('Invalid reference found... | def dbRestore(self, db_value, context=None) | Extracts the db_value provided back from the database.
:param db_value: <variant>
:param context: <orb.Context>
:return: <variant> | 5.397742 | 5.410275 | 0.997683 |
super(ReferenceColumn, self).loadJSON(jdata)
# load additional information
self.__reference = jdata.get('reference') or self.__reference
self.__removeAction = jdata.get('removeAction') or self.__removeAction | def loadJSON(self, jdata) | Loads the given JSON information for this column.
:param jdata: <dict> | 5.525953 | 5.025696 | 1.09954 |
model = orb.system.model(self.__reference)
if not model:
raise orb.errors.ModelNotFound(schema=self.__reference)
return model | def referenceModel(self) | Returns the model that this column references.
:return <Table> || None | 10.917785 | 12.271318 | 0.889699 |
context = context or orb.Context()
value = super(ReferenceColumn, self).restore(value, context=context)
# check to make sure that we're processing the right values
if self.testFlag(self.Flags.I18n) and context.locale == 'all':
return {locale: self._restore(val, cont... | def restore(self, value, context=None) | Returns the inflated value state. This method will match the desired inflated state.
:param value: <variant>
:param inflated: <bool>
:return: <variant> | 6.593148 | 7.585073 | 0.869227 |
ref_model = self.referenceModel()
if isinstance(value, orb.Model):
expected_schema = ref_model.schema().name()
received_schema = value.schema().name()
if expected_schema != received_schema:
raise orb.errors.InvalidReference(self.name(),
... | def validate(self, value) | Re-implements the orb.Column.validate method to verify that the
reference model type that is used with this column instance is
the type of value being provided.
:param value: <variant>
:return: <bool> | 4.570691 | 3.44601 | 1.326372 |
model = self.referenceModel()
return model(value, context=context) | def valueFromString(self, value, context=None) | Re-implements the orb.Column.valueFromString method to
lookup a reference object based on the given value.
:param value: <str>
:param context: <orb.Context> || None
:return: <orb.Model> || None | 10.837722 | 15.133457 | 0.716143 |
manager = manager or orb.system
manager.activate(self)
return True | def activate(self, manager=None) | Activates this database within the given orb instance. This will
register the database to orb and then set it as the active one.
:param manager | <orb.Manager> | 17.860264 | 34.482788 | 0.517947 |
self.connection().addNamespace(namespace, orb.Context(**context)) | def addNamespace(self, namespace, **context) | Creates a new namespace within this database.
:param namespace: <str> | 23.187462 | 25.730316 | 0.901173 |
back = self.backend()
if back:
back.interrupt(threadId) | def interrupt(self, threadId=None) | Interrupts the thread at the given id.
:param threadId | <int> || None | 10.14728 | 10.290127 | 0.986118 |
# define custom properties
if not isinstance(connection, orb.Connection):
conn = orb.Connection.byName(connection)
if not conn:
raise orb.errors.BackendNotFound(connection)
connection = conn(self)
else:
connection.setDataba... | def setConnection(self, connection) | Assigns the backend connection for this database instance.
:param connection: <str> || <orb.Connection> | 5.728396 | 4.978736 | 1.150572 |
context = orb.Context(**context)
# collect the information for this database
conn = self.__connection
all_models = orb.system.models(orb.Model).values()
all_models.sort(cmp=lambda x,y: cmp(x.schema(), y.schema()))
tables = [model for model in all_models if issu... | def sync(self, models=None, **context) | Syncs the database by calling its schema sync method. If
no specific schema has been set for this database, then
the global database schema will be used. If the dryRun
flag is specified, then all the resulting commands will
just be logged to the current logger and not actually
... | 3.121252 | 3.174303 | 0.983287 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.