code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
generator = check_random_state(random_state)
while True:
batch_inds = generator.permutation(N)
for b in batch_inds:
yield b | def endless_permutations(N, random_state=None) | Generate an endless sequence of random integers from permutations of the
set [0, ..., N).
If we call this N times, we will sweep through the entire set without
replacement, on the (N+1)th call a new permutation will be created, etc.
Parameters
----------
N: int
the length of the set
... | 3.283487 | 5.088681 | 0.645253 |
if create:
if not (path or alias):
raise TypeError("If create is specified, we need path and scm type")
return get_backend(alias)(path, create=True)
if path is None:
path = abspath(os.path.curdir)
try:
scm, path = get_scm(path, search_up=True)
path = ... | def get_repo(path=None, alias=None, create=False) | Returns ``Repository`` object of type linked with given ``alias`` at
the specified ``path``. If ``alias`` is not given it will try to guess it
using get_scm method | 3.976211 | 3.74158 | 1.062709 |
if alias not in settings.BACKENDS:
raise VCSError("Given alias '%s' is not recognized! Allowed aliases:\n"
"%s" % (alias, pformat(settings.BACKENDS.keys())))
backend_path = settings.BACKENDS[alias]
klass = import_class(backend_path)
return klass | def get_backend(alias) | Returns ``Repository`` class identified by the given alias or raises
VCSError if alias is not recognized or backend class cannot be imported. | 4.270243 | 3.372848 | 1.266065 |
if not os.path.isdir(path):
raise VCSError("Given path %s is not a directory" % path)
def get_scms(path):
return [(scm, path) for scm in get_scms_for_path(path)]
found_scms = get_scms(path)
while not found_scms and search_up:
newpath = abspath(path, '..')
if newpat... | def get_scm(path, search_up=False, explicit_alias=None) | Returns one of alias from ``ALIASES`` (in order of precedence same as
shortcuts given in ``ALIASES``) and top working dir path for the given
argument. If no scm-specific directory is found or more than one scm is
found at that directory, ``VCSError`` is raised.
:param search_up: if set to ``True``, thi... | 2.209114 | 2.273961 | 0.971483 |
from vcs.backends import get_backend
if hasattr(path, '__call__'):
path = path()
if not os.path.isdir(path):
raise VCSError("Given path %r is not a directory" % path)
result = []
for key in ALIASES:
dirname = os.path.join(path, '.' + key)
if os.path.isdir(dirnam... | def get_scms_for_path(path) | Returns all scm's found at the given path. If no scm is recognized
- empty list is returned.
:param path: path to directory which should be checked. May be callable.
:raises VCSError: if given ``path`` is not a directory | 4.657053 | 4.100248 | 1.135798 |
repo_paths = []
dirnames = (os.path.abspath(dirname) for dirname in os.listdir(path))
for dirname in dirnames:
try:
get_scm(dirname)
repo_paths.append(dirname)
except VCSError:
pass
return repo_paths | def get_repo_paths(path) | Returns path's subdirectories which seems to be a repository. | 3.310885 | 3.039189 | 1.089397 |
command = ' '.join((cmd, args))
p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
return p.retcode, stdout, stderr | def run_command(cmd, *args) | Runs command on the system with given ``args``. | 2.820014 | 2.749024 | 1.025824 |
import logging
try:
import pygments
pygments
except ImportError:
return code
from pygments import highlight
from pygments.lexers import guess_lexer_for_filename, ClassNotFound
from pygments.formatters import TerminalFormatter
try:
lexer = guess_lexer_for... | def get_highlighted_code(name, code, type='terminal') | If pygments are available on the system
then returned output is colored. Otherwise
unchanged content is returned. | 2.811557 | 2.528487 | 1.111952 |
text = text.strip()
CID_RE = r'[a-zA-Z0-9]+'
if not '..' in text:
m = re.match(r'^(?P<cid>%s)$' % CID_RE, text)
if m:
return {
'start': None,
'main': text,
'end': None,
}
else:
RE = r'^(?P<start>%s)?\.{2... | def parse_changesets(text) | Returns dictionary with *start*, *main* and *end* ids.
Examples::
>>> parse_changesets('aaabbb')
{'start': None, 'main': 'aaabbb', 'end': None}
>>> parse_changesets('aaabbb..cccddd')
{'start': 'aaabbb', 'main': None, 'end': 'cccddd'} | 3.21266 | 2.800304 | 1.147254 |
text = text.strip().lower()
INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M',
'%Y-%m-%d',
'%m/%d/%Y %H:%M:%S',
'%m/%d/%Y %H:%M',
'%m/%d/%Y',
'%m/%d/%y %H:%M:%S',
'%m/%d/%y %H:%M',
'%m/%d/%y',
)
for format in INPUT_FORM... | def parse_datetime(text) | Parses given text and returns ``datetime.datetime`` instance or raises
``ValueError``.
:param text: string of desired date/datetime or something more verbose,
like *yesterday*, *2weeks 3days*, etc. | 1.842251 | 1.82456 | 1.009696 |
data = {}
for attr in attrs:
data[attr] = getattr(obj, attr)
return data | def get_dict_for_attrs(obj, attrs) | Returns dictionary for each attribute from given ``obj``. | 2.512358 | 2.389539 | 1.051398 |
r
# way faster than calling bernoulli.logpmf
y, f = np.broadcast_arrays(y, f)
ll = y * f - softplus(f)
return ll | def loglike(self, y, f) | r"""
Bernoulli log likelihood.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
-------
l... | 7.589074 | 8.105907 | 0.93624 |
r
ll = binom.logpmf(y, n=n, p=expit(f))
return ll | def loglike(self, y, f, n) | r"""
Binomial log likelihood.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
n: ndarray
the total nu... | 10.030174 | 9.463281 | 1.059905 |
r
y, f, n = np.broadcast_arrays(y, f, n)
return y - expit(f) * n | def df(self, y, f, n) | r"""
Derivative of Binomial log likelihood w.r.t.\ f.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
n: ndarray... | 6.830131 | 10.213004 | 0.668768 |
r
return binom.cdf(y, n=n, p=expit(f)) | def cdf(self, y, f, n) | r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
n: ndarra... | 14.409331 | 18.287327 | 0.787941 |
r
# way faster than calling norm.logpdf
var = self._check_param(var)
y, f = np.broadcast_arrays(y, f)
ll = - 0.5 * (np.log(2 * np.pi * var) + (y - f)**2 / var)
return ll | def loglike(self, y, f, var=None) | r"""
Gaussian log likelihood.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
var: float, ndarray, optional
... | 4.520569 | 4.783674 | 0.944999 |
r
var = self._check_param(var)
y, f = np.broadcast_arrays(y, f)
return (y - f) / var | def df(self, y, f, var) | r"""
Derivative of Gaussian log likelihood w.r.t.\ f.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
var: float... | 5.525439 | 6.951755 | 0.794827 |
r
var = self._check_param(var)
y, f = np.broadcast_arrays(y, f)
ivar = 1. / var
return 0.5 * (((y - f) * ivar)**2 - ivar) | def dp(self, y, f, var) | r"""
Derivative of Gaussian log likelihood w.r.t.\ the variance
:math:`\sigma^2`.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\... | 5.117624 | 5.700579 | 0.897738 |
r
var = self._check_param(var)
return norm.cdf(y, loc=f, scale=np.sqrt(var)) | def cdf(self, y, f, var) | r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
var: floa... | 6.885987 | 7.941594 | 0.867079 |
r
y, f = np.broadcast_arrays(y, f)
if self.tranfcn == 'exp':
g = np.exp(f)
logg = f
else:
g = softplus(f)
logg = np.log(g)
return y * logg - g - gammaln(y + 1) | def loglike(self, y, f) | r"""
Poisson log likelihood.
Parameters
----------
y: ndarray
array of integer targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
-------
logp: ndarray
... | 4.30238 | 5.282205 | 0.814505 |
r
return np.exp(f) if self.tranfcn == 'exp' else softplus(f) | def Ey(self, f) | r"""
Expected value of the Poisson likelihood.
Parameters
----------
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
-------
Ey: ndarray
expected value of y, :math:`\math... | 17.699551 | 28.633247 | 0.618147 |
r
y, f = np.broadcast_arrays(y, f)
if self.tranfcn == 'exp':
return y - np.exp(f)
else:
return expit(f) * (y / safesoftplus(f) - 1) | def df(self, y, f) | r"""
Derivative of Poisson log likelihood w.r.t.\ f.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
... | 9.869436 | 12.541546 | 0.786939 |
r
mu = np.exp(f) if self.tranfcn == 'exp' else softplus(f)
return poisson.cdf(y, mu=mu) | def cdf(self, y, f) | r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
... | 12.237338 | 17.116879 | 0.714928 |
if state_size_changed:
self.state = deque(repeat('', self.state_size),
maxlen=self.state_size)
else:
self.state.extend(repeat('', self.state_size))
self.end = True | def reset(self, state_size_changed=False) | Reset parser state.
Parameters
----------
state_size_changed : `bool`, optional
`True` if maximum state size changed (default: `False`). | 4.036612 | 4.454396 | 0.906208 |
data = super().save()
data['state_sizes'] = self.state_sizes
data['reset_on_sentence_end'] = self.reset_on_sentence_end
return data | def save(self) | Convert to JSON.
Returns
-------
`dict`
JSON data. | 4.912184 | 5.507489 | 0.89191 |
data = super().save()
data['levels'] = self.levels
if self.parsers is None:
data['parsers'] = None
else:
data['parsers'] = [parser.save() for parser in self.parsers]
return data | def save(self) | Convert to JSON.
Returns
-------
`dict`
JSON data. | 3.226583 | 3.511882 | 0.918762 |
size = hues * saturations * values
if size > 256:
raise ValueError('palette size > 256: {0}'.format(size))
if min(hues, saturations, values) < 1:
raise ValueError('invalid palette size: {0} {1} {2}'
.format(hues, saturations, values))
ret = []
if hues =... | def palette(hues, saturations, values) | Generate a palette.
Parameters
----------
hues : `int`
Number of hues.
saturations : `int`
Number of saturations.
values : `int`
Number of values.
Raises
------
ValueError
If `hues` * `saturations` * `values` > 256
or min(`hues`, `saturations`, `... | 2.251216 | 2.126737 | 1.05853 |
if ctype == 0:
img2 = img.convert(mode='P')
img2.putpalette(palette_img.getpalette())
return img2
img.load()
palette_img.load()
if palette_img.palette is None:
raise ValueError('invalid palette image')
im = img.im.convert('P', int(dither), palette_img.im)
re... | def convert(ctype, img, palette_img, dither=False) | Convert an image to palette type.
Parameters
----------
ctype : `int`
Conversion type.
img : `PIL.Image`
Image to convert.
palette_img : `PIL.Image`
Palette source image.
dither : `bool`, optional
Enable dithering (default: `False`).
Raises
------
Va... | 3.559279 | 3.582917 | 0.993403 |
def unescape(c):
return {
"\\\\": "\\",
"\\\"": "\"",
"\\n": "\n",
"\\t": "\t",
"\\b": "\b",
}[c.group(0)]
return re.sub(r"(\\.)", unescape, value) | def _unescape_value(value) | Unescape a value. | 3.658204 | 3.570286 | 1.024625 |
try:
value = self.get(section, name)
except KeyError:
return default
if value.lower() == "true":
return True
elif value.lower() == "false":
return False
raise ValueError("not a valid boolean string: %r" % value) | def get_boolean(self, section, name, default=None) | Retrieve a configuration setting as boolean.
:param section: Tuple with section name and optional subsection namee
:param name: Name of the setting, including section and possible
subsection.
:return: Contents of the setting
:raise KeyError: if the value is not set | 2.45867 | 2.606288 | 0.943361 |
ret = cls()
section = None
setting = None
for lineno, line in enumerate(f.readlines()):
line = line.lstrip()
if setting is None:
if _strip_comments(line).strip() == "":
continue
if line[0] == "[":
... | def from_file(cls, f) | Read configuration from a file-like object. | 2.227297 | 2.201461 | 1.011736 |
f = GitFile(path, 'rb')
try:
ret = cls.from_file(f)
ret.path = path
return ret
finally:
f.close() | def from_path(cls, path) | Read configuration from a file on disk. | 3.832896 | 3.772653 | 1.015968 |
if path is None:
path = self.path
f = GitFile(path, 'wb')
try:
self.write_to_file(f)
finally:
f.close() | def write_to_path(self, path=None) | Write configuration to a file on disk. | 3.229072 | 3.179724 | 1.015519 |
for section, values in self._values.iteritems():
try:
section_name, subsection_name = section
except ValueError:
(section_name, ) = section
subsection_name = None
if subsection_name is None:
f.write("[%s... | def write_to_file(self, f) | Write configuration to a file-like object. | 2.172515 | 2.124615 | 1.022546 |
paths = []
paths.append(os.path.expanduser("~/.gitconfig"))
paths.append("/etc/gitconfig")
backends = []
for path in paths:
try:
cf = ConfigFile.from_path(path)
except (IOError, OSError), e:
if e.errno != errno.ENOE... | def default_backends(cls) | Retrieve the default configuration.
This will look in the repository configuration (if for_path is
specified), the users' home directory and the system
configuration. | 2.796144 | 2.789108 | 1.002523 |
generator = check_random_state(random_state)
X = generator.randn(n_samples, n_features)
# unpack the columns of X
y = func(*X.T) + bias
if noise > 0.0:
y += generator.normal(scale=noise, size=y.shape)
return X, y | def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0,
random_state=None) | Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape
(100, 1)
>>> y.shape
(100,)
>>> X[:5].round(2)
array([[ 1.62],
[-0.61],
[-0.53],
... | 2.708748 | 4.684289 | 0.578262 |
generator = check_random_state(random_state)
# TODO: Add arguments to support other priors
coefs = generator.randn(degree + 1)
pows = np.arange(degree + 1)
poly = np.vectorize(lambda x: np.sum(coefs * x ** pows))
X, y = make_regression(poly, n_samples=n_samples, bias=bias, noise=noise,
... | def make_polynomial(degree=3, n_samples=100, bias=0.0, noise=0.0,
return_coefs=False, random_state=None) | Generate a noisy polynomial for a regression problem
Examples
--------
>>> X, y, coefs = make_polynomial(degree=3, n_samples=200, noise=.5,
... return_coefs=True, random_state=1) | 2.861398 | 3.501883 | 0.817103 |
data_home_default = Path(__file__).ancestor(3).child('demos',
'_revrand_data')
if data_home is None:
data_home = os.environ.get('REVRAND_DATA', data_home_default)
if not os.path.exists(data_home):
os.makedirs(data_home)
ret... | def get_data_home(data_home=None) | Return the path of the revrand data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'revrand_data'
in the user home folder.
Alternatively, it can be set by the 'REVRAND_DATA' environment
varia... | 3.762153 | 3.369218 | 1.116625 |
train_src_url = "http://www.gaussianprocess.org/gpml/data/sarcos_inv.mat"
test_src_url = ("http://www.gaussianprocess.org/gpml/data/sarcos_inv_test"
".mat")
data_home = get_data_home(data_home=data_home)
train_filename = os.path.join(data_home, 'sarcos_inv.mat')
test_filen... | def fetch_gpml_sarcos_data(transpose_data=True, data_home=None) | Fetch the SARCOS dataset from the internet and parse appropriately into
python arrays
>>> gpml_sarcos = fetch_gpml_sarcos_data()
>>> gpml_sarcos.train.data.shape
(44484, 21)
>>> gpml_sarcos.train.targets.shape
(44484,)
>>> gpml_sarcos.train.targets.round(2) # doctest: +ELLIPSIS
array... | 1.640962 | 1.762528 | 0.931027 |
data_home = get_data_home(data_home=data_home)
data_filename = os.path.join(data_home,
'usps_resampled/usps_resampled.mat')
if not os.path.exists(data_filename):
r = requests.get('http://www.gaussianprocess.org/gpml/data/'
'usps_resamp... | def fetch_gpml_usps_resampled_data(transpose_data=True, data_home=None) | Fetch the USPS handwritten digits dataset from the internet and parse
appropriately into python arrays
>>> usps_resampled = fetch_gpml_usps_resampled_data()
>>> usps_resampled.train.targets.shape
(4649,)
>>> usps_resampled.train.targets # doctest: +ELLIPSIS
array([6, 0, 1, ..., 9, 2, 7])
... | 1.851243 | 1.967258 | 0.941027 |
# Xtrain = np.linspace(xmin, xmax, ntrain)[:, np.newaxis]
Xtrain = np.random.rand(ntrain)[:, np.newaxis] * (xmin - xmax) - xmin
Xtest = np.linspace(xmin, xmax, ntest)[:, np.newaxis]
Xcat = np.vstack((Xtrain, Xtest))
K = scale * np.exp(-cdist(Xcat, Xcat, metric='sqeuclidean') /
... | def gen_gausprocess_se(ntrain, ntest, noise=1., lenscale=1., scale=1.,
xmin=-10, xmax=10) | Generate a random (noisy) draw from a Gaussian Process with a RBF kernel. | 2.226071 | 2.218152 | 1.00357 |
if self.state_separator:
return state.split(self.state_separator)
return list(state) | def split_state(self, state) | Split state string.
Parameters
----------
state : `str`
Returns
-------
`list` of `str` | 4.50105 | 5.289429 | 0.850952 |
links = self.get_links(dataset, state, backward)
if not links:
return None, None
x = randint(0, sum(link[0] for link in links) - 1)
for link in links:
count = link[0]
if x < count:
return link[1], self.follow_link(link, state, ... | def random_link(self, dataset, state, backward=False) | Get a random link.
Parameters
----------
dataset : `object`
Dataset from `self.get_dataset()`.
state : `object`
Link source.
backward : `bool`, optional
Link direction.
Raises
------
ValueError
If link coun... | 3.477422 | 3.482264 | 0.998609 |
if isinstance(state, str):
state = self.split_state(state)
state = self.get_state(state, size)
dataset = self.get_dataset(dataset)
while True:
link, state = self.random_link(dataset, state, backward)
if link is None or backward and link == '':... | def generate(self, state, size, dataset, backward=False) | Generate a sequence.
Parameters
----------
state : `str` or `iterable` of `str`
Initial state.
size : `int`
State size.
dataset : `str`
Dataset key.
backward : `bool`, optional
Link direction.
Returns
-----... | 4.268915 | 3.851066 | 1.108502 |
self.settings['storage'] = {
'state_separator': self.state_separator
}
self.do_save(fp) | def save(self, fp=None) | Update settings JSON data and save to file.
Parameters
----------
fp : `file` or `str`, optional
Output file. | 10.838861 | 13.492234 | 0.803341 |
self.check_integrity(parents)
from .repository import MercurialRepository
if not isinstance(message, unicode) or not isinstance(author, unicode):
raise RepositoryError('Given message and author needs to be '
'an <unicode> instance got %r & ... | def commit(self, message, author, parents=None, branch=None, date=None,
**kwargs) | Performs in-memory commit (doesn't check workdir in any way) and
returns newly created ``Changeset``. Updates repository's
``revisions``.
:param message: message of the commit
:param author: full username, i.e. "Joe Doe <joe.doe@example.com>"
:param parents: single parent or seq... | 4.362319 | 4.4025 | 0.990873 |
try:
bytes = float(bytes)
except (TypeError, ValueError, UnicodeDecodeError):
return '0%sB' % sep
if bytes < 1024:
size = bytes
template = '%.0f%sB'
elif bytes < 1024 * 1024:
size = bytes / 1024
template = '%.0f%sKB'
elif bytes < 1024 * 1024 * 10... | def filesizeformat(bytes, sep=' ') | Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 B, 2.3 GB etc).
Grabbed from Django (http://www.djangoproject.com), slightly modified.
:param bytes: size in bytes (as integer)
:param sep: string separator between number and abbreviation | 1.591466 | 1.638826 | 0.971101 |
code_list = []
if text == '' and len(opts) == 1 and opts[0] == 'reset':
return '\x1b[%sm' % RESET
for k, v in kwargs.iteritems():
if k == 'fg':
code_list.append(foreground[v])
elif k == 'bg':
code_list.append(background[v])
for o in opts:
if o... | def colorize(text='', opts=(), **kwargs) | Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid option... | 2.486835 | 2.386261 | 1.042147 |
if not config_string:
return PALETTES[DEFAULT_PALETTE]
# Split the color configuration into parts
parts = config_string.lower().split(';')
palette = PALETTES[NOCOLOR_PALETTE].copy()
for part in parts:
if part in PALETTES:
# A default palette has been specified
... | def parse_color_setting(config_string) | Parse a DJANGO_COLORS environment variable to produce the system palette
The general form of a pallete definition is:
"palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option"
where:
palette is a named palette; one of 'light', 'dark', or 'nocolor'.
role is a named st... | 4.831995 | 4.516495 | 1.069855 |
r
def coupled(*args, **kwargs):
return f(*args, **kwargs), g(*args, **kwargs)
return coupled | def couple(f, g) | r"""
Compose a function thate returns two arguments.
Given a pair of functions that take the same arguments, return a
single function that returns a pair consisting of the return values
of each function.
Notes
-----
Equivalent to::
lambda f, g: lambda *args, **kwargs: (f(*args, **... | 4.611275 | 5.706423 | 0.808085 |
def fst(*args, **kwargs):
return fn(*args, **kwargs)[0]
def snd(*args, **kwargs):
return fn(*args, **kwargs)[1]
return fst, snd | def decouple(fn) | Inverse operation of couple.
Create two functions of one argument and one return from a function that
takes two arguments and has two returns
Examples
--------
>>> h = lambda x: (2*x**3, 6*x**2)
>>> f, g = decouple(h)
>>> f(5)
250
>>> g(5)
150 | 2.301813 | 3.922275 | 0.586857 |
r
iters = tee(iterable, n)
for i, it in enumerate(iters):
for _ in range(i):
next(it, None)
return zip(*iters) | def nwise(iterable, n) | r"""
Sliding window iterator.
Iterator that acts like a sliding window of size `n`; slides over
some iterable `n` items at a time. If iterable has `m` elements,
this function will return an iterator over `m-n+1` tuples.
Parameters
----------
iterable : iterable
An iterable object.
... | 3.570916 | 2.801787 | 1.274514 |
if newshape == ():
return np.asscalar(a)
if newshape == (0,):
return []
return np.reshape(a, newshape, order) | def scalar_reshape(a, newshape, order='C') | Reshape, but also return scalars or empty lists.
Identical to `numpy.reshape` except in the case where `newshape` is
the empty tuple, in which case we return a scalar instead of a
0-dimensional array.
Examples
--------
>>> a = np.arange(6)
>>> np.array_equal(np.reshape(a, (3, 2)), scalar_r... | 3.282802 | 3.999476 | 0.820808 |
r
if isinstance(shapes, list):
sizes = list(map(sumprod, shapes))
ends = np.cumsum(sizes)
begs = np.concatenate(([0], ends[:-1]))
struct_arys = [unflatten(ary[b:e], s, reshape=reshape)
for b, e, s in zip(begs, ends, shapes)]
return struct_arys
e... | def unflatten(ary, shapes, reshape=scalar_reshape) | r"""
Inverse opertation of flatten.
Given a flat (1d) array, and a list of shapes (represented as tuples),
return a list of ndarrays with the specified shapes.
Parameters
----------
ary : a 1d array
A flat (1d) array.
shapes : list of tuples
A list of ndarray shapes (tuple... | 3.116603 | 3.765248 | 0.827729 |
if isinstance(seq, tuple):
# important to make sure dtype is int
# since prod on empty tuple is a float (1.0)
return np.prod(seq, dtype=int)
else:
return np.sum((sumprod(s) for s in seq), dtype=int) | def sumprod(seq) | Product of tuple, or sum of products of lists of tuples.
Parameters
----------
seq : tuple or list
Returns
-------
int :
the product of input tuples, or the sum of products of lists of tuples,
recursively.
Examples
--------
>>> tup = (1, 2, 3)
>>> sumprod(tup)
... | 5.746767 | 5.967896 | 0.962947 |
def applyormap(it):
if issequence(it):
return map_recursive(fn, it, output_type)
else:
return fn(it)
applied = map(applyormap, iterable)
return output_type(applied) if output_type else applied | def map_recursive(fn, iterable, output_type=None) | Apply a function of a potentially nested list of lists.
Parameters
----------
fn : callable
The function to apply to each element (and sub elements) in iterable
iterable : iterable
An iterable, sequence, sequence of sequences etc. :code:`fn` will be
applied to each element in ea... | 3.792968 | 5.897511 | 0.643147 |
r
index_set = set(indices)
for i, arg in enumerate(iterable):
if i in index_set:
yield fn(arg)
else:
yield arg | def map_indices(fn, iterable, indices) | r"""
Map a function across indices of an iterable.
Notes
-----
Roughly equivalent to, though more efficient than::
lambda fn, iterable, *indices: (fn(arg) if i in indices else arg
for i, arg in enumerate(iterable))
Examples
--------
>>> a =... | 3.918248 | 5.852675 | 0.66948 |
archivers = {
'tar': TarArchiver,
'tbz2': Tbz2Archiver,
'tgz': TgzArchiver,
'zip': ZipArchiver,
}
return archivers[kind]() | def get_archiver(self, kind) | Returns instance of archiver class specific to given kind
:param kind: archive kind | 2.654621 | 2.721536 | 0.975413 |
@wraps(func)
def new_init(self, *args, **kwargs):
apply_ind = kwargs.pop('apply_ind', None)
if np.isscalar(apply_ind):
apply_ind = [apply_ind]
func(self, *args, **kwargs)
self.apply_ind = apply_ind
return new_init | def slice_init(func) | Decorator for adding partial application functionality to a basis object.
This will add an "apply_ind" argument to a basis object initialiser that
can be used to apply the basis function to only the dimensions specified in
apply_ind. E.g.,
>>> X = np.ones((100, 20))
>>> base = LinearBasis(onescol=... | 2.597086 | 2.466192 | 1.053075 |
X = X if self.apply_ind is None else X[:, self.apply_ind]
return func(self, X, *vargs, **kwargs) | def slice_transform(func, self, X, *vargs, **kwargs) | Decorator for implementing partial application.
This must decorate the ``transform`` and ``grad`` methods of basis objects
if the ``slice_init`` decorator was used. | 3.942798 | 5.041852 | 0.782014 |
if issequence(grad):
fgrad = [apply_grad(fun, g) for g in grad]
return fgrad if len(fgrad) != 1 else fgrad[0]
elif len(grad) == 0:
return []
elif (grad.ndim == 1) or (grad.ndim == 2):
return fun(grad)
elif grad.ndim == 3:
return np.array([fun(grad[:, :, i]) f... | def apply_grad(fun, grad) | Apply a function that takes a gradient matrix to a sequence of 2 or 3
dimensional gradients.
This is partucularly useful when the gradient of a basis concatenation
object is quite complex, eg.
>>> X = np.random.randn(100, 3)
>>> y = np.random.randn(100)
>>> N, d = X.shape
>>> base = Random... | 2.594517 | 2.580214 | 1.005543 |
# Cache
if not hasattr(self, '_D'):
self._D = self.transform(X[[0]], *self.params_values()).shape[1]
return self._D | def get_dim(self, X) | Get the output dimensionality of this basis.
This makes a cheap call to transform with the initial parameter values
to ascertain the dimensionality of the output features.
Parameters
----------
X : ndarray
(N, d) array of observations where N is the number of sample... | 7.722475 | 7.295733 | 1.058492 |
return [p.value for p in atleast_list(self.params) if p.has_value] | def params_values(self) | Get a list of the ``Parameter`` values if they have a value.
This does not include the basis regularizer. | 8.829831 | 7.327005 | 1.205108 |
r
reg = self.regularizer.value if regularizer is None else regularizer
diag = np.full(self.get_dim(X), reg, dtype=float)
return diag, slice(None) | def regularizer_diagonal(self, X, regularizer=None) | r"""
Get the diagonal of the prior variance on the weights (regularizer).
This also returns a slice into the regression weights to which this
regularizer applies.
Parameters
----------
X : ndarray
(N, d) array of observations where N is the number of samples... | 6.692374 | 5.6591 | 1.182586 |
N = len(X)
return np.ones((N, 1)) * self.offset | def transform(self, X) | Return this basis applied to X.
Parameters
----------
X: ndarray
of shape (N, d) of observations where N is the number of samples,
and d is the dimensionality of X.
Returns
-------
ndarray:
of shape (N, 1) of ones * self.offset. | 5.936 | 5.04926 | 1.175618 |
N, D = X.shape
return np.hstack((np.ones((N, 1)), X)) if self.onescol else X | def transform(self, X) | Return this basis applied to X.
Parameters
----------
X: ndarray
of shape (N, d) of observations where N is the number of samples,
and d is the dimensionality of X.
Returns
-------
ndarray:
of shape (N, d+1), or (N, d) depending on on... | 4.863277 | 4.150073 | 1.171854 |
N, D = X.shape
pow_arr = np.arange(self.order) + 1
# Polynomial terms
Phi = X[:, :, np.newaxis] ** pow_arr
# Flatten along last axes
Phi = Phi.reshape(N, D * self.order)
# Prepend intercept
if self.include_bias:
Phi = np.hstack((np... | def transform(self, X) | Return this basis applied to X.
Parameters
----------
X: ndarray
of shape (N, d) of observations where N is the number of samples,
and d is the dimensionality of X.
Returns
-------
ndarray:
of shape (N, d*order+1), the extra 1 is from... | 6.850135 | 7.038477 | 0.973241 |
N, d = X.shape
lenscale = self._check_dim(d, lenscale)
den = (2 * lenscale**2)
return np.exp(- cdist(X / den, self.C / den, 'sqeuclidean')) | def transform(self, X, lenscale=None) | Apply the RBF to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
scalar or array of shape (d,) length scales (one for each dimen... | 6.506996 | 7.474648 | 0.870542 |
r
N, d = X.shape
lenscale = self._check_dim(d, lenscale)
Phi = self.transform(X, lenscale)
dPhi = []
for i, l in enumerate(lenscale):
ldist = cdist(X[:, [i]] / l**3, self.C[:, [i]] / l**3,
'sqeuclidean')
dPhi.append(Phi *... | def grad(self, X, lenscale=None) | r"""
Get the gradients of this basis w.r.t.\ the length scale.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
scalar or ar... | 4.787761 | 5.255243 | 0.911045 |
r
N, d = X.shape
lenscale = self._check_dim(d, lenscale)
return expit(cdist(X / lenscale, self.C / lenscale, 'euclidean')) | def transform(self, X, lenscale=None) | r"""
Apply the sigmoid basis function to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: float
the length scale (scalar) of the RBFs to apply to X. ... | 8.259115 | 11.517202 | 0.717111 |
N, D = X.shape
lenscale = self._check_dim(D, lenscale)[:, np.newaxis]
WX = np.dot(X, self.W / lenscale)
return np.hstack((np.cos(WX), np.sin(WX))) / np.sqrt(self.n) | def transform(self, X, lenscale=None) | Apply the random basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
scalar or array of shape (d,) length scales (one for e... | 4.381389 | 5.444464 | 0.804742 |
r
N, D = X.shape
lenscale = self._check_dim(D, lenscale)[:, np.newaxis]
WX = np.dot(X, self.W / lenscale)
sinWX = - np.sin(WX)
cosWX = np.cos(WX)
dPhi = []
for i, l in enumerate(lenscale):
dWX = np.outer(X[:, i], - self.W[i, :] / l**2)
... | def grad(self, X, lenscale=None) | r"""
Get the gradients of this basis w.r.t.\ the length scales.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
scalar or a... | 4.200637 | 4.539289 | 0.925396 |
lenscale = self._check_dim(X.shape[1], lenscale)
VX = self._makeVX(X / lenscale)
Phi = np.hstack((np.cos(VX), np.sin(VX))) / np.sqrt(self.n)
return Phi | def transform(self, X, lenscale=None) | Apply the Fast Food RBF basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
scalar or array of shape (d,) length scales (on... | 5.743408 | 7.021209 | 0.818008 |
r
d = X.shape[1]
lenscale = self._check_dim(d, lenscale)
VX = self._makeVX(X / lenscale)
sinVX = - np.sin(VX)
cosVX = np.cos(VX)
dPhi = []
for i, l in enumerate(lenscale):
indlen = np.zeros(d)
indlen[i] = 1. / l**2
dVX... | def grad(self, X, lenscale=None) | r"""
Get the gradients of this basis w.r.t.\ the length scale.
Parameters
----------
x: ndarray
(n, d) array of observations where n is the number of samples, and
d is the dimensionality of x.
lenscale: scalar or ndarray
scalar or array of sha... | 5.127892 | 5.219046 | 0.982534 |
mean = self._check_dim(X.shape[1], mean, paramind=0)
lenscale = self._check_dim(X.shape[1], lenscale, paramind=1)
VX = self._makeVX(X / lenscale)
mX = X.dot(mean)[:, np.newaxis]
Phi = np.hstack((np.cos(VX + mX), np.sin(VX + mX),
np.cos(VX - mX),... | def transform(self, X, mean=None, lenscale=None) | Apply the spectral mixture component basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
mean: ndarray, optional
array of shape (d,) frequency means (one for eac... | 3.809711 | 4.035394 | 0.944074 |
r
d = X.shape[1]
mean = self._check_dim(d, mean, paramind=0)
lenscale = self._check_dim(d, lenscale, paramind=1)
VX = self._makeVX(X / lenscale)
mX = X.dot(mean)[:, np.newaxis]
sinVXpmX = - np.sin(VX + mX)
sinVXmmX = - np.sin(VX - mX)
cosVXpmX = ... | def grad(self, X, mean=None, lenscale=None) | r"""
Get the gradients of this basis w.r.t.\ the mean and length scales.
Parameters
----------
x: ndarray
(n, d) array of observations where n is the number of samples, and
d is the dimensionality of x.
mean: ndarray, optional
array of shape (... | 2.93369 | 2.959036 | 0.991434 |
Phi = []
args = list(params)
for base in self.bases:
phi, args = base._transform_popargs(X, *args)
Phi.append(phi)
return np.hstack(Phi) | def transform(self, X, *params) | Return the basis function applied to X.
I.e. Phi(X, params), where params can also optionally be used and
learned.
Parameters
----------
X : ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
... | 6.646137 | 8.206591 | 0.809854 |
# Establish a few dimensions
N = X.shape[0]
D = self.get_dim(X)
endinds = self.__base_locations(X) # for the Padding indices
args = list(params)
# Generate structured gradients with appropriate zero padding
def make_dPhi(i, g):
# Pad the gr... | def grad(self, X, *params) | Return the gradient of the basis function for each parameter.
Parameters
----------
X : ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
*params : optional
parameter aguments, these are the param... | 7.799942 | 7.641012 | 1.0208 |
r
regularizer = repeat(None) if regularizer is () else regularizer
regs, _ = zip(*(b.regularizer_diagonal(X, r)
for b, r in zip(self.bases, regularizer)))
if self.__slices is None:
baseinds = self.__base_locations(X)
self.__slices = [slice... | def regularizer_diagonal(self, X, *regularizer) | r"""
Get the diagonal of the prior variance on the weights (regularizer).
This also returns a slice into the regression weights to which all of
the concatenated bases' regularizers applies.
Parameters
----------
X : ndarray
(N, d) array of observations where... | 5.193119 | 5.420744 | 0.958009 |
paramlist = [b.params for b in self.bases if b.params.has_value]
if len(paramlist) == 0:
return Parameter()
else:
return paramlist if len(paramlist) > 1 else paramlist[0] | def params(self) | Return a list of all of the ``Parameter`` objects.
Or a just a single ``Parameter`` is there is only one, and single empty
``Parameter`` if there are no parameters. | 4.612178 | 4.19426 | 1.099641 |
try:
filenode_old_date = filenode_old.changeset.date
except NodeError:
filenode_old_date = None
try:
filenode_new_date = filenode_new.changeset.date
except NodeError:
filenode_new_date = None
for filenode in (filenode_old, filenode_new):
if not isinstan... | def get_udiff(filenode_old, filenode_new, show_whitespace=True) | Returns unified diff between given ``filenode_old`` and ``filenode_new``. | 2.513256 | 2.476975 | 1.014647 |
for filenode in (filenode_old, filenode_new):
if not isinstance(filenode, FileNode):
raise VCSError("Given object should be FileNode object, not %s"
% filenode.__class__)
old_raw_id = getattr(filenode_old.changeset, 'raw_id', '0' * 40)
new_raw_id = getattr(filenode... | def get_gitdiff(filenode_old, filenode_new, ignore_whitespace=True) | Returns git style diff between given ``filenode_old`` and ``filenode_new``.
:param ignore_whitespace: ignore whitespaces in diff | 2.702063 | 2.892465 | 0.934173 |
self.__udiff, iterator_copy = itertools.tee(self.__udiff)
return iterator_copy | def copy_iterator(self) | make a fresh copy of generator, we should not iterate thru
an original as it's needed for repeating operations on
this instance of DiffProcessor | 13.185922 | 9.315537 | 1.415476 |
try:
if line1.startswith('--- ') and line2.startswith('+++ '):
l1 = line1[4:].split(None, 1)
old_filename = l1[0].lstrip('a/') if len(l1) >= 1 else None
old_rev = l1[1] if len(l1) == 2 else 'old'
l2 = line2[4:].split(None, 1)... | def _extract_rev(self, line1, line2) | Extract the filename and revision hint from a line. | 2.362343 | 2.323262 | 1.016822 |
if line['action'] == 'del':
old, new = line, next
else:
old, new = next, line
oldwords = re.split(r'(\W)', old['line'])
newwords = re.split(r'(\W)', new['line'])
sequence = difflib.SequenceMatcher(None, oldwords, newwords)
oldfragments... | def _highlight_line_difflib(self, line, next) | Highlight inline changes in both lines. | 2.013946 | 1.971269 | 1.021649 |
start = 0
limit = min(len(line['line']), len(next['line']))
while start < limit and line['line'][start] == next['line'][start]:
start += 1
end = -1
limit -= start
while -end <= limit and line['line'][end] == next['line'][end]:
end -= 1
... | def _highlight_line_udiff(self, line, next) | Highlight inline changes in both lines. | 2.711863 | 2.594426 | 1.045265 |
lineiter = self.lines
files = []
try:
line = lineiter.next()
# skip first context
skipfirst = True
while 1:
# continue until we found the old file
if not line.startswith('--- '):
line = l... | def _parse_udiff(self) | Parse the diff an return data for the template. | 2.797059 | 2.744177 | 1.019271 |
# Transform all whitespace to underscore
idstring = re.sub(r'\s', "_", '%s' % idstring)
# Remove everything that is not a hyphen or a member of \w
idstring = re.sub(r'(?!-)\W', "", idstring).lower()
return idstring | def _safe_id(self, idstring) | Make a string safe for including in an id attribute.
The HTML spec says that id attributes 'must begin with
a letter ([A-Za-z]) and may be followed by any number
of letters, digits ([0-9]), hyphens ("-"), underscores
("_"), colons (":"), and periods (".")'. These regexps
are sli... | 5.257431 | 4.042206 | 1.300634 |
udiff_copy = self.copy_iterator()
if self.__format == 'gitdiff':
udiff_copy = self._parse_gitdiff(udiff_copy)
return u''.join(udiff_copy) | def raw_diff(self) | Returns raw string as udiff | 8.029279 | 6.538478 | 1.228004 |
def _link_to_if(condition, label, url):
if condition:
return '''<a href="%(url)s">%(label)s</a>''' % {'url': url,
'label': label}
else:
return label
diff_lines =... | def as_html(self, table_class='code-difftable', line_class='line',
new_lineno_class='lineno old', old_lineno_class='lineno new',
code_class='code') | Return udiff as html table with customized css classes | 2.020254 | 2.012928 | 1.00364 |
'''Stores a navigator in the identity map for the current
api. Can take a link or a bare uri'''
if link is None:
return # We don't cache navigators without a Link
elif hasattr(link, 'uri'):
self.id_map[link.uri] = nav
else:
self.id_map[link] =... | def cache(self, link, nav) | Stores a navigator in the identity map for the current
api. Can take a link or a bare uri | 8.603031 | 3.51605 | 2.446788 |
'''Retrieves a cached navigator from the id_map.
Either a Link object or a bare uri string may be passed in.'''
if hasattr(link, 'uri'):
return self.id_map.get(link.uri, default)
else:
return self.id_map.get(link, default) | def get_cached(self, link, default=None) | Retrieves a cached navigator from the id_map.
Either a Link object or a bare uri string may be passed in. | 5.30218 | 1.962624 | 2.701577 |
'''Returns whether the current navigator is cached. Intended
to be overwritten and customized by subclasses.
'''
if link is None:
return False
elif hasattr(link, 'uri'):
return link.uri in self.id_map
else:
return link in self.id_map | def is_cached(self, link) | Returns whether the current navigator is cached. Intended
to be overwritten and customized by subclasses. | 6.877079 | 3.087668 | 2.227273 |
'''Returns the template uri expanded with the current arguments'''
kwargs = dict([(k, v if v != 0 else '0') for k, v in kwargs.items()])
return uritemplate.expand(self.link.uri, kwargs) | def expand_uri(self, **kwargs) | Returns the template uri expanded with the current arguments | 7.123205 | 5.038907 | 1.413641 |
'''Expands with the given arguments and returns a new
untemplated Link object
'''
props = self.link.props.copy()
del props['templated']
return Link(
uri=self.expand_uri(**kwargs),
properties=props,
) | def expand_link(self, **kwargs) | Expands with the given arguments and returns a new
untemplated Link object | 9.109182 | 4.848228 | 1.878868 |
'''Create a HALNavigator'''
root = utils.fix_scheme(root)
halnav = HALNavigator(
link=Link(uri=root),
core=APICore(
root=root,
nav_class=HALNavigator,
apiname=apiname,
default_curie=default_curie,
... | def hal(root,
apiname=None,
default_curie=None,
auth=None,
headers=None,
session=None,
) | Create a HALNavigator | 4.547993 | 4.103201 | 1.108401 |
doc_url = uritemplate.expand(self.curies[prefix], {'rel': _rel})
else:
doc_url = rel
print('opening', doc_url)
webbrowser.open(doc_url) | def docsfor(self, rel): # pragma: nocover
'''Obtains the documentation for a link relation. Opens in a webbrowser
window'''
prefix, _rel = rel.split(':')
if prefix in self.curies | Obtains the documentation for a link relation. Opens in a webbrowser
window | 3.975117 | 3.752403 | 1.059352 |
'''Creates linked navigators from a HAL response body'''
ld = utils.CurieDict(self._core.default_curie, {})
for rel, link in body.get('_links', {}).items():
if rel != 'curies':
if isinstance(link, list):
ld[rel] = utils.LinkList(
... | def _make_links_from(self, body) | Creates linked navigators from a HAL response body | 6.534649 | 5.041008 | 1.296298 |
'''Creates embedded navigators from a HAL response doc'''
ld = utils.CurieDict(self._core.default_curie, {})
for rel, doc in doc.get('_embedded', {}).items():
if isinstance(doc, list):
ld[rel] = [self._recursively_embed(d) for d in doc]
else:
... | def _make_embedded_from(self, doc) | Creates embedded navigators from a HAL response doc | 5.823171 | 4.16146 | 1.39931 |
'''Crafts a navigator from a hal-json embedded document'''
self_link = None
self_uri = utils.getpath(doc, '_links.self.href')
if self_uri is not None:
uri = urlparse.urljoin(self.uri, self_uri)
self_link = Link(
uri=uri,
properties=... | def _recursively_embed(self, doc, update_state=True) | Crafts a navigator from a hal-json embedded document | 3.25308 | 2.752431 | 1.181893 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.