repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jonathf/chaospy | chaospy/distributions/sampler/sequences/hammersley.py | create_hammersley_samples | def create_hammersley_samples(order, dim=1, burnin=-1, primes=()):
"""
Create samples from the Hammersley set.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Hammersley sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Hammersley sequence.
burnin (int):
Skip the first ``burnin`` samples. If negative, the maximum of
``primes`` is used.
primes (tuple):
The (non-)prime base to calculate values along each axis. If
empty, growing prime values starting from 2 will be used.
Returns:
(numpy.ndarray):
Hammersley set with ``shape == (dim, order)``.
"""
if dim == 1:
return create_halton_samples(
order=order, dim=1, burnin=burnin, primes=primes)
out = numpy.empty((dim, order), dtype=float)
out[:dim-1] = create_halton_samples(
order=order, dim=dim-1, burnin=burnin, primes=primes)
out[dim-1] = numpy.linspace(0, 1, order+2)[1:-1]
return out | python | def create_hammersley_samples(order, dim=1, burnin=-1, primes=()):
"""
Create samples from the Hammersley set.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Hammersley sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Hammersley sequence.
burnin (int):
Skip the first ``burnin`` samples. If negative, the maximum of
``primes`` is used.
primes (tuple):
The (non-)prime base to calculate values along each axis. If
empty, growing prime values starting from 2 will be used.
Returns:
(numpy.ndarray):
Hammersley set with ``shape == (dim, order)``.
"""
if dim == 1:
return create_halton_samples(
order=order, dim=1, burnin=burnin, primes=primes)
out = numpy.empty((dim, order), dtype=float)
out[:dim-1] = create_halton_samples(
order=order, dim=dim-1, burnin=burnin, primes=primes)
out[dim-1] = numpy.linspace(0, 1, order+2)[1:-1]
return out | [
"def",
"create_hammersley_samples",
"(",
"order",
",",
"dim",
"=",
"1",
",",
"burnin",
"=",
"-",
"1",
",",
"primes",
"=",
"(",
")",
")",
":",
"if",
"dim",
"==",
"1",
":",
"return",
"create_halton_samples",
"(",
"order",
"=",
"order",
",",
"dim",
"=",... | Create samples from the Hammersley set.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Hammersley sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Hammersley sequence.
burnin (int):
Skip the first ``burnin`` samples. If negative, the maximum of
``primes`` is used.
primes (tuple):
The (non-)prime base to calculate values along each axis. If
empty, growing prime values starting from 2 will be used.
Returns:
(numpy.ndarray):
Hammersley set with ``shape == (dim, order)``. | [
"Create",
"samples",
"from",
"the",
"Hammersley",
"set",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/hammersley.py#L29-L58 | train | 207,000 |
jonathf/chaospy | chaospy/distributions/sampler/sequences/primes.py | create_primes | def create_primes(threshold):
"""
Generate prime values using sieve of Eratosthenes method.
Args:
threshold (int):
The upper bound for the size of the prime values.
Returns (List[int]):
All primes from 2 and up to ``threshold``.
"""
if threshold == 2:
return [2]
elif threshold < 2:
return []
numbers = list(range(3, threshold+1, 2))
root_of_threshold = threshold ** 0.5
half = int((threshold+1)/2-1)
idx = 0
counter = 3
while counter <= root_of_threshold:
if numbers[idx]:
idy = int((counter*counter-3)/2)
numbers[idy] = 0
while idy < half:
numbers[idy] = 0
idy += counter
idx += 1
counter = 2*idx+3
return [2] + [number for number in numbers if number] | python | def create_primes(threshold):
"""
Generate prime values using sieve of Eratosthenes method.
Args:
threshold (int):
The upper bound for the size of the prime values.
Returns (List[int]):
All primes from 2 and up to ``threshold``.
"""
if threshold == 2:
return [2]
elif threshold < 2:
return []
numbers = list(range(3, threshold+1, 2))
root_of_threshold = threshold ** 0.5
half = int((threshold+1)/2-1)
idx = 0
counter = 3
while counter <= root_of_threshold:
if numbers[idx]:
idy = int((counter*counter-3)/2)
numbers[idy] = 0
while idy < half:
numbers[idy] = 0
idy += counter
idx += 1
counter = 2*idx+3
return [2] + [number for number in numbers if number] | [
"def",
"create_primes",
"(",
"threshold",
")",
":",
"if",
"threshold",
"==",
"2",
":",
"return",
"[",
"2",
"]",
"elif",
"threshold",
"<",
"2",
":",
"return",
"[",
"]",
"numbers",
"=",
"list",
"(",
"range",
"(",
"3",
",",
"threshold",
"+",
"1",
",",... | Generate prime values using sieve of Eratosthenes method.
Args:
threshold (int):
The upper bound for the size of the prime values.
Returns (List[int]):
All primes from 2 and up to ``threshold``. | [
"Generate",
"prime",
"values",
"using",
"sieve",
"of",
"Eratosthenes",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/primes.py#L17-L48 | train | 207,001 |
jonathf/chaospy | chaospy/distributions/evaluation/inverse.py | evaluate_inverse | def evaluate_inverse(
distribution,
u_data,
cache=None,
parameters=None
):
"""
Evaluate inverse Rosenblatt transformation.
Args:
distribution (Dist):
Distribution to evaluate.
u_data (numpy.ndarray):
Locations for where evaluate inverse transformation distribution at.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The cumulative distribution values of ``distribution`` at location
``u_data`` using parameters ``parameters``.
"""
if cache is None:
cache = {}
out = numpy.zeros(u_data.shape)
# Distribution self know how to handle inverse Rosenblatt.
if hasattr(distribution, "_ppf"):
parameters = load_parameters(
distribution, "_ppf", parameters=parameters, cache=cache)
out[:] = distribution._ppf(u_data.copy(), **parameters)
# Approximate inverse Rosenblatt based on cumulative distribution function.
else:
from .. import approximation
parameters = load_parameters(
distribution, "_cdf", parameters=parameters, cache=cache)
out[:] = approximation.approximate_inverse(
distribution, u_data.copy(), cache=cache.copy(), parameters=parameters)
# Store cache.
cache[distribution] = out
return out | python | def evaluate_inverse(
distribution,
u_data,
cache=None,
parameters=None
):
"""
Evaluate inverse Rosenblatt transformation.
Args:
distribution (Dist):
Distribution to evaluate.
u_data (numpy.ndarray):
Locations for where evaluate inverse transformation distribution at.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The cumulative distribution values of ``distribution`` at location
``u_data`` using parameters ``parameters``.
"""
if cache is None:
cache = {}
out = numpy.zeros(u_data.shape)
# Distribution self know how to handle inverse Rosenblatt.
if hasattr(distribution, "_ppf"):
parameters = load_parameters(
distribution, "_ppf", parameters=parameters, cache=cache)
out[:] = distribution._ppf(u_data.copy(), **parameters)
# Approximate inverse Rosenblatt based on cumulative distribution function.
else:
from .. import approximation
parameters = load_parameters(
distribution, "_cdf", parameters=parameters, cache=cache)
out[:] = approximation.approximate_inverse(
distribution, u_data.copy(), cache=cache.copy(), parameters=parameters)
# Store cache.
cache[distribution] = out
return out | [
"def",
"evaluate_inverse",
"(",
"distribution",
",",
"u_data",
",",
"cache",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"u_data",
".",
"shap... | Evaluate inverse Rosenblatt transformation.
Args:
distribution (Dist):
Distribution to evaluate.
u_data (numpy.ndarray):
Locations for where evaluate inverse transformation distribution at.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The cumulative distribution values of ``distribution`` at location
``u_data`` using parameters ``parameters``. | [
"Evaluate",
"inverse",
"Rosenblatt",
"transformation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/inverse.py#L42-L88 | train | 207,002 |
jonathf/chaospy | chaospy/bertran/fourier.py | FourierRecursive.mom_recurse | def mom_recurse(self, idxi, idxj, idxk):
"""Backend mement main loop."""
rank_ = min(
chaospy.bertran.rank(idxi, self.dim),
chaospy.bertran.rank(idxj, self.dim),
chaospy.bertran.rank(idxk, self.dim)
)
par, axis0 = chaospy.bertran.parent(idxk, self.dim)
gpar, _ = chaospy.bertran.parent(par, self.dim, axis0)
idxi_child = chaospy.bertran.child(idxi, self.dim, axis0)
oneup = chaospy.bertran.child(0, self.dim, axis0)
out1 = self.mom_111(idxi_child, idxj, par)
out2 = self.mom_111(
chaospy.bertran.child(oneup, self.dim, axis0), par, par)
for k in range(gpar, idxk):
if chaospy.bertran.rank(k, self.dim) >= rank_:
out1 -= self.mom_111(oneup, k, par) \
* self.mom_111(idxi, idxj, k)
out2 -= self.mom_111(oneup, par, k) \
* self(oneup, k, par)
return out1 / out2 | python | def mom_recurse(self, idxi, idxj, idxk):
"""Backend mement main loop."""
rank_ = min(
chaospy.bertran.rank(idxi, self.dim),
chaospy.bertran.rank(idxj, self.dim),
chaospy.bertran.rank(idxk, self.dim)
)
par, axis0 = chaospy.bertran.parent(idxk, self.dim)
gpar, _ = chaospy.bertran.parent(par, self.dim, axis0)
idxi_child = chaospy.bertran.child(idxi, self.dim, axis0)
oneup = chaospy.bertran.child(0, self.dim, axis0)
out1 = self.mom_111(idxi_child, idxj, par)
out2 = self.mom_111(
chaospy.bertran.child(oneup, self.dim, axis0), par, par)
for k in range(gpar, idxk):
if chaospy.bertran.rank(k, self.dim) >= rank_:
out1 -= self.mom_111(oneup, k, par) \
* self.mom_111(idxi, idxj, k)
out2 -= self.mom_111(oneup, par, k) \
* self(oneup, k, par)
return out1 / out2 | [
"def",
"mom_recurse",
"(",
"self",
",",
"idxi",
",",
"idxj",
",",
"idxk",
")",
":",
"rank_",
"=",
"min",
"(",
"chaospy",
".",
"bertran",
".",
"rank",
"(",
"idxi",
",",
"self",
".",
"dim",
")",
",",
"chaospy",
".",
"bertran",
".",
"rank",
"(",
"id... | Backend mement main loop. | [
"Backend",
"mement",
"main",
"loop",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/fourier.py#L68-L89 | train | 207,003 |
jonathf/chaospy | chaospy/descriptives/sensitivity/nataf.py | Sens_m_nataf | def Sens_m_nataf(order, dist, samples, vals, **kws):
"""
Variance-based decomposition through the Nataf distribution.
Generates first order sensitivity indices
Args:
order (int):
Polynomial order used ``orth_ttr``.
dist (Copula):
Assumed to be Nataf with independent components
samples (numpy.ndarray):
Samples used for evaluation (typically generated from ``dist``.)
vals (numpy.ndarray): Evaluations of the model for given samples.
Returns:
(numpy.ndarray):
Sensitivity indices with shape ``(len(dist),) + vals.shape[1:]``.
"""
assert dist.__class__.__name__ == "Copula"
trans = dist.prm["trans"]
assert trans.__class__.__name__ == "nataf"
vals = numpy.array(vals)
cov = trans.prm["C"]
cov = numpy.dot(cov, cov.T)
marginal = dist.prm["dist"]
dim = len(dist)
orth = chaospy.orthogonal.orth_ttr(order, marginal, sort="GR")
r = range(dim)
index = [1] + [0]*(dim-1)
nataf = chaospy.dist.Nataf(marginal, cov, r)
samples_ = marginal.inv( nataf.fwd( samples ) )
poly, coeffs = chaospy.collocation.fit_regression(
orth, samples_, vals, retall=1)
V = Var(poly, marginal, **kws)
out = numpy.zeros((dim,) + poly.shape)
out[0] = Var(E_cond(poly, index, marginal, **kws),
marginal, **kws)/(V+(V == 0))*(V != 0)
for i in range(1, dim):
r = r[1:] + r[:1]
index = index[-1:] + index[:-1]
nataf = chaospy.dist.Nataf(marginal, cov, r)
samples_ = marginal.inv( nataf.fwd( samples ) )
poly, coeffs = chaospy.collocation.fit_regression(
orth, samples_, vals, retall=1)
out[i] = Var(E_cond(poly, index, marginal, **kws),
marginal, **kws)/(V+(V == 0))*(V != 0)
return out | python | def Sens_m_nataf(order, dist, samples, vals, **kws):
"""
Variance-based decomposition through the Nataf distribution.
Generates first order sensitivity indices
Args:
order (int):
Polynomial order used ``orth_ttr``.
dist (Copula):
Assumed to be Nataf with independent components
samples (numpy.ndarray):
Samples used for evaluation (typically generated from ``dist``.)
vals (numpy.ndarray): Evaluations of the model for given samples.
Returns:
(numpy.ndarray):
Sensitivity indices with shape ``(len(dist),) + vals.shape[1:]``.
"""
assert dist.__class__.__name__ == "Copula"
trans = dist.prm["trans"]
assert trans.__class__.__name__ == "nataf"
vals = numpy.array(vals)
cov = trans.prm["C"]
cov = numpy.dot(cov, cov.T)
marginal = dist.prm["dist"]
dim = len(dist)
orth = chaospy.orthogonal.orth_ttr(order, marginal, sort="GR")
r = range(dim)
index = [1] + [0]*(dim-1)
nataf = chaospy.dist.Nataf(marginal, cov, r)
samples_ = marginal.inv( nataf.fwd( samples ) )
poly, coeffs = chaospy.collocation.fit_regression(
orth, samples_, vals, retall=1)
V = Var(poly, marginal, **kws)
out = numpy.zeros((dim,) + poly.shape)
out[0] = Var(E_cond(poly, index, marginal, **kws),
marginal, **kws)/(V+(V == 0))*(V != 0)
for i in range(1, dim):
r = r[1:] + r[:1]
index = index[-1:] + index[:-1]
nataf = chaospy.dist.Nataf(marginal, cov, r)
samples_ = marginal.inv( nataf.fwd( samples ) )
poly, coeffs = chaospy.collocation.fit_regression(
orth, samples_, vals, retall=1)
out[i] = Var(E_cond(poly, index, marginal, **kws),
marginal, **kws)/(V+(V == 0))*(V != 0)
return out | [
"def",
"Sens_m_nataf",
"(",
"order",
",",
"dist",
",",
"samples",
",",
"vals",
",",
"*",
"*",
"kws",
")",
":",
"assert",
"dist",
".",
"__class__",
".",
"__name__",
"==",
"\"Copula\"",
"trans",
"=",
"dist",
".",
"prm",
"[",
"\"trans\"",
"]",
"assert",
... | Variance-based decomposition through the Nataf distribution.
Generates first order sensitivity indices
Args:
order (int):
Polynomial order used ``orth_ttr``.
dist (Copula):
Assumed to be Nataf with independent components
samples (numpy.ndarray):
Samples used for evaluation (typically generated from ``dist``.)
vals (numpy.ndarray): Evaluations of the model for given samples.
Returns:
(numpy.ndarray):
Sensitivity indices with shape ``(len(dist),) + vals.shape[1:]``. | [
"Variance",
"-",
"based",
"decomposition",
"through",
"the",
"Nataf",
"distribution",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/sensitivity/nataf.py#L10-L71 | train | 207,004 |
jonathf/chaospy | chaospy/quad/collection/golub_welsch.py | quad_golub_welsch | def quad_golub_welsch(order, dist, accuracy=100, **kws):
"""
Golub-Welsch algorithm for creating quadrature nodes and weights.
Args:
order (int):
Quadrature order
dist (Dist):
Distribution nodes and weights are found for with `dim=len(dist)`
accuracy (int):
Accuracy used in discretized Stieltjes procedure. Will
be increased by one for each iteration.
Returns:
(numpy.ndarray, numpy.ndarray):
Optimal collocation nodes with `x.shape=(dim, order+1)` and weights
with `w.shape=(order+1,)`.
Examples:
>>> Z = chaospy.Normal()
>>> x, w = chaospy.quad_golub_welsch(3, Z)
>>> print(numpy.around(x, 4))
[[-2.3344 -0.742 0.742 2.3344]]
>>> print(numpy.around(w, 4))
[0.0459 0.4541 0.4541 0.0459]
>>> Z = chaospy.J(chaospy.Uniform(), chaospy.Uniform())
>>> x, w = chaospy.quad_golub_welsch(1, Z)
>>> print(numpy.around(x, 4))
[[0.2113 0.2113 0.7887 0.7887]
[0.2113 0.7887 0.2113 0.7887]]
>>> print(numpy.around(w, 4))
[0.25 0.25 0.25 0.25]
"""
order = numpy.array(order)*numpy.ones(len(dist), dtype=int)+1
_, _, coeff1, coeff2 = chaospy.quad.generate_stieltjes(
dist, numpy.max(order), accuracy=accuracy, retall=True, **kws)
dimensions = len(dist)
abscisas, weights = _golbub_welsch(order, coeff1, coeff2)
if dimensions == 1:
abscisa = numpy.reshape(abscisas, (1, order[0]))
weight = numpy.reshape(weights, (order[0],))
else:
abscisa = chaospy.quad.combine(abscisas).T
weight = numpy.prod(chaospy.quad.combine(weights), -1)
assert len(abscisa) == dimensions
assert len(weight) == len(abscisa.T)
return abscisa, weight | python | def quad_golub_welsch(order, dist, accuracy=100, **kws):
"""
Golub-Welsch algorithm for creating quadrature nodes and weights.
Args:
order (int):
Quadrature order
dist (Dist):
Distribution nodes and weights are found for with `dim=len(dist)`
accuracy (int):
Accuracy used in discretized Stieltjes procedure. Will
be increased by one for each iteration.
Returns:
(numpy.ndarray, numpy.ndarray):
Optimal collocation nodes with `x.shape=(dim, order+1)` and weights
with `w.shape=(order+1,)`.
Examples:
>>> Z = chaospy.Normal()
>>> x, w = chaospy.quad_golub_welsch(3, Z)
>>> print(numpy.around(x, 4))
[[-2.3344 -0.742 0.742 2.3344]]
>>> print(numpy.around(w, 4))
[0.0459 0.4541 0.4541 0.0459]
>>> Z = chaospy.J(chaospy.Uniform(), chaospy.Uniform())
>>> x, w = chaospy.quad_golub_welsch(1, Z)
>>> print(numpy.around(x, 4))
[[0.2113 0.2113 0.7887 0.7887]
[0.2113 0.7887 0.2113 0.7887]]
>>> print(numpy.around(w, 4))
[0.25 0.25 0.25 0.25]
"""
order = numpy.array(order)*numpy.ones(len(dist), dtype=int)+1
_, _, coeff1, coeff2 = chaospy.quad.generate_stieltjes(
dist, numpy.max(order), accuracy=accuracy, retall=True, **kws)
dimensions = len(dist)
abscisas, weights = _golbub_welsch(order, coeff1, coeff2)
if dimensions == 1:
abscisa = numpy.reshape(abscisas, (1, order[0]))
weight = numpy.reshape(weights, (order[0],))
else:
abscisa = chaospy.quad.combine(abscisas).T
weight = numpy.prod(chaospy.quad.combine(weights), -1)
assert len(abscisa) == dimensions
assert len(weight) == len(abscisa.T)
return abscisa, weight | [
"def",
"quad_golub_welsch",
"(",
"order",
",",
"dist",
",",
"accuracy",
"=",
"100",
",",
"*",
"*",
"kws",
")",
":",
"order",
"=",
"numpy",
".",
"array",
"(",
"order",
")",
"*",
"numpy",
".",
"ones",
"(",
"len",
"(",
"dist",
")",
",",
"dtype",
"="... | Golub-Welsch algorithm for creating quadrature nodes and weights.
Args:
order (int):
Quadrature order
dist (Dist):
Distribution nodes and weights are found for with `dim=len(dist)`
accuracy (int):
Accuracy used in discretized Stieltjes procedure. Will
be increased by one for each iteration.
Returns:
(numpy.ndarray, numpy.ndarray):
Optimal collocation nodes with `x.shape=(dim, order+1)` and weights
with `w.shape=(order+1,)`.
Examples:
>>> Z = chaospy.Normal()
>>> x, w = chaospy.quad_golub_welsch(3, Z)
>>> print(numpy.around(x, 4))
[[-2.3344 -0.742 0.742 2.3344]]
>>> print(numpy.around(w, 4))
[0.0459 0.4541 0.4541 0.0459]
>>> Z = chaospy.J(chaospy.Uniform(), chaospy.Uniform())
>>> x, w = chaospy.quad_golub_welsch(1, Z)
>>> print(numpy.around(x, 4))
[[0.2113 0.2113 0.7887 0.7887]
[0.2113 0.7887 0.2113 0.7887]]
>>> print(numpy.around(w, 4))
[0.25 0.25 0.25 0.25] | [
"Golub",
"-",
"Welsch",
"algorithm",
"for",
"creating",
"quadrature",
"nodes",
"and",
"weights",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/golub_welsch.py#L98-L147 | train | 207,005 |
jonathf/chaospy | chaospy/quad/collection/golub_welsch.py | _golbub_welsch | def _golbub_welsch(orders, coeff1, coeff2):
"""Recurrence coefficients to abscisas and weights."""
abscisas, weights = [], []
for dim, order in enumerate(orders):
if order:
bands = numpy.zeros((2, order))
bands[0] = coeff1[dim, :order]
bands[1, :-1] = numpy.sqrt(coeff2[dim, 1:order])
vals, vecs = scipy.linalg.eig_banded(bands, lower=True)
abscisa, weight = vals.real, vecs[0, :]**2
indices = numpy.argsort(abscisa)
abscisa, weight = abscisa[indices], weight[indices]
else:
abscisa, weight = numpy.array([coeff1[dim, 0]]), numpy.array([1.])
abscisas.append(abscisa)
weights.append(weight)
return abscisas, weights | python | def _golbub_welsch(orders, coeff1, coeff2):
"""Recurrence coefficients to abscisas and weights."""
abscisas, weights = [], []
for dim, order in enumerate(orders):
if order:
bands = numpy.zeros((2, order))
bands[0] = coeff1[dim, :order]
bands[1, :-1] = numpy.sqrt(coeff2[dim, 1:order])
vals, vecs = scipy.linalg.eig_banded(bands, lower=True)
abscisa, weight = vals.real, vecs[0, :]**2
indices = numpy.argsort(abscisa)
abscisa, weight = abscisa[indices], weight[indices]
else:
abscisa, weight = numpy.array([coeff1[dim, 0]]), numpy.array([1.])
abscisas.append(abscisa)
weights.append(weight)
return abscisas, weights | [
"def",
"_golbub_welsch",
"(",
"orders",
",",
"coeff1",
",",
"coeff2",
")",
":",
"abscisas",
",",
"weights",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"dim",
",",
"order",
"in",
"enumerate",
"(",
"orders",
")",
":",
"if",
"order",
":",
"bands",
"=",
"num... | Recurrence coefficients to abscisas and weights. | [
"Recurrence",
"coefficients",
"to",
"abscisas",
"and",
"weights",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/golub_welsch.py#L150-L170 | train | 207,006 |
jonathf/chaospy | chaospy/descriptives/kurtosis.py | Kurt | def Kurt(poly, dist=None, fisher=True, **kws):
"""
Kurtosis operator.
Element by element 4rd order statistics of a distribution or polynomial.
Args:
poly (Poly, Dist):
Input to take kurtosis on.
dist (Dist):
Defines the space the skewness is taken on. It is ignored if
``poly`` is a distribution.
fisher (bool):
If True, Fisher's definition is used (Normal -> 0.0). If False,
Pearson's definition is used (normal -> 3.0)
Returns:
(numpy.ndarray):
Element for element variance along ``poly``, where
``skewness.shape==poly.shape``.
Examples:
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> print(numpy.around(chaospy.Kurt(dist), 4))
[6. 0.]
>>> print(numpy.around(chaospy.Kurt(dist, fisher=False), 4))
[9. 3.]
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> print(numpy.around(chaospy.Kurt(poly, dist), 4))
[nan 6. 0. 15.]
"""
if isinstance(poly, distributions.Dist):
x = polynomials.variable(len(poly))
poly, dist = x, poly
else:
poly = polynomials.Poly(poly)
if fisher:
adjust = 3
else:
adjust = 0
shape = poly.shape
poly = polynomials.flatten(poly)
m1 = E(poly, dist)
m2 = E(poly**2, dist)
m3 = E(poly**3, dist)
m4 = E(poly**4, dist)
out = (m4-4*m3*m1 + 6*m2*m1**2 - 3*m1**4) /\
(m2**2-2*m2*m1**2+m1**4) - adjust
out = numpy.reshape(out, shape)
return out | python | def Kurt(poly, dist=None, fisher=True, **kws):
"""
Kurtosis operator.
Element by element 4rd order statistics of a distribution or polynomial.
Args:
poly (Poly, Dist):
Input to take kurtosis on.
dist (Dist):
Defines the space the skewness is taken on. It is ignored if
``poly`` is a distribution.
fisher (bool):
If True, Fisher's definition is used (Normal -> 0.0). If False,
Pearson's definition is used (normal -> 3.0)
Returns:
(numpy.ndarray):
Element for element variance along ``poly``, where
``skewness.shape==poly.shape``.
Examples:
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> print(numpy.around(chaospy.Kurt(dist), 4))
[6. 0.]
>>> print(numpy.around(chaospy.Kurt(dist, fisher=False), 4))
[9. 3.]
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> print(numpy.around(chaospy.Kurt(poly, dist), 4))
[nan 6. 0. 15.]
"""
if isinstance(poly, distributions.Dist):
x = polynomials.variable(len(poly))
poly, dist = x, poly
else:
poly = polynomials.Poly(poly)
if fisher:
adjust = 3
else:
adjust = 0
shape = poly.shape
poly = polynomials.flatten(poly)
m1 = E(poly, dist)
m2 = E(poly**2, dist)
m3 = E(poly**3, dist)
m4 = E(poly**4, dist)
out = (m4-4*m3*m1 + 6*m2*m1**2 - 3*m1**4) /\
(m2**2-2*m2*m1**2+m1**4) - adjust
out = numpy.reshape(out, shape)
return out | [
"def",
"Kurt",
"(",
"poly",
",",
"dist",
"=",
"None",
",",
"fisher",
"=",
"True",
",",
"*",
"*",
"kws",
")",
":",
"if",
"isinstance",
"(",
"poly",
",",
"distributions",
".",
"Dist",
")",
":",
"x",
"=",
"polynomials",
".",
"variable",
"(",
"len",
... | Kurtosis operator.
Element by element 4rd order statistics of a distribution or polynomial.
Args:
poly (Poly, Dist):
Input to take kurtosis on.
dist (Dist):
Defines the space the skewness is taken on. It is ignored if
``poly`` is a distribution.
fisher (bool):
If True, Fisher's definition is used (Normal -> 0.0). If False,
Pearson's definition is used (normal -> 3.0)
Returns:
(numpy.ndarray):
Element for element variance along ``poly``, where
``skewness.shape==poly.shape``.
Examples:
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> print(numpy.around(chaospy.Kurt(dist), 4))
[6. 0.]
>>> print(numpy.around(chaospy.Kurt(dist, fisher=False), 4))
[9. 3.]
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> print(numpy.around(chaospy.Kurt(poly, dist), 4))
[nan 6. 0. 15.] | [
"Kurtosis",
"operator",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/kurtosis.py#L8-L63 | train | 207,007 |
jonathf/chaospy | chaospy/poly/collection/core.py | basis | def basis(start, stop=None, dim=1, sort="G", cross_truncation=1.):
"""
Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order along each
axis.
stop (int, numpy.ndarray):
the maximum shape included. If omitted:
``stop <- start; start <- 0`` If int is provided, set as largest
total order. If array of int, set as largest order along each axis.
dim (int):
dim of the basis. Ignored if array is provided in either start or
stop.
sort (str):
The polynomial ordering where the letters ``G``, ``I`` and ``R``
can be used to set grade, inverse and reverse to the ordering. For
``basis(start=0, stop=2, dim=2, order=order)`` we get:
====== ==================
order output
====== ==================
"" [1 y y^2 x xy x^2]
"G" [1 y x y^2 xy x^2]
"I" [x^2 xy x y^2 y 1]
"R" [1 x x^2 y xy y^2]
"GIR" [y^2 xy x^2 y x 1]
====== ==================
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly) : Polynomial array.
Examples:
>>> print(chaospy.basis(4, 4, 2))
[q0^4, q0^3q1, q0^2q1^2, q0q1^3, q1^4]
>>> print(chaospy.basis([1, 1], [2, 2]))
[q0q1, q0^2q1, q0q1^2, q0^2q1^2]
"""
if stop is None:
start, stop = numpy.array(0), start
start = numpy.array(start, dtype=int)
stop = numpy.array(stop, dtype=int)
dim = max(start.size, stop.size, dim)
indices = numpy.array(chaospy.bertran.bindex(
numpy.min(start), 2*numpy.max(stop), dim, sort, cross_truncation))
if start.size == 1:
bellow = numpy.sum(indices, -1) >= start
else:
start = numpy.ones(dim, dtype=int)*start
bellow = numpy.all(indices-start >= 0, -1)
if stop.size == 1:
above = numpy.sum(indices, -1) <= stop.item()
else:
stop = numpy.ones(dim, dtype=int)*stop
above = numpy.all(stop-indices >= 0, -1)
pool = list(indices[above*bellow])
arg = numpy.zeros(len(pool), dtype=int)
arg[0] = 1
poly = {}
for idx in pool:
idx = tuple(idx)
poly[idx] = arg
arg = numpy.roll(arg, 1)
x = numpy.zeros(len(pool), dtype=int)
x[0] = 1
A = {}
for I in pool:
I = tuple(I)
A[I] = x
x = numpy.roll(x,1)
return Poly(A, dim) | python | def basis(start, stop=None, dim=1, sort="G", cross_truncation=1.):
"""
Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order along each
axis.
stop (int, numpy.ndarray):
the maximum shape included. If omitted:
``stop <- start; start <- 0`` If int is provided, set as largest
total order. If array of int, set as largest order along each axis.
dim (int):
dim of the basis. Ignored if array is provided in either start or
stop.
sort (str):
The polynomial ordering where the letters ``G``, ``I`` and ``R``
can be used to set grade, inverse and reverse to the ordering. For
``basis(start=0, stop=2, dim=2, order=order)`` we get:
====== ==================
order output
====== ==================
"" [1 y y^2 x xy x^2]
"G" [1 y x y^2 xy x^2]
"I" [x^2 xy x y^2 y 1]
"R" [1 x x^2 y xy y^2]
"GIR" [y^2 xy x^2 y x 1]
====== ==================
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly) : Polynomial array.
Examples:
>>> print(chaospy.basis(4, 4, 2))
[q0^4, q0^3q1, q0^2q1^2, q0q1^3, q1^4]
>>> print(chaospy.basis([1, 1], [2, 2]))
[q0q1, q0^2q1, q0q1^2, q0^2q1^2]
"""
if stop is None:
start, stop = numpy.array(0), start
start = numpy.array(start, dtype=int)
stop = numpy.array(stop, dtype=int)
dim = max(start.size, stop.size, dim)
indices = numpy.array(chaospy.bertran.bindex(
numpy.min(start), 2*numpy.max(stop), dim, sort, cross_truncation))
if start.size == 1:
bellow = numpy.sum(indices, -1) >= start
else:
start = numpy.ones(dim, dtype=int)*start
bellow = numpy.all(indices-start >= 0, -1)
if stop.size == 1:
above = numpy.sum(indices, -1) <= stop.item()
else:
stop = numpy.ones(dim, dtype=int)*stop
above = numpy.all(stop-indices >= 0, -1)
pool = list(indices[above*bellow])
arg = numpy.zeros(len(pool), dtype=int)
arg[0] = 1
poly = {}
for idx in pool:
idx = tuple(idx)
poly[idx] = arg
arg = numpy.roll(arg, 1)
x = numpy.zeros(len(pool), dtype=int)
x[0] = 1
A = {}
for I in pool:
I = tuple(I)
A[I] = x
x = numpy.roll(x,1)
return Poly(A, dim) | [
"def",
"basis",
"(",
"start",
",",
"stop",
"=",
"None",
",",
"dim",
"=",
"1",
",",
"sort",
"=",
"\"G\"",
",",
"cross_truncation",
"=",
"1.",
")",
":",
"if",
"stop",
"is",
"None",
":",
"start",
",",
"stop",
"=",
"numpy",
".",
"array",
"(",
"0",
... | Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order along each
axis.
stop (int, numpy.ndarray):
the maximum shape included. If omitted:
``stop <- start; start <- 0`` If int is provided, set as largest
total order. If array of int, set as largest order along each axis.
dim (int):
dim of the basis. Ignored if array is provided in either start or
stop.
sort (str):
The polynomial ordering where the letters ``G``, ``I`` and ``R``
can be used to set grade, inverse and reverse to the ordering. For
``basis(start=0, stop=2, dim=2, order=order)`` we get:
====== ==================
order output
====== ==================
"" [1 y y^2 x xy x^2]
"G" [1 y x y^2 xy x^2]
"I" [x^2 xy x y^2 y 1]
"R" [1 x x^2 y xy y^2]
"GIR" [y^2 xy x^2 y x 1]
====== ==================
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly) : Polynomial array.
Examples:
>>> print(chaospy.basis(4, 4, 2))
[q0^4, q0^3q1, q0^2q1^2, q0q1^3, q1^4]
>>> print(chaospy.basis([1, 1], [2, 2]))
[q0q1, q0^2q1, q0q1^2, q0^2q1^2] | [
"Create",
"an",
"N",
"-",
"dimensional",
"unit",
"polynomial",
"basis",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L15-L97 | train | 207,008 |
jonathf/chaospy | chaospy/poly/collection/core.py | cutoff | def cutoff(poly, *args):
"""
Remove polynomial components with order outside a given interval.
Args:
poly (Poly):
Input data.
low (int):
The lowest order that is allowed to be included. Defaults to 0.
high (int):
The upper threshold for the cutoff range.
Returns:
(Poly):
The same as `P`, except that all terms that have a order not within
the bound `low <= order < high` are removed.
Examples:
>>> poly = chaospy.prange(4, 1) + chaospy.prange(4, 2)[::-1]
>>> print(poly) # doctest: +SKIP
[q1^3+1, q0+q1^2, q0^2+q1, q0^3+1]
>>> print(chaospy.cutoff(poly, 3)) # doctest: +SKIP
[1, q0+q1^2, q0^2+q1, 1]
>>> print(chaospy.cutoff(poly, 1, 3)) # doctest: +SKIP
[0, q0+q1^2, q0^2+q1, 0]
"""
if len(args) == 1:
low, high = 0, args[0]
else:
low, high = args[:2]
core_old = poly.A
core_new = {}
for key in poly.keys:
if low <= numpy.sum(key) < high:
core_new[key] = core_old[key]
return Poly(core_new, poly.dim, poly.shape, poly.dtype) | python | def cutoff(poly, *args):
"""
Remove polynomial components with order outside a given interval.
Args:
poly (Poly):
Input data.
low (int):
The lowest order that is allowed to be included. Defaults to 0.
high (int):
The upper threshold for the cutoff range.
Returns:
(Poly):
The same as `P`, except that all terms that have a order not within
the bound `low <= order < high` are removed.
Examples:
>>> poly = chaospy.prange(4, 1) + chaospy.prange(4, 2)[::-1]
>>> print(poly) # doctest: +SKIP
[q1^3+1, q0+q1^2, q0^2+q1, q0^3+1]
>>> print(chaospy.cutoff(poly, 3)) # doctest: +SKIP
[1, q0+q1^2, q0^2+q1, 1]
>>> print(chaospy.cutoff(poly, 1, 3)) # doctest: +SKIP
[0, q0+q1^2, q0^2+q1, 0]
"""
if len(args) == 1:
low, high = 0, args[0]
else:
low, high = args[:2]
core_old = poly.A
core_new = {}
for key in poly.keys:
if low <= numpy.sum(key) < high:
core_new[key] = core_old[key]
return Poly(core_new, poly.dim, poly.shape, poly.dtype) | [
"def",
"cutoff",
"(",
"poly",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"low",
",",
"high",
"=",
"0",
",",
"args",
"[",
"0",
"]",
"else",
":",
"low",
",",
"high",
"=",
"args",
"[",
":",
"2",
"]",
"core_old",... | Remove polynomial components with order outside a given interval.
Args:
poly (Poly):
Input data.
low (int):
The lowest order that is allowed to be included. Defaults to 0.
high (int):
The upper threshold for the cutoff range.
Returns:
(Poly):
The same as `P`, except that all terms that have a order not within
the bound `low <= order < high` are removed.
Examples:
>>> poly = chaospy.prange(4, 1) + chaospy.prange(4, 2)[::-1]
>>> print(poly) # doctest: +SKIP
[q1^3+1, q0+q1^2, q0^2+q1, q0^3+1]
>>> print(chaospy.cutoff(poly, 3)) # doctest: +SKIP
[1, q0+q1^2, q0^2+q1, 1]
>>> print(chaospy.cutoff(poly, 1, 3)) # doctest: +SKIP
[0, q0+q1^2, q0^2+q1, 0] | [
"Remove",
"polynomial",
"components",
"with",
"order",
"outside",
"a",
"given",
"interval",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L113-L149 | train | 207,009 |
jonathf/chaospy | chaospy/poly/collection/core.py | prange | def prange(N=1, dim=1):
"""
Constructor to create a range of polynomials where the exponent vary.
Args:
N (int):
Number of polynomials in the array.
dim (int):
The dimension the polynomial should span.
Returns:
(Poly):
A polynomial array of length N containing simple polynomials with
increasing exponent.
Examples:
>>> print(prange(4))
[1, q0, q0^2, q0^3]
>>> print(prange(4, dim=3))
[1, q2, q2^2, q2^3]
"""
A = {}
r = numpy.arange(N, dtype=int)
key = numpy.zeros(dim, dtype=int)
for i in range(N):
key[-1] = i
A[tuple(key)] = 1*(r==i)
return Poly(A, dim, (N,), int) | python | def prange(N=1, dim=1):
"""
Constructor to create a range of polynomials where the exponent vary.
Args:
N (int):
Number of polynomials in the array.
dim (int):
The dimension the polynomial should span.
Returns:
(Poly):
A polynomial array of length N containing simple polynomials with
increasing exponent.
Examples:
>>> print(prange(4))
[1, q0, q0^2, q0^3]
>>> print(prange(4, dim=3))
[1, q2, q2^2, q2^3]
"""
A = {}
r = numpy.arange(N, dtype=int)
key = numpy.zeros(dim, dtype=int)
for i in range(N):
key[-1] = i
A[tuple(key)] = 1*(r==i)
return Poly(A, dim, (N,), int) | [
"def",
"prange",
"(",
"N",
"=",
"1",
",",
"dim",
"=",
"1",
")",
":",
"A",
"=",
"{",
"}",
"r",
"=",
"numpy",
".",
"arange",
"(",
"N",
",",
"dtype",
"=",
"int",
")",
"key",
"=",
"numpy",
".",
"zeros",
"(",
"dim",
",",
"dtype",
"=",
"int",
"... | Constructor to create a range of polynomials where the exponent vary.
Args:
N (int):
Number of polynomials in the array.
dim (int):
The dimension the polynomial should span.
Returns:
(Poly):
A polynomial array of length N containing simple polynomials with
increasing exponent.
Examples:
>>> print(prange(4))
[1, q0, q0^2, q0^3]
>>> print(prange(4, dim=3))
[1, q2, q2^2, q2^3] | [
"Constructor",
"to",
"create",
"a",
"range",
"of",
"polynomials",
"where",
"the",
"exponent",
"vary",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L202-L230 | train | 207,010 |
jonathf/chaospy | chaospy/poly/collection/core.py | rolldim | def rolldim(P, n=1):
"""
Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
>>> P = x*x*x + y*y + z
>>> print(P)
q0^3+q1^2+q2
>>> print(rolldim(P))
q0^2+q2^3+q1
"""
dim = P.dim
shape = P.shape
dtype = P.dtype
A = dict(((key[n:]+key[:n],P.A[key]) for key in P.keys))
return Poly(A, dim, shape, dtype) | python | def rolldim(P, n=1):
"""
Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
>>> P = x*x*x + y*y + z
>>> print(P)
q0^3+q1^2+q2
>>> print(rolldim(P))
q0^2+q2^3+q1
"""
dim = P.dim
shape = P.shape
dtype = P.dtype
A = dict(((key[n:]+key[:n],P.A[key]) for key in P.keys))
return Poly(A, dim, shape, dtype) | [
"def",
"rolldim",
"(",
"P",
",",
"n",
"=",
"1",
")",
":",
"dim",
"=",
"P",
".",
"dim",
"shape",
"=",
"P",
".",
"shape",
"dtype",
"=",
"P",
".",
"dtype",
"A",
"=",
"dict",
"(",
"(",
"(",
"key",
"[",
"n",
":",
"]",
"+",
"key",
"[",
":",
"... | Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
>>> P = x*x*x + y*y + z
>>> print(P)
q0^3+q1^2+q2
>>> print(rolldim(P))
q0^2+q2^3+q1 | [
"Roll",
"the",
"axes",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L233-L256 | train | 207,011 |
jonathf/chaospy | chaospy/poly/collection/core.py | swapdim | def swapdim(P, dim1=1, dim2=0):
"""
Swap the dim between two variables.
Args:
P (Poly):
Input polynomial.
dim1 (int):
First dim
dim2 (int):
Second dim.
Returns:
(Poly):
Polynomial with swapped dimensions.
Examples:
>>> x,y = variable(2)
>>> P = x**4-y
>>> print(P)
q0^4-q1
>>> print(swapdim(P))
q1^4-q0
"""
if not isinstance(P, Poly):
return numpy.swapaxes(P, dim1, dim2)
dim = P.dim
shape = P.shape
dtype = P.dtype
if dim1==dim2:
return P
m = max(dim1, dim2)
if P.dim <= m:
P = chaospy.poly.dimension.setdim(P, m+1)
dim = m+1
A = {}
for key in P.keys:
val = P.A[key]
key = list(key)
key[dim1], key[dim2] = key[dim2], key[dim1]
A[tuple(key)] = val
return Poly(A, dim, shape, dtype) | python | def swapdim(P, dim1=1, dim2=0):
"""
Swap the dim between two variables.
Args:
P (Poly):
Input polynomial.
dim1 (int):
First dim
dim2 (int):
Second dim.
Returns:
(Poly):
Polynomial with swapped dimensions.
Examples:
>>> x,y = variable(2)
>>> P = x**4-y
>>> print(P)
q0^4-q1
>>> print(swapdim(P))
q1^4-q0
"""
if not isinstance(P, Poly):
return numpy.swapaxes(P, dim1, dim2)
dim = P.dim
shape = P.shape
dtype = P.dtype
if dim1==dim2:
return P
m = max(dim1, dim2)
if P.dim <= m:
P = chaospy.poly.dimension.setdim(P, m+1)
dim = m+1
A = {}
for key in P.keys:
val = P.A[key]
key = list(key)
key[dim1], key[dim2] = key[dim2], key[dim1]
A[tuple(key)] = val
return Poly(A, dim, shape, dtype) | [
"def",
"swapdim",
"(",
"P",
",",
"dim1",
"=",
"1",
",",
"dim2",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"P",
",",
"Poly",
")",
":",
"return",
"numpy",
".",
"swapaxes",
"(",
"P",
",",
"dim1",
",",
"dim2",
")",
"dim",
"=",
"P",
".",... | Swap the dim between two variables.
Args:
P (Poly):
Input polynomial.
dim1 (int):
First dim
dim2 (int):
Second dim.
Returns:
(Poly):
Polynomial with swapped dimensions.
Examples:
>>> x,y = variable(2)
>>> P = x**4-y
>>> print(P)
q0^4-q1
>>> print(swapdim(P))
q1^4-q0 | [
"Swap",
"the",
"dim",
"between",
"two",
"variables",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L259-L307 | train | 207,012 |
jonathf/chaospy | chaospy/poly/collection/core.py | tril | def tril(P, k=0):
"""Lower triangle of coefficients."""
A = P.A.copy()
for key in P.keys:
A[key] = numpy.tril(P.A[key])
return Poly(A, dim=P.dim, shape=P.shape) | python | def tril(P, k=0):
"""Lower triangle of coefficients."""
A = P.A.copy()
for key in P.keys:
A[key] = numpy.tril(P.A[key])
return Poly(A, dim=P.dim, shape=P.shape) | [
"def",
"tril",
"(",
"P",
",",
"k",
"=",
"0",
")",
":",
"A",
"=",
"P",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"P",
".",
"keys",
":",
"A",
"[",
"key",
"]",
"=",
"numpy",
".",
"tril",
"(",
"P",
".",
"A",
"[",
"key",
"]",
")... | Lower triangle of coefficients. | [
"Lower",
"triangle",
"of",
"coefficients",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L310-L315 | train | 207,013 |
jonathf/chaospy | chaospy/poly/collection/core.py | tricu | def tricu(P, k=0):
"""Cross-diagonal upper triangle."""
tri = numpy.sum(numpy.mgrid[[slice(0,_,1) for _ in P.shape]], 0)
tri = tri<len(tri) + k
if isinstance(P, Poly):
A = P.A.copy()
B = {}
for key in P.keys:
B[key] = A[key]*tri
return Poly(B, shape=P.shape, dim=P.dim, dtype=P.dtype)
out = P*tri
return out | python | def tricu(P, k=0):
"""Cross-diagonal upper triangle."""
tri = numpy.sum(numpy.mgrid[[slice(0,_,1) for _ in P.shape]], 0)
tri = tri<len(tri) + k
if isinstance(P, Poly):
A = P.A.copy()
B = {}
for key in P.keys:
B[key] = A[key]*tri
return Poly(B, shape=P.shape, dim=P.dim, dtype=P.dtype)
out = P*tri
return out | [
"def",
"tricu",
"(",
"P",
",",
"k",
"=",
"0",
")",
":",
"tri",
"=",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"mgrid",
"[",
"[",
"slice",
"(",
"0",
",",
"_",
",",
"1",
")",
"for",
"_",
"in",
"P",
".",
"shape",
"]",
"]",
",",
"0",
")",
"tr... | Cross-diagonal upper triangle. | [
"Cross",
"-",
"diagonal",
"upper",
"triangle",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L318-L331 | train | 207,014 |
jonathf/chaospy | chaospy/poly/collection/core.py | variable | def variable(dims=1):
"""
Simple constructor to create single variables to create polynomials.
Args:
dims (int):
Number of dimensions in the array.
Returns:
(Poly):
Polynomial array with unit components in each dimension.
Examples:
>>> print(variable())
q0
>>> print(variable(3))
[q0, q1, q2]
"""
if dims == 1:
return Poly({(1,): 1}, dim=1, shape=())
return Poly({
tuple(indices): indices for indices in numpy.eye(dims, dtype=int)
}, dim=dims, shape=(dims,)) | python | def variable(dims=1):
"""
Simple constructor to create single variables to create polynomials.
Args:
dims (int):
Number of dimensions in the array.
Returns:
(Poly):
Polynomial array with unit components in each dimension.
Examples:
>>> print(variable())
q0
>>> print(variable(3))
[q0, q1, q2]
"""
if dims == 1:
return Poly({(1,): 1}, dim=1, shape=())
return Poly({
tuple(indices): indices for indices in numpy.eye(dims, dtype=int)
}, dim=dims, shape=(dims,)) | [
"def",
"variable",
"(",
"dims",
"=",
"1",
")",
":",
"if",
"dims",
"==",
"1",
":",
"return",
"Poly",
"(",
"{",
"(",
"1",
",",
")",
":",
"1",
"}",
",",
"dim",
"=",
"1",
",",
"shape",
"=",
"(",
")",
")",
"return",
"Poly",
"(",
"{",
"tuple",
... | Simple constructor to create single variables to create polynomials.
Args:
dims (int):
Number of dimensions in the array.
Returns:
(Poly):
Polynomial array with unit components in each dimension.
Examples:
>>> print(variable())
q0
>>> print(variable(3))
[q0, q1, q2] | [
"Simple",
"constructor",
"to",
"create",
"single",
"variables",
"to",
"create",
"polynomials",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L334-L356 | train | 207,015 |
jonathf/chaospy | chaospy/poly/collection/core.py | all | def all(A, ax=None):
"""Test if all values in A evaluate to True """
if isinstance(A, Poly):
out = numpy.zeros(A.shape, dtype=bool)
B = A.A
for key in A.keys:
out += all(B[key], ax)
return out
return numpy.all(A, ax) | python | def all(A, ax=None):
"""Test if all values in A evaluate to True """
if isinstance(A, Poly):
out = numpy.zeros(A.shape, dtype=bool)
B = A.A
for key in A.keys:
out += all(B[key], ax)
return out
return numpy.all(A, ax) | [
"def",
"all",
"(",
"A",
",",
"ax",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"A",
",",
"Poly",
")",
":",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"A",
".",
"shape",
",",
"dtype",
"=",
"bool",
")",
"B",
"=",
"A",
".",
"A",
"for",
"key",... | Test if all values in A evaluate to True | [
"Test",
"if",
"all",
"values",
"in",
"A",
"evaluate",
"to",
"True"
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L367-L376 | train | 207,016 |
jonathf/chaospy | chaospy/poly/collection/core.py | around | def around(A, decimals=0):
"""
Evenly round to the given number of decimals.
Args:
A (Poly, numpy.ndarray):
Input data.
decimals (int):
Number of decimal places to round to (default: 0). If decimals is
negative, it specifies the number of positions to the left of the
decimal point.
Returns:
(Poly, numpy.ndarray):
Same type as A.
Examples:
>>> P = chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float)
>>> print(P)
[1.0, 0.25q0, 0.0625q0^2]
>>> print(chaospy.around(P))
[1.0, 0.0, 0.0]
>>> print(chaospy.around(P, 2))
[1.0, 0.25q0, 0.06q0^2]
"""
if isinstance(A, Poly):
B = A.A.copy()
for key in A.keys:
B[key] = around(B[key], decimals)
return Poly(B, A.dim, A.shape, A.dtype)
return numpy.around(A, decimals) | python | def around(A, decimals=0):
"""
Evenly round to the given number of decimals.
Args:
A (Poly, numpy.ndarray):
Input data.
decimals (int):
Number of decimal places to round to (default: 0). If decimals is
negative, it specifies the number of positions to the left of the
decimal point.
Returns:
(Poly, numpy.ndarray):
Same type as A.
Examples:
>>> P = chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float)
>>> print(P)
[1.0, 0.25q0, 0.0625q0^2]
>>> print(chaospy.around(P))
[1.0, 0.0, 0.0]
>>> print(chaospy.around(P, 2))
[1.0, 0.25q0, 0.06q0^2]
"""
if isinstance(A, Poly):
B = A.A.copy()
for key in A.keys:
B[key] = around(B[key], decimals)
return Poly(B, A.dim, A.shape, A.dtype)
return numpy.around(A, decimals) | [
"def",
"around",
"(",
"A",
",",
"decimals",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"A",
",",
"Poly",
")",
":",
"B",
"=",
"A",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"A",
".",
"keys",
":",
"B",
"[",
"key",
"]",
"=",
"ar... | Evenly round to the given number of decimals.
Args:
A (Poly, numpy.ndarray):
Input data.
decimals (int):
Number of decimal places to round to (default: 0). If decimals is
negative, it specifies the number of positions to the left of the
decimal point.
Returns:
(Poly, numpy.ndarray):
Same type as A.
Examples:
>>> P = chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float)
>>> print(P)
[1.0, 0.25q0, 0.0625q0^2]
>>> print(chaospy.around(P))
[1.0, 0.0, 0.0]
>>> print(chaospy.around(P, 2))
[1.0, 0.25q0, 0.06q0^2] | [
"Evenly",
"round",
"to",
"the",
"given",
"number",
"of",
"decimals",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L391-L422 | train | 207,017 |
jonathf/chaospy | chaospy/poly/collection/core.py | diag | def diag(A, k=0):
"""Extract or construct a diagonal polynomial array."""
if isinstance(A, Poly):
core, core_new = A.A, {}
for key in A.keys:
core_new[key] = numpy.diag(core[key], k)
return Poly(core_new, A.dim, None, A.dtype)
return numpy.diag(A, k) | python | def diag(A, k=0):
"""Extract or construct a diagonal polynomial array."""
if isinstance(A, Poly):
core, core_new = A.A, {}
for key in A.keys:
core_new[key] = numpy.diag(core[key], k)
return Poly(core_new, A.dim, None, A.dtype)
return numpy.diag(A, k) | [
"def",
"diag",
"(",
"A",
",",
"k",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"A",
",",
"Poly",
")",
":",
"core",
",",
"core_new",
"=",
"A",
".",
"A",
",",
"{",
"}",
"for",
"key",
"in",
"A",
".",
"keys",
":",
"core_new",
"[",
"key",
"]",
... | Extract or construct a diagonal polynomial array. | [
"Extract",
"or",
"construct",
"a",
"diagonal",
"polynomial",
"array",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L425-L434 | train | 207,018 |
jonathf/chaospy | chaospy/poly/collection/core.py | prune | def prune(A, threshold):
"""
Remove coefficients that is not larger than a given threshold.
Args:
A (Poly):
Input data.
threshold (float):
Threshold for which values to cut.
Returns:
(Poly):
Same type as A.
Examples:
>>> P = chaospy.sum(chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float))
>>> print(P)
0.0625q0^2+0.25q0+1.0
>>> print(chaospy.prune(P, 0.1))
0.25q0+1.0
>>> print(chaospy.prune(P, 0.5))
1.0
>>> print(chaospy.prune(P, 1.5))
0.0
"""
if isinstance(A, Poly):
B = A.A.copy()
for key in A.keys:
values = B[key].copy()
values[numpy.abs(values) < threshold] = 0.
B[key] = values
return Poly(B, A.dim, A.shape, A.dtype)
A = A.copy()
A[numpy.abs(A) < threshold] = 0.
return A | python | def prune(A, threshold):
"""
Remove coefficients that is not larger than a given threshold.
Args:
A (Poly):
Input data.
threshold (float):
Threshold for which values to cut.
Returns:
(Poly):
Same type as A.
Examples:
>>> P = chaospy.sum(chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float))
>>> print(P)
0.0625q0^2+0.25q0+1.0
>>> print(chaospy.prune(P, 0.1))
0.25q0+1.0
>>> print(chaospy.prune(P, 0.5))
1.0
>>> print(chaospy.prune(P, 1.5))
0.0
"""
if isinstance(A, Poly):
B = A.A.copy()
for key in A.keys:
values = B[key].copy()
values[numpy.abs(values) < threshold] = 0.
B[key] = values
return Poly(B, A.dim, A.shape, A.dtype)
A = A.copy()
A[numpy.abs(A) < threshold] = 0.
return A | [
"def",
"prune",
"(",
"A",
",",
"threshold",
")",
":",
"if",
"isinstance",
"(",
"A",
",",
"Poly",
")",
":",
"B",
"=",
"A",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"A",
".",
"keys",
":",
"values",
"=",
"B",
"[",
"key",
"]",
".",
... | Remove coefficients that is not larger than a given threshold.
Args:
A (Poly):
Input data.
threshold (float):
Threshold for which values to cut.
Returns:
(Poly):
Same type as A.
Examples:
>>> P = chaospy.sum(chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float))
>>> print(P)
0.0625q0^2+0.25q0+1.0
>>> print(chaospy.prune(P, 0.1))
0.25q0+1.0
>>> print(chaospy.prune(P, 0.5))
1.0
>>> print(chaospy.prune(P, 1.5))
0.0 | [
"Remove",
"coefficients",
"that",
"is",
"not",
"larger",
"than",
"a",
"given",
"threshold",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/core.py#L457-L492 | train | 207,019 |
jonathf/chaospy | chaospy/distributions/operators/joint.py | J._range | def _range(self, xloc, cache):
"""
Special handle for finding bounds on constrained dists.
Example:
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.range())
[[0. 0.]
[1. 2.]]
"""
uloc = numpy.zeros((2, len(self)))
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
xloc_ = xloc[idx].reshape(1, -1)
uloc[:, idx] = evaluation.evaluate_bound(
dist, xloc_, cache=cache).flatten()
return uloc | python | def _range(self, xloc, cache):
"""
Special handle for finding bounds on constrained dists.
Example:
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.range())
[[0. 0.]
[1. 2.]]
"""
uloc = numpy.zeros((2, len(self)))
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
xloc_ = xloc[idx].reshape(1, -1)
uloc[:, idx] = evaluation.evaluate_bound(
dist, xloc_, cache=cache).flatten()
return uloc | [
"def",
"_range",
"(",
"self",
",",
"xloc",
",",
"cache",
")",
":",
"uloc",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"2",
",",
"len",
"(",
"self",
")",
")",
")",
"for",
"dist",
"in",
"evaluation",
".",
"sorted_dependencies",
"(",
"self",
",",
"reverse"... | Special handle for finding bounds on constrained dists.
Example:
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.range())
[[0. 0.]
[1. 2.]] | [
"Special",
"handle",
"for",
"finding",
"bounds",
"on",
"constrained",
"dists",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/joint.py#L76-L95 | train | 207,020 |
jonathf/chaospy | chaospy/descriptives/correlation/spearman.py | Spearman | def Spearman(poly, dist, sample=10000, retall=False, **kws):
"""
Calculate Spearman's rank-order correlation coefficient.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where correlation is taken.
sample (int):
Number of samples used in estimation.
retall (bool):
If true, return p-value as well.
Returns:
(float, numpy.ndarray):
Correlation output ``rho``. Of type float if two-dimensional problem.
Correleation matrix if larger.
(float, numpy.ndarray):
The two-sided p-value for a hypothesis test whose null hypothesis
is that two sets of data are uncorrelated, has same dimension as
``rho``.
"""
samples = dist.sample(sample, **kws)
poly = polynomials.flatten(poly)
Y = poly(*samples)
if retall:
return spearmanr(Y.T)
return spearmanr(Y.T)[0] | python | def Spearman(poly, dist, sample=10000, retall=False, **kws):
"""
Calculate Spearman's rank-order correlation coefficient.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where correlation is taken.
sample (int):
Number of samples used in estimation.
retall (bool):
If true, return p-value as well.
Returns:
(float, numpy.ndarray):
Correlation output ``rho``. Of type float if two-dimensional problem.
Correleation matrix if larger.
(float, numpy.ndarray):
The two-sided p-value for a hypothesis test whose null hypothesis
is that two sets of data are uncorrelated, has same dimension as
``rho``.
"""
samples = dist.sample(sample, **kws)
poly = polynomials.flatten(poly)
Y = poly(*samples)
if retall:
return spearmanr(Y.T)
return spearmanr(Y.T)[0] | [
"def",
"Spearman",
"(",
"poly",
",",
"dist",
",",
"sample",
"=",
"10000",
",",
"retall",
"=",
"False",
",",
"*",
"*",
"kws",
")",
":",
"samples",
"=",
"dist",
".",
"sample",
"(",
"sample",
",",
"*",
"*",
"kws",
")",
"poly",
"=",
"polynomials",
".... | Calculate Spearman's rank-order correlation coefficient.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where correlation is taken.
sample (int):
Number of samples used in estimation.
retall (bool):
If true, return p-value as well.
Returns:
(float, numpy.ndarray):
Correlation output ``rho``. Of type float if two-dimensional problem.
Correleation matrix if larger.
(float, numpy.ndarray):
The two-sided p-value for a hypothesis test whose null hypothesis
is that two sets of data are uncorrelated, has same dimension as
``rho``. | [
"Calculate",
"Spearman",
"s",
"rank",
"-",
"order",
"correlation",
"coefficient",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/correlation/spearman.py#L5-L33 | train | 207,021 |
jonathf/chaospy | chaospy/distributions/copulas/baseclass.py | Archimedean._diff | def _diff(self, x, th, eps):
"""
Differentiation function.
Numerical approximation of a Rosenblatt transformation created from
copula formulation.
"""
foo = lambda y: self.igen(numpy.sum(self.gen(y, th), 0), th)
out1 = out2 = 0.
sign = 1 - 2*(x > .5).T
for I in numpy.ndindex(*((2,)*(len(x)-1)+(1,))):
eps_ = numpy.array(I)*eps
x_ = (x.T + sign*eps_).T
out1 += (-1)**sum(I)*foo(x_)
x_[-1] = 1
out2 += (-1)**sum(I)*foo(x_)
out = out1/out2
return out | python | def _diff(self, x, th, eps):
"""
Differentiation function.
Numerical approximation of a Rosenblatt transformation created from
copula formulation.
"""
foo = lambda y: self.igen(numpy.sum(self.gen(y, th), 0), th)
out1 = out2 = 0.
sign = 1 - 2*(x > .5).T
for I in numpy.ndindex(*((2,)*(len(x)-1)+(1,))):
eps_ = numpy.array(I)*eps
x_ = (x.T + sign*eps_).T
out1 += (-1)**sum(I)*foo(x_)
x_[-1] = 1
out2 += (-1)**sum(I)*foo(x_)
out = out1/out2
return out | [
"def",
"_diff",
"(",
"self",
",",
"x",
",",
"th",
",",
"eps",
")",
":",
"foo",
"=",
"lambda",
"y",
":",
"self",
".",
"igen",
"(",
"numpy",
".",
"sum",
"(",
"self",
".",
"gen",
"(",
"y",
",",
"th",
")",
",",
"0",
")",
",",
"th",
")",
"out1... | Differentiation function.
Numerical approximation of a Rosenblatt transformation created from
copula formulation. | [
"Differentiation",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/copulas/baseclass.py#L166-L187 | train | 207,022 |
push-things/django-th | django_th/forms/services.py | available_services | def available_services():
"""
get the available services to be activated
read the models dir to find the services installed
to be added to the system by the administrator
"""
all_datas = ()
data = ()
for class_path in settings.TH_SERVICES:
class_name = class_path.rsplit('.', 1)[1]
# 2nd array position contains the name of the service
data = (class_name, class_name.rsplit('Service', 1)[1])
all_datas = (data,) + all_datas
return all_datas | python | def available_services():
"""
get the available services to be activated
read the models dir to find the services installed
to be added to the system by the administrator
"""
all_datas = ()
data = ()
for class_path in settings.TH_SERVICES:
class_name = class_path.rsplit('.', 1)[1]
# 2nd array position contains the name of the service
data = (class_name, class_name.rsplit('Service', 1)[1])
all_datas = (data,) + all_datas
return all_datas | [
"def",
"available_services",
"(",
")",
":",
"all_datas",
"=",
"(",
")",
"data",
"=",
"(",
")",
"for",
"class_path",
"in",
"settings",
".",
"TH_SERVICES",
":",
"class_name",
"=",
"class_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"1",
"]",
"... | get the available services to be activated
read the models dir to find the services installed
to be added to the system by the administrator | [
"get",
"the",
"available",
"services",
"to",
"be",
"activated"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/forms/services.py#L7-L22 | train | 207,023 |
push-things/django-th | django_th/management/commands/read_n_pub.py | Command.handle | def handle(self, *args, **options):
"""
get the trigger to fire
"""
trigger_id = options.get('trigger_id')
trigger = TriggerService.objects.filter(
id=int(trigger_id),
status=True,
user__is_active=True,
provider_failed__lt=settings.DJANGO_TH.get('failed_tries', 10),
consumer_failed__lt=settings.DJANGO_TH.get('failed_tries', 10)
).select_related('consumer__name', 'provider__name')
try:
with Pool(processes=1) as pool:
r = Read()
result = pool.map_async(r.reading, trigger)
result.get(timeout=360)
p = Pub()
result = pool.map_async(p.publishing, trigger)
result.get(timeout=360)
cache.delete('django_th' + '_fire_trigger_' + str(trigger_id))
except TimeoutError as e:
logger.warning(e) | python | def handle(self, *args, **options):
"""
get the trigger to fire
"""
trigger_id = options.get('trigger_id')
trigger = TriggerService.objects.filter(
id=int(trigger_id),
status=True,
user__is_active=True,
provider_failed__lt=settings.DJANGO_TH.get('failed_tries', 10),
consumer_failed__lt=settings.DJANGO_TH.get('failed_tries', 10)
).select_related('consumer__name', 'provider__name')
try:
with Pool(processes=1) as pool:
r = Read()
result = pool.map_async(r.reading, trigger)
result.get(timeout=360)
p = Pub()
result = pool.map_async(p.publishing, trigger)
result.get(timeout=360)
cache.delete('django_th' + '_fire_trigger_' + str(trigger_id))
except TimeoutError as e:
logger.warning(e) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"trigger_id",
"=",
"options",
".",
"get",
"(",
"'trigger_id'",
")",
"trigger",
"=",
"TriggerService",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"int",
"(",
"trig... | get the trigger to fire | [
"get",
"the",
"trigger",
"to",
"fire"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/management/commands/read_n_pub.py#L27-L50 | train | 207,024 |
push-things/django-th | th_pushbullet/my_pushbullet.py | ServicePushbullet.read_data | def read_data(self, **kwargs):
"""
get the data from the service
as the pushbullet service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs.get('trigger_id')
trigger = Pushbullet.objects.get(trigger_id=trigger_id)
date_triggered = kwargs.get('date_triggered')
data = list()
pushes = self.pushb.get_pushes()
for p in pushes:
title = 'From Pushbullet'
created = arrow.get(p.get('created'))
if created > date_triggered and p.get('type') == trigger.type and\
(p.get('sender_email') == p.get('receiver_email') or p.get('sender_email') is None):
title = title + ' Channel' if p.get('channel_iden') and p.get('title') is None else title
# if sender_email and receiver_email are the same ;
# that means that "I" made a note or something
# if sender_email is None, then "an API" does the post
body = p.get('body')
data.append({'title': title, 'content': body})
# digester
self.send_digest_event(trigger_id, title, '')
cache.set('th_pushbullet_' + str(trigger_id), data)
return data | python | def read_data(self, **kwargs):
"""
get the data from the service
as the pushbullet service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs.get('trigger_id')
trigger = Pushbullet.objects.get(trigger_id=trigger_id)
date_triggered = kwargs.get('date_triggered')
data = list()
pushes = self.pushb.get_pushes()
for p in pushes:
title = 'From Pushbullet'
created = arrow.get(p.get('created'))
if created > date_triggered and p.get('type') == trigger.type and\
(p.get('sender_email') == p.get('receiver_email') or p.get('sender_email') is None):
title = title + ' Channel' if p.get('channel_iden') and p.get('title') is None else title
# if sender_email and receiver_email are the same ;
# that means that "I" made a note or something
# if sender_email is None, then "an API" does the post
body = p.get('body')
data.append({'title': title, 'content': body})
# digester
self.send_digest_event(trigger_id, title, '')
cache.set('th_pushbullet_' + str(trigger_id), data)
return data | [
"def",
"read_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"trigger_id",
"=",
"kwargs",
".",
"get",
"(",
"'trigger_id'",
")",
"trigger",
"=",
"Pushbullet",
".",
"objects",
".",
"get",
"(",
"trigger_id",
"=",
"trigger_id",
")",
"date_triggered",
... | get the data from the service
as the pushbullet service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list | [
"get",
"the",
"data",
"from",
"the",
"service",
"as",
"the",
"pushbullet",
"service",
"does",
"not",
"have",
"any",
"date",
"in",
"its",
"API",
"linked",
"to",
"the",
"note",
"add",
"the",
"triggered",
"date",
"to",
"the",
"dict",
"data",
"thus",
"the",
... | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_pushbullet/my_pushbullet.py#L55-L89 | train | 207,025 |
push-things/django-th | django_th/html_entities.py | HtmlEntities.html_entity_decode_char | def html_entity_decode_char(self, m, defs=htmlentities.entitydefs):
"""
decode html entity into one of the html char
"""
try:
char = defs[m.group(1)]
return "&{char};".format(char=char)
except ValueError:
return m.group(0)
except KeyError:
return m.group(0) | python | def html_entity_decode_char(self, m, defs=htmlentities.entitydefs):
"""
decode html entity into one of the html char
"""
try:
char = defs[m.group(1)]
return "&{char};".format(char=char)
except ValueError:
return m.group(0)
except KeyError:
return m.group(0) | [
"def",
"html_entity_decode_char",
"(",
"self",
",",
"m",
",",
"defs",
"=",
"htmlentities",
".",
"entitydefs",
")",
":",
"try",
":",
"char",
"=",
"defs",
"[",
"m",
".",
"group",
"(",
"1",
")",
"]",
"return",
"\"&{char};\"",
".",
"format",
"(",
"char",
... | decode html entity into one of the html char | [
"decode",
"html",
"entity",
"into",
"one",
"of",
"the",
"html",
"char"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/html_entities.py#L11-L21 | train | 207,026 |
push-things/django-th | django_th/html_entities.py | HtmlEntities.html_entity_decode_codepoint | def html_entity_decode_codepoint(self, m,
defs=htmlentities.codepoint2name):
"""
decode html entity into one of the codepoint2name
"""
try:
char = defs[m.group(1)]
return "&{char};".format(char=char)
except ValueError:
return m.group(0)
except KeyError:
return m.group(0) | python | def html_entity_decode_codepoint(self, m,
defs=htmlentities.codepoint2name):
"""
decode html entity into one of the codepoint2name
"""
try:
char = defs[m.group(1)]
return "&{char};".format(char=char)
except ValueError:
return m.group(0)
except KeyError:
return m.group(0) | [
"def",
"html_entity_decode_codepoint",
"(",
"self",
",",
"m",
",",
"defs",
"=",
"htmlentities",
".",
"codepoint2name",
")",
":",
"try",
":",
"char",
"=",
"defs",
"[",
"m",
".",
"group",
"(",
"1",
")",
"]",
"return",
"\"&{char};\"",
".",
"format",
"(",
... | decode html entity into one of the codepoint2name | [
"decode",
"html",
"entity",
"into",
"one",
"of",
"the",
"codepoint2name"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/html_entities.py#L23-L34 | train | 207,027 |
push-things/django-th | django_th/html_entities.py | HtmlEntities.html_entity_decode | def html_entity_decode(self):
"""
entry point of this set of tools
to decode html entities
"""
pattern = re.compile(r"&#(\w+?);")
string = pattern.sub(self.html_entity_decode_char, self.my_string)
return pattern.sub(self.html_entity_decode_codepoint, string) | python | def html_entity_decode(self):
"""
entry point of this set of tools
to decode html entities
"""
pattern = re.compile(r"&#(\w+?);")
string = pattern.sub(self.html_entity_decode_char, self.my_string)
return pattern.sub(self.html_entity_decode_codepoint, string) | [
"def",
"html_entity_decode",
"(",
"self",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"&#(\\w+?);\"",
")",
"string",
"=",
"pattern",
".",
"sub",
"(",
"self",
".",
"html_entity_decode_char",
",",
"self",
".",
"my_string",
")",
"return",
"pattern",... | entry point of this set of tools
to decode html entities | [
"entry",
"point",
"of",
"this",
"set",
"of",
"tools",
"to",
"decode",
"html",
"entities"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/html_entities.py#L37-L44 | train | 207,028 |
push-things/django-th | th_pocket/my_pocket.py | ServicePocket.read_data | def read_data(self, **kwargs):
"""
get the data from the service
As the pocket service does not have any date in its API linked to the note,
add the triggered date to the dict data thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs.get('trigger_id')
date_triggered = kwargs.get('date_triggered')
data = list()
# pocket uses a timestamp date format
since = arrow.get(date_triggered).timestamp
if self.token is not None:
# get the data from the last time the trigger have been started
# timestamp form
pockets = self.pocket.get(since=since, state="unread")
content = ''
if pockets is not None and len(pockets[0]['list']) > 0:
for my_pocket in pockets[0]['list'].values():
if my_pocket.get('excerpt'):
content = my_pocket['excerpt']
elif my_pocket.get('given_title'):
content = my_pocket['given_title']
my_date = arrow.get(str(date_triggered), 'YYYY-MM-DD HH:mm:ss').to(settings.TIME_ZONE)
data.append({'my_date': str(my_date),
'tag': '',
'link': my_pocket['given_url'],
'title': my_pocket['given_title'],
'content': content,
'tweet_id': 0})
# digester
self.send_digest_event(trigger_id, my_pocket['given_title'], my_pocket['given_url'])
cache.set('th_pocket_' + str(trigger_id), data)
return data | python | def read_data(self, **kwargs):
"""
get the data from the service
As the pocket service does not have any date in its API linked to the note,
add the triggered date to the dict data thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs.get('trigger_id')
date_triggered = kwargs.get('date_triggered')
data = list()
# pocket uses a timestamp date format
since = arrow.get(date_triggered).timestamp
if self.token is not None:
# get the data from the last time the trigger have been started
# timestamp form
pockets = self.pocket.get(since=since, state="unread")
content = ''
if pockets is not None and len(pockets[0]['list']) > 0:
for my_pocket in pockets[0]['list'].values():
if my_pocket.get('excerpt'):
content = my_pocket['excerpt']
elif my_pocket.get('given_title'):
content = my_pocket['given_title']
my_date = arrow.get(str(date_triggered), 'YYYY-MM-DD HH:mm:ss').to(settings.TIME_ZONE)
data.append({'my_date': str(my_date),
'tag': '',
'link': my_pocket['given_url'],
'title': my_pocket['given_title'],
'content': content,
'tweet_id': 0})
# digester
self.send_digest_event(trigger_id, my_pocket['given_title'], my_pocket['given_url'])
cache.set('th_pocket_' + str(trigger_id), data)
return data | [
"def",
"read_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"trigger_id",
"=",
"kwargs",
".",
"get",
"(",
"'trigger_id'",
")",
"date_triggered",
"=",
"kwargs",
".",
"get",
"(",
"'date_triggered'",
")",
"data",
"=",
"list",
"(",
")",
"# pocket use... | get the data from the service
As the pocket service does not have any date in its API linked to the note,
add the triggered date to the dict data thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list | [
"get",
"the",
"data",
"from",
"the",
"service",
"As",
"the",
"pocket",
"service",
"does",
"not",
"have",
"any",
"date",
"in",
"its",
"API",
"linked",
"to",
"the",
"note",
"add",
"the",
"triggered",
"date",
"to",
"the",
"dict",
"data",
"thus",
"the",
"s... | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_pocket/my_pocket.py#L74-L114 | train | 207,029 |
push-things/django-th | th_evernote/sanitize.py | remove_prohibited_element | def remove_prohibited_element(tag_name, document_element):
"""
To fit the Evernote DTD need, drop this tag name
"""
elements = document_element.getElementsByTagName(tag_name)
for element in elements:
p = element.parentNode
p.removeChild(element) | python | def remove_prohibited_element(tag_name, document_element):
"""
To fit the Evernote DTD need, drop this tag name
"""
elements = document_element.getElementsByTagName(tag_name)
for element in elements:
p = element.parentNode
p.removeChild(element) | [
"def",
"remove_prohibited_element",
"(",
"tag_name",
",",
"document_element",
")",
":",
"elements",
"=",
"document_element",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"for",
"element",
"in",
"elements",
":",
"p",
"=",
"element",
".",
"parentNode",
"p",
... | To fit the Evernote DTD need, drop this tag name | [
"To",
"fit",
"the",
"Evernote",
"DTD",
"need",
"drop",
"this",
"tag",
"name"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/sanitize.py#L42-L49 | train | 207,030 |
push-things/django-th | django_th/services/services.py | ServicesMgr._get_content | def _get_content(data, which_content):
"""
get the content that could be hidden
in the middle of "content" or "summary detail"
from the data of the provider
"""
content = ''
if data.get(which_content):
if isinstance(data.get(which_content), feedparser.FeedParserDict):
content = data.get(which_content)['value']
elif not isinstance(data.get(which_content), str):
if 'value' in data.get(which_content)[0]:
content = data.get(which_content)[0].value
else:
content = data.get(which_content)
return content | python | def _get_content(data, which_content):
"""
get the content that could be hidden
in the middle of "content" or "summary detail"
from the data of the provider
"""
content = ''
if data.get(which_content):
if isinstance(data.get(which_content), feedparser.FeedParserDict):
content = data.get(which_content)['value']
elif not isinstance(data.get(which_content), str):
if 'value' in data.get(which_content)[0]:
content = data.get(which_content)[0].value
else:
content = data.get(which_content)
return content | [
"def",
"_get_content",
"(",
"data",
",",
"which_content",
")",
":",
"content",
"=",
"''",
"if",
"data",
".",
"get",
"(",
"which_content",
")",
":",
"if",
"isinstance",
"(",
"data",
".",
"get",
"(",
"which_content",
")",
",",
"feedparser",
".",
"FeedParse... | get the content that could be hidden
in the middle of "content" or "summary detail"
from the data of the provider | [
"get",
"the",
"content",
"that",
"could",
"be",
"hidden",
"in",
"the",
"middle",
"of",
"content",
"or",
"summary",
"detail",
"from",
"the",
"data",
"of",
"the",
"provider"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/services/services.py#L64-L79 | train | 207,031 |
push-things/django-th | django_th/services/services.py | ServicesMgr.get_request_token | def get_request_token(self, request):
"""
request the token to the external service
"""
if self.oauth == 'oauth1':
oauth = OAuth1Session(self.consumer_key, client_secret=self.consumer_secret)
request_token = oauth.fetch_request_token(self.REQ_TOKEN)
# Save the request token information for later
request.session['oauth_token'] = request_token['oauth_token']
request.session['oauth_token_secret'] = request_token['oauth_token_secret']
return request_token
else:
callback_url = self.callback_url(request)
oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope)
authorization_url, state = oauth.authorization_url(self.AUTH_URL)
return authorization_url | python | def get_request_token(self, request):
"""
request the token to the external service
"""
if self.oauth == 'oauth1':
oauth = OAuth1Session(self.consumer_key, client_secret=self.consumer_secret)
request_token = oauth.fetch_request_token(self.REQ_TOKEN)
# Save the request token information for later
request.session['oauth_token'] = request_token['oauth_token']
request.session['oauth_token_secret'] = request_token['oauth_token_secret']
return request_token
else:
callback_url = self.callback_url(request)
oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope)
authorization_url, state = oauth.authorization_url(self.AUTH_URL)
return authorization_url | [
"def",
"get_request_token",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"oauth",
"==",
"'oauth1'",
":",
"oauth",
"=",
"OAuth1Session",
"(",
"self",
".",
"consumer_key",
",",
"client_secret",
"=",
"self",
".",
"consumer_secret",
")",
"request_to... | request the token to the external service | [
"request",
"the",
"token",
"to",
"the",
"external",
"service"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/services/services.py#L235-L251 | train | 207,032 |
push-things/django-th | th_evernote/my_evernote.py | ServiceEvernote.save_data | def save_data(self, trigger_id, **data):
"""
let's save the data
don't want to handle empty title nor content
otherwise this will produce an Exception by
the Evernote's API
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean
"""
# set the title and content of the data
title, content = super(ServiceEvernote, self).save_data(trigger_id, **data)
# get the evernote data of this trigger
trigger = Evernote.objects.get(trigger_id=trigger_id)
# initialize notestore process
note_store = self._notestore(trigger_id, data)
if isinstance(note_store, evernote.api.client.Store):
# note object
note = self._notebook(trigger, note_store)
# its attributes
note = self._attributes(note, data)
# its footer
content = self._footer(trigger, data, content)
# its title
note.title = limit_content(title, 255)
# its content
note = self._content(note, content)
# create a note
return EvernoteMgr.create_note(note_store, note, trigger_id, data)
else:
# so its note an evernote object, so something wrong happens
return note_store | python | def save_data(self, trigger_id, **data):
"""
let's save the data
don't want to handle empty title nor content
otherwise this will produce an Exception by
the Evernote's API
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean
"""
# set the title and content of the data
title, content = super(ServiceEvernote, self).save_data(trigger_id, **data)
# get the evernote data of this trigger
trigger = Evernote.objects.get(trigger_id=trigger_id)
# initialize notestore process
note_store = self._notestore(trigger_id, data)
if isinstance(note_store, evernote.api.client.Store):
# note object
note = self._notebook(trigger, note_store)
# its attributes
note = self._attributes(note, data)
# its footer
content = self._footer(trigger, data, content)
# its title
note.title = limit_content(title, 255)
# its content
note = self._content(note, content)
# create a note
return EvernoteMgr.create_note(note_store, note, trigger_id, data)
else:
# so its note an evernote object, so something wrong happens
return note_store | [
"def",
"save_data",
"(",
"self",
",",
"trigger_id",
",",
"*",
"*",
"data",
")",
":",
"# set the title and content of the data",
"title",
",",
"content",
"=",
"super",
"(",
"ServiceEvernote",
",",
"self",
")",
".",
"save_data",
"(",
"trigger_id",
",",
"*",
"*... | let's save the data
don't want to handle empty title nor content
otherwise this will produce an Exception by
the Evernote's API
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | [
"let",
"s",
"save",
"the",
"data",
"don",
"t",
"want",
"to",
"handle",
"empty",
"title",
"nor",
"content",
"otherwise",
"this",
"will",
"produce",
"an",
"Exception",
"by",
"the",
"Evernote",
"s",
"API"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/my_evernote.py#L142-L177 | train | 207,033 |
push-things/django-th | th_evernote/my_evernote.py | ServiceEvernote.get_evernote_client | def get_evernote_client(self, token=None):
"""
get the token from evernote
"""
if token:
return EvernoteClient(token=token, sandbox=self.sandbox)
else:
return EvernoteClient(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret,
sandbox=self.sandbox) | python | def get_evernote_client(self, token=None):
"""
get the token from evernote
"""
if token:
return EvernoteClient(token=token, sandbox=self.sandbox)
else:
return EvernoteClient(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret,
sandbox=self.sandbox) | [
"def",
"get_evernote_client",
"(",
"self",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
":",
"return",
"EvernoteClient",
"(",
"token",
"=",
"token",
",",
"sandbox",
"=",
"self",
".",
"sandbox",
")",
"else",
":",
"return",
"EvernoteClient",
"(",
"c... | get the token from evernote | [
"get",
"the",
"token",
"from",
"evernote"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/my_evernote.py#L265-L273 | train | 207,034 |
push-things/django-th | th_evernote/my_evernote.py | ServiceEvernote.auth | def auth(self, request):
"""
let's auth the user to the Service
"""
client = self.get_evernote_client()
request_token = client.get_request_token(self.callback_url(request))
# Save the request token information for later
request.session['oauth_token'] = request_token['oauth_token']
request.session['oauth_token_secret'] = request_token['oauth_token_secret']
# Redirect the user to the Evernote authorization URL
# return the URL string which will be used by redirect()
# from the calling func
return client.get_authorize_url(request_token) | python | def auth(self, request):
"""
let's auth the user to the Service
"""
client = self.get_evernote_client()
request_token = client.get_request_token(self.callback_url(request))
# Save the request token information for later
request.session['oauth_token'] = request_token['oauth_token']
request.session['oauth_token_secret'] = request_token['oauth_token_secret']
# Redirect the user to the Evernote authorization URL
# return the URL string which will be used by redirect()
# from the calling func
return client.get_authorize_url(request_token) | [
"def",
"auth",
"(",
"self",
",",
"request",
")",
":",
"client",
"=",
"self",
".",
"get_evernote_client",
"(",
")",
"request_token",
"=",
"client",
".",
"get_request_token",
"(",
"self",
".",
"callback_url",
"(",
"request",
")",
")",
"# Save the request token i... | let's auth the user to the Service | [
"let",
"s",
"auth",
"the",
"user",
"to",
"the",
"Service"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/my_evernote.py#L275-L287 | train | 207,035 |
push-things/django-th | django_th/views.py | TriggerListView.get_context_data | def get_context_data(self, **kwargs):
"""
get the data of the view
data are :
1) number of triggers enabled
2) number of triggers disabled
3) number of activated services
4) list of activated services by the connected user
"""
triggers_enabled = triggers_disabled = services_activated = ()
context = super(TriggerListView, self).get_context_data(**kwargs)
if self.kwargs.get('trigger_filtered_by'):
page_link = reverse('trigger_filter_by',
kwargs={'trigger_filtered_by':
self.kwargs.get('trigger_filtered_by')})
elif self.kwargs.get('trigger_ordered_by'):
page_link = reverse('trigger_order_by',
kwargs={'trigger_ordered_by':
self.kwargs.get('trigger_ordered_by')})
else:
page_link = reverse('home')
if self.request.user.is_authenticated:
# get the enabled triggers
triggers_enabled = TriggerService.objects.filter(
user=self.request.user, status=1).count()
# get the disabled triggers
triggers_disabled = TriggerService.objects.filter(
user=self.request.user, status=0).count()
# get the activated services
user_service = UserService.objects.filter(user=self.request.user)
"""
List of triggers activated by the user
"""
context['trigger_filter_by'] = user_service
"""
number of service activated for the current user
"""
services_activated = user_service.count()
"""
which triggers are enabled/disabled
"""
context['nb_triggers'] = {'enabled': triggers_enabled,
'disabled': triggers_disabled}
"""
Number of services activated
"""
context['nb_services'] = services_activated
context['page_link'] = page_link
context['fire'] = settings.DJANGO_TH.get('fire', False)
return context | python | def get_context_data(self, **kwargs):
"""
get the data of the view
data are :
1) number of triggers enabled
2) number of triggers disabled
3) number of activated services
4) list of activated services by the connected user
"""
triggers_enabled = triggers_disabled = services_activated = ()
context = super(TriggerListView, self).get_context_data(**kwargs)
if self.kwargs.get('trigger_filtered_by'):
page_link = reverse('trigger_filter_by',
kwargs={'trigger_filtered_by':
self.kwargs.get('trigger_filtered_by')})
elif self.kwargs.get('trigger_ordered_by'):
page_link = reverse('trigger_order_by',
kwargs={'trigger_ordered_by':
self.kwargs.get('trigger_ordered_by')})
else:
page_link = reverse('home')
if self.request.user.is_authenticated:
# get the enabled triggers
triggers_enabled = TriggerService.objects.filter(
user=self.request.user, status=1).count()
# get the disabled triggers
triggers_disabled = TriggerService.objects.filter(
user=self.request.user, status=0).count()
# get the activated services
user_service = UserService.objects.filter(user=self.request.user)
"""
List of triggers activated by the user
"""
context['trigger_filter_by'] = user_service
"""
number of service activated for the current user
"""
services_activated = user_service.count()
"""
which triggers are enabled/disabled
"""
context['nb_triggers'] = {'enabled': triggers_enabled,
'disabled': triggers_disabled}
"""
Number of services activated
"""
context['nb_services'] = services_activated
context['page_link'] = page_link
context['fire'] = settings.DJANGO_TH.get('fire', False)
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"triggers_enabled",
"=",
"triggers_disabled",
"=",
"services_activated",
"=",
"(",
")",
"context",
"=",
"super",
"(",
"TriggerListView",
",",
"self",
")",
".",
"get_context_data",
"(",
... | get the data of the view
data are :
1) number of triggers enabled
2) number of triggers disabled
3) number of activated services
4) list of activated services by the connected user | [
"get",
"the",
"data",
"of",
"the",
"view"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/views.py#L108-L164 | train | 207,036 |
push-things/django-th | th_rss/lib/feedsservice/feedsservice.py | Feeds.datas | def datas(self):
"""
read the data from a given URL or path to a local file
"""
data = feedparser.parse(self.URL_TO_PARSE, agent=self.USER_AGENT)
# when chardet says
# >>> chardet.detect(data)
# {'confidence': 0.99, 'encoding': 'utf-8'}
# bozo says sometimes
# >>> data.bozo_exception
# CharacterEncodingOverride('document declared as us-ascii, but parsed as utf-8', ) # invalid Feed
# so I remove this detection :(
# the issue come from the server that return a charset different from the feeds
# it is not related to Feedparser but from the HTTP server itself
if data.bozo == 1:
data.entries = ''
return data | python | def datas(self):
"""
read the data from a given URL or path to a local file
"""
data = feedparser.parse(self.URL_TO_PARSE, agent=self.USER_AGENT)
# when chardet says
# >>> chardet.detect(data)
# {'confidence': 0.99, 'encoding': 'utf-8'}
# bozo says sometimes
# >>> data.bozo_exception
# CharacterEncodingOverride('document declared as us-ascii, but parsed as utf-8', ) # invalid Feed
# so I remove this detection :(
# the issue come from the server that return a charset different from the feeds
# it is not related to Feedparser but from the HTTP server itself
if data.bozo == 1:
data.entries = ''
return data | [
"def",
"datas",
"(",
"self",
")",
":",
"data",
"=",
"feedparser",
".",
"parse",
"(",
"self",
".",
"URL_TO_PARSE",
",",
"agent",
"=",
"self",
".",
"USER_AGENT",
")",
"# when chardet says",
"# >>> chardet.detect(data)",
"# {'confidence': 0.99, 'encoding': 'utf-8'}",
"... | read the data from a given URL or path to a local file | [
"read",
"the",
"data",
"from",
"a",
"given",
"URL",
"or",
"path",
"to",
"a",
"local",
"file"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_rss/lib/feedsservice/feedsservice.py#L21-L39 | train | 207,037 |
push-things/django-th | django_th/views_wizard.py | finalcallback | def finalcallback(request, **kwargs):
"""
let's do the callback of the related service after
the auth request from UserServiceCreateView
"""
default_provider.load_services()
service_name = kwargs.get('service_name')
service_object = default_provider.get_service(service_name)
lets_callback = getattr(service_object, 'callback')
# call the auth func from this class
# and redirect to the external service page
# to auth the application django-th to access to the user
# account details
return render_to_response(lets_callback(request)) | python | def finalcallback(request, **kwargs):
"""
let's do the callback of the related service after
the auth request from UserServiceCreateView
"""
default_provider.load_services()
service_name = kwargs.get('service_name')
service_object = default_provider.get_service(service_name)
lets_callback = getattr(service_object, 'callback')
# call the auth func from this class
# and redirect to the external service page
# to auth the application django-th to access to the user
# account details
return render_to_response(lets_callback(request)) | [
"def",
"finalcallback",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"default_provider",
".",
"load_services",
"(",
")",
"service_name",
"=",
"kwargs",
".",
"get",
"(",
"'service_name'",
")",
"service_object",
"=",
"default_provider",
".",
"get_service",
... | let's do the callback of the related service after
the auth request from UserServiceCreateView | [
"let",
"s",
"do",
"the",
"callback",
"of",
"the",
"related",
"service",
"after",
"the",
"auth",
"request",
"from",
"UserServiceCreateView"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/views_wizard.py#L145-L158 | train | 207,038 |
push-things/django-th | th_rss/lib/conditionchecker/conditionchecker.py | Condition.filter_that | def filter_that(self, criteria, data):
'''
this method just use the module 're' to check if the data contain
the string to find
'''
import re
prog = re.compile(criteria)
return True if prog.match(data) else False | python | def filter_that(self, criteria, data):
'''
this method just use the module 're' to check if the data contain
the string to find
'''
import re
prog = re.compile(criteria)
return True if prog.match(data) else False | [
"def",
"filter_that",
"(",
"self",
",",
"criteria",
",",
"data",
")",
":",
"import",
"re",
"prog",
"=",
"re",
".",
"compile",
"(",
"criteria",
")",
"return",
"True",
"if",
"prog",
".",
"match",
"(",
"data",
")",
"else",
"False"
] | this method just use the module 're' to check if the data contain
the string to find | [
"this",
"method",
"just",
"use",
"the",
"module",
"re",
"to",
"check",
"if",
"the",
"data",
"contain",
"the",
"string",
"to",
"find"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_rss/lib/conditionchecker/conditionchecker.py#L53-L61 | train | 207,039 |
push-things/django-th | django_th/service_provider.py | ServiceProvider.load_services | def load_services(self, services=settings.TH_SERVICES):
"""
get the service from the settings
"""
kwargs = {}
for class_path in services:
module_name, class_name = class_path.rsplit('.', 1)
klass = import_from_path(class_path)
service = klass(None, **kwargs)
self.register(class_name, service) | python | def load_services(self, services=settings.TH_SERVICES):
"""
get the service from the settings
"""
kwargs = {}
for class_path in services:
module_name, class_name = class_path.rsplit('.', 1)
klass = import_from_path(class_path)
service = klass(None, **kwargs)
self.register(class_name, service) | [
"def",
"load_services",
"(",
"self",
",",
"services",
"=",
"settings",
".",
"TH_SERVICES",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"class_path",
"in",
"services",
":",
"module_name",
",",
"class_name",
"=",
"class_path",
".",
"rsplit",
"(",
"'.'",
",",
... | get the service from the settings | [
"get",
"the",
"service",
"from",
"the",
"settings"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/service_provider.py#L8-L17 | train | 207,040 |
push-things/django-th | django_th/recycle.py | recycle | def recycle():
"""
the purpose of this tasks is to recycle the data from the cache
with version=2 in the main cache
"""
# http://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk
for service in cache.iter_keys('th_*'):
try:
# get the value from the cache version=2
service_value = cache.get(service, version=2)
# put it in the version=1
cache.set(service, service_value)
# remote version=2
cache.delete_pattern(service, version=2)
except ValueError:
pass
logger.info('recycle of cache done!') | python | def recycle():
"""
the purpose of this tasks is to recycle the data from the cache
with version=2 in the main cache
"""
# http://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk
for service in cache.iter_keys('th_*'):
try:
# get the value from the cache version=2
service_value = cache.get(service, version=2)
# put it in the version=1
cache.set(service, service_value)
# remote version=2
cache.delete_pattern(service, version=2)
except ValueError:
pass
logger.info('recycle of cache done!') | [
"def",
"recycle",
"(",
")",
":",
"# http://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk",
"for",
"service",
"in",
"cache",
".",
"iter_keys",
"(",
"'th_*'",
")",
":",
"try",
":",
"# get the value from the cache version=2",
"service_value",
"=",
"cache",
... | the purpose of this tasks is to recycle the data from the cache
with version=2 in the main cache | [
"the",
"purpose",
"of",
"this",
"tasks",
"is",
"to",
"recycle",
"the",
"data",
"from",
"the",
"cache",
"with",
"version",
"=",
"2",
"in",
"the",
"main",
"cache"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/recycle.py#L14-L30 | train | 207,041 |
push-things/django-th | django_th/management/commands/send_digest.py | Command.handle | def handle(self, *args, **options):
"""
get all the digest data to send to each user
"""
now = arrow.utcnow().to(settings.TIME_ZONE)
now = now.date()
digest = Digest.objects.filter(date_end=str(now)).order_by('user', 'date_end')
users = digest.distinct('user')
subject = 'Your digester'
msg_plain = render_to_string('digest/email.txt', {'digest': digest, 'subject': subject})
msg_html = render_to_string('digest/email.html', {'digest': digest, 'subject': subject})
message = msg_plain
from_email = settings.ADMINS
recipient_list = ()
for user in users:
recipient_list += (user.user.email,)
send_mail(subject, message, from_email, recipient_list,
html_message=msg_html) | python | def handle(self, *args, **options):
"""
get all the digest data to send to each user
"""
now = arrow.utcnow().to(settings.TIME_ZONE)
now = now.date()
digest = Digest.objects.filter(date_end=str(now)).order_by('user', 'date_end')
users = digest.distinct('user')
subject = 'Your digester'
msg_plain = render_to_string('digest/email.txt', {'digest': digest, 'subject': subject})
msg_html = render_to_string('digest/email.html', {'digest': digest, 'subject': subject})
message = msg_plain
from_email = settings.ADMINS
recipient_list = ()
for user in users:
recipient_list += (user.user.email,)
send_mail(subject, message, from_email, recipient_list,
html_message=msg_html) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"now",
"=",
"arrow",
".",
"utcnow",
"(",
")",
".",
"to",
"(",
"settings",
".",
"TIME_ZONE",
")",
"now",
"=",
"now",
".",
"date",
"(",
")",
"digest",
"=",
"Diges... | get all the digest data to send to each user | [
"get",
"all",
"the",
"digest",
"data",
"to",
"send",
"to",
"each",
"user"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/management/commands/send_digest.py#L18-L39 | train | 207,042 |
push-things/django-th | th_evernote/evernote_mgr.py | EvernoteMgr.get_notebook | def get_notebook(note_store, my_notebook):
"""
get the notebook from its name
"""
notebook_id = 0
notebooks = note_store.listNotebooks()
# get the notebookGUID ...
for notebook in notebooks:
if notebook.name.lower() == my_notebook.lower():
notebook_id = notebook.guid
break
return notebook_id | python | def get_notebook(note_store, my_notebook):
"""
get the notebook from its name
"""
notebook_id = 0
notebooks = note_store.listNotebooks()
# get the notebookGUID ...
for notebook in notebooks:
if notebook.name.lower() == my_notebook.lower():
notebook_id = notebook.guid
break
return notebook_id | [
"def",
"get_notebook",
"(",
"note_store",
",",
"my_notebook",
")",
":",
"notebook_id",
"=",
"0",
"notebooks",
"=",
"note_store",
".",
"listNotebooks",
"(",
")",
"# get the notebookGUID ...",
"for",
"notebook",
"in",
"notebooks",
":",
"if",
"notebook",
".",
"name... | get the notebook from its name | [
"get",
"the",
"notebook",
"from",
"its",
"name"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/evernote_mgr.py#L22-L33 | train | 207,043 |
push-things/django-th | th_evernote/evernote_mgr.py | EvernoteMgr.set_notebook | def set_notebook(note_store, my_notebook, notebook_id):
"""
create a notebook
"""
if notebook_id == 0:
new_notebook = Types.Notebook()
new_notebook.name = my_notebook
new_notebook.defaultNotebook = False
notebook_id = note_store.createNotebook(new_notebook).guid
return notebook_id | python | def set_notebook(note_store, my_notebook, notebook_id):
"""
create a notebook
"""
if notebook_id == 0:
new_notebook = Types.Notebook()
new_notebook.name = my_notebook
new_notebook.defaultNotebook = False
notebook_id = note_store.createNotebook(new_notebook).guid
return notebook_id | [
"def",
"set_notebook",
"(",
"note_store",
",",
"my_notebook",
",",
"notebook_id",
")",
":",
"if",
"notebook_id",
"==",
"0",
":",
"new_notebook",
"=",
"Types",
".",
"Notebook",
"(",
")",
"new_notebook",
".",
"name",
"=",
"my_notebook",
"new_notebook",
".",
"d... | create a notebook | [
"create",
"a",
"notebook"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/evernote_mgr.py#L36-L45 | train | 207,044 |
push-things/django-th | th_evernote/evernote_mgr.py | EvernoteMgr.set_note_attribute | def set_note_attribute(data):
"""
add the link of the 'source' in the note
"""
na = False
if data.get('link'):
na = Types.NoteAttributes()
# add the url
na.sourceURL = data.get('link')
# add the object to the note
return na | python | def set_note_attribute(data):
"""
add the link of the 'source' in the note
"""
na = False
if data.get('link'):
na = Types.NoteAttributes()
# add the url
na.sourceURL = data.get('link')
# add the object to the note
return na | [
"def",
"set_note_attribute",
"(",
"data",
")",
":",
"na",
"=",
"False",
"if",
"data",
".",
"get",
"(",
"'link'",
")",
":",
"na",
"=",
"Types",
".",
"NoteAttributes",
"(",
")",
"# add the url",
"na",
".",
"sourceURL",
"=",
"data",
".",
"get",
"(",
"'l... | add the link of the 'source' in the note | [
"add",
"the",
"link",
"of",
"the",
"source",
"in",
"the",
"note"
] | 86c999d16bcf30b6224206e5b40824309834ac8c | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/evernote_mgr.py#L148-L158 | train | 207,045 |
EntilZha/PyFunctional | functional/util.py | is_primitive | def is_primitive(val):
"""
Checks if the passed value is a primitive type.
>>> is_primitive(1)
True
>>> is_primitive("abc")
True
>>> is_primitive(True)
True
>>> is_primitive({})
False
>>> is_primitive([])
False
>>> is_primitive(set([]))
:param val: value to check
:return: True if value is a primitive, else False
"""
return isinstance(val,
(str, bool, float, complex, bytes, six.text_type)
+ six.string_types + six.integer_types) | python | def is_primitive(val):
"""
Checks if the passed value is a primitive type.
>>> is_primitive(1)
True
>>> is_primitive("abc")
True
>>> is_primitive(True)
True
>>> is_primitive({})
False
>>> is_primitive([])
False
>>> is_primitive(set([]))
:param val: value to check
:return: True if value is a primitive, else False
"""
return isinstance(val,
(str, bool, float, complex, bytes, six.text_type)
+ six.string_types + six.integer_types) | [
"def",
"is_primitive",
"(",
"val",
")",
":",
"return",
"isinstance",
"(",
"val",
",",
"(",
"str",
",",
"bool",
",",
"float",
",",
"complex",
",",
"bytes",
",",
"six",
".",
"text_type",
")",
"+",
"six",
".",
"string_types",
"+",
"six",
".",
"integer_t... | Checks if the passed value is a primitive type.
>>> is_primitive(1)
True
>>> is_primitive("abc")
True
>>> is_primitive(True)
True
>>> is_primitive({})
False
>>> is_primitive([])
False
>>> is_primitive(set([]))
:param val: value to check
:return: True if value is a primitive, else False | [
"Checks",
"if",
"the",
"passed",
"value",
"is",
"a",
"primitive",
"type",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/util.py#L20-L46 | train | 207,046 |
EntilZha/PyFunctional | functional/util.py | split_every | def split_every(parts, iterable):
"""
Split an iterable into parts of length parts
>>> l = iter([1, 2, 3, 4])
>>> split_every(2, l)
[[1, 2], [3, 4]]
:param iterable: iterable to split
:param parts: number of chunks
:return: return the iterable split in parts
"""
return takewhile(bool, (list(islice(iterable, parts)) for _ in count())) | python | def split_every(parts, iterable):
"""
Split an iterable into parts of length parts
>>> l = iter([1, 2, 3, 4])
>>> split_every(2, l)
[[1, 2], [3, 4]]
:param iterable: iterable to split
:param parts: number of chunks
:return: return the iterable split in parts
"""
return takewhile(bool, (list(islice(iterable, parts)) for _ in count())) | [
"def",
"split_every",
"(",
"parts",
",",
"iterable",
")",
":",
"return",
"takewhile",
"(",
"bool",
",",
"(",
"list",
"(",
"islice",
"(",
"iterable",
",",
"parts",
")",
")",
"for",
"_",
"in",
"count",
"(",
")",
")",
")"
] | Split an iterable into parts of length parts
>>> l = iter([1, 2, 3, 4])
>>> split_every(2, l)
[[1, 2], [3, 4]]
:param iterable: iterable to split
:param parts: number of chunks
:return: return the iterable split in parts | [
"Split",
"an",
"iterable",
"into",
"parts",
"of",
"length",
"parts"
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/util.py#L105-L117 | train | 207,047 |
EntilZha/PyFunctional | functional/util.py | compute_partition_size | def compute_partition_size(result, processes):
"""
Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: Best partition size
"""
try:
return max(math.ceil(len(result) / processes), 1)
except TypeError:
return 1 | python | def compute_partition_size(result, processes):
"""
Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: Best partition size
"""
try:
return max(math.ceil(len(result) / processes), 1)
except TypeError:
return 1 | [
"def",
"compute_partition_size",
"(",
"result",
",",
"processes",
")",
":",
"try",
":",
"return",
"max",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"result",
")",
"/",
"processes",
")",
",",
"1",
")",
"except",
"TypeError",
":",
"return",
"1"
] | Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: Best partition size | [
"Attempts",
"to",
"compute",
"the",
"partition",
"size",
"to",
"evenly",
"distribute",
"work",
"across",
"processes",
".",
"Defaults",
"to",
"1",
"if",
"the",
"length",
"of",
"result",
"cannot",
"be",
"determined",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/util.py#L179-L191 | train | 207,048 |
EntilZha/PyFunctional | functional/lineage.py | Lineage.evaluate | def evaluate(self, sequence):
"""
Compute the lineage on the sequence.
:param sequence: Sequence to compute
:return: Evaluated sequence
"""
last_cache_index = self.cache_scan()
transformations = self.transformations[last_cache_index:]
return self.engine.evaluate(sequence, transformations) | python | def evaluate(self, sequence):
"""
Compute the lineage on the sequence.
:param sequence: Sequence to compute
:return: Evaluated sequence
"""
last_cache_index = self.cache_scan()
transformations = self.transformations[last_cache_index:]
return self.engine.evaluate(sequence, transformations) | [
"def",
"evaluate",
"(",
"self",
",",
"sequence",
")",
":",
"last_cache_index",
"=",
"self",
".",
"cache_scan",
"(",
")",
"transformations",
"=",
"self",
".",
"transformations",
"[",
"last_cache_index",
":",
"]",
"return",
"self",
".",
"engine",
".",
"evaluat... | Compute the lineage on the sequence.
:param sequence: Sequence to compute
:return: Evaluated sequence | [
"Compute",
"the",
"lineage",
"on",
"the",
"sequence",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/lineage.py#L56-L65 | train | 207,049 |
EntilZha/PyFunctional | functional/pipeline.py | _wrap | def _wrap(value):
"""
Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipeline.Sequence
:param value: value to wrap
:return: wrapped or not wrapped value
"""
if is_primitive(value):
return value
if isinstance(value, (dict, set)) or is_namedtuple(value):
return value
elif isinstance(value, collections.Iterable):
try:
if type(value).__name__ == 'DataFrame':
import pandas
if isinstance(value, pandas.DataFrame):
return Sequence(value.values)
except ImportError: # pragma: no cover
pass
return Sequence(value)
else:
return value | python | def _wrap(value):
"""
Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipeline.Sequence
:param value: value to wrap
:return: wrapped or not wrapped value
"""
if is_primitive(value):
return value
if isinstance(value, (dict, set)) or is_namedtuple(value):
return value
elif isinstance(value, collections.Iterable):
try:
if type(value).__name__ == 'DataFrame':
import pandas
if isinstance(value, pandas.DataFrame):
return Sequence(value.values)
except ImportError: # pragma: no cover
pass
return Sequence(value)
else:
return value | [
"def",
"_wrap",
"(",
"value",
")",
":",
"if",
"is_primitive",
"(",
"value",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"set",
")",
")",
"or",
"is_namedtuple",
"(",
"value",
")",
":",
"return",
"value",
"elif... | Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipeline.Sequence
:param value: value to wrap
:return: wrapped or not wrapped value | [
"Wraps",
"the",
"passed",
"value",
"in",
"a",
"Sequence",
"if",
"it",
"is",
"not",
"a",
"primitive",
".",
"If",
"it",
"is",
"a",
"string",
"argument",
"it",
"is",
"expanded",
"to",
"a",
"list",
"of",
"characters",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1694-L1726 | train | 207,050 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.cartesian | def cartesian(self, *iterables, **kwargs):
"""
Returns the cartesian product of the passed iterables with the specified number of
repetitions.
The keyword argument `repeat` is read from kwargs to pass to itertools.cartesian.
>>> seq.range(2).cartesian(range(2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
:param iterables: elements for cartesian product
:param kwargs: the variable `repeat` is read from kwargs
:return: cartesian product
"""
return self._transform(transformations.cartesian_t(iterables, kwargs.get('repeat', 1))) | python | def cartesian(self, *iterables, **kwargs):
"""
Returns the cartesian product of the passed iterables with the specified number of
repetitions.
The keyword argument `repeat` is read from kwargs to pass to itertools.cartesian.
>>> seq.range(2).cartesian(range(2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
:param iterables: elements for cartesian product
:param kwargs: the variable `repeat` is read from kwargs
:return: cartesian product
"""
return self._transform(transformations.cartesian_t(iterables, kwargs.get('repeat', 1))) | [
"def",
"cartesian",
"(",
"self",
",",
"*",
"iterables",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"cartesian_t",
"(",
"iterables",
",",
"kwargs",
".",
"get",
"(",
"'repeat'",
",",
"1",
")",
")"... | Returns the cartesian product of the passed iterables with the specified number of
repetitions.
The keyword argument `repeat` is read from kwargs to pass to itertools.cartesian.
>>> seq.range(2).cartesian(range(2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
:param iterables: elements for cartesian product
:param kwargs: the variable `repeat` is read from kwargs
:return: cartesian product | [
"Returns",
"the",
"cartesian",
"product",
"of",
"the",
"passed",
"iterables",
"with",
"the",
"specified",
"number",
"of",
"repetitions",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L350-L364 | train | 207,051 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.drop | def drop(self, n):
"""
Drop the first n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop(2)
[3, 4, 5]
:param n: number of elements to drop
:return: sequence without first n elements
"""
if n <= 0:
return self._transform(transformations.drop_t(0))
else:
return self._transform(transformations.drop_t(n)) | python | def drop(self, n):
"""
Drop the first n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop(2)
[3, 4, 5]
:param n: number of elements to drop
:return: sequence without first n elements
"""
if n <= 0:
return self._transform(transformations.drop_t(0))
else:
return self._transform(transformations.drop_t(n)) | [
"def",
"drop",
"(",
"self",
",",
"n",
")",
":",
"if",
"n",
"<=",
"0",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"drop_t",
"(",
"0",
")",
")",
"else",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
... | Drop the first n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop(2)
[3, 4, 5]
:param n: number of elements to drop
:return: sequence without first n elements | [
"Drop",
"the",
"first",
"n",
"elements",
"of",
"the",
"sequence",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L366-L379 | train | 207,052 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.drop_right | def drop_right(self, n):
"""
Drops the last n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop_right(2)
[1, 2, 3]
:param n: number of elements to drop
:return: sequence with last n elements dropped
"""
return self._transform(transformations.CACHE_T, transformations.drop_right_t(n)) | python | def drop_right(self, n):
"""
Drops the last n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop_right(2)
[1, 2, 3]
:param n: number of elements to drop
:return: sequence with last n elements dropped
"""
return self._transform(transformations.CACHE_T, transformations.drop_right_t(n)) | [
"def",
"drop_right",
"(",
"self",
",",
"n",
")",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"CACHE_T",
",",
"transformations",
".",
"drop_right_t",
"(",
"n",
")",
")"
] | Drops the last n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop_right(2)
[1, 2, 3]
:param n: number of elements to drop
:return: sequence with last n elements dropped | [
"Drops",
"the",
"last",
"n",
"elements",
"of",
"the",
"sequence",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L381-L391 | train | 207,053 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.take | def take(self, n):
"""
Take the first n elements of the sequence.
>>> seq([1, 2, 3, 4]).take(2)
[1, 2]
:param n: number of elements to take
:return: first n elements of sequence
"""
if n <= 0:
return self._transform(transformations.take_t(0))
else:
return self._transform(transformations.take_t(n)) | python | def take(self, n):
"""
Take the first n elements of the sequence.
>>> seq([1, 2, 3, 4]).take(2)
[1, 2]
:param n: number of elements to take
:return: first n elements of sequence
"""
if n <= 0:
return self._transform(transformations.take_t(0))
else:
return self._transform(transformations.take_t(n)) | [
"def",
"take",
"(",
"self",
",",
"n",
")",
":",
"if",
"n",
"<=",
"0",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"take_t",
"(",
"0",
")",
")",
"else",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
... | Take the first n elements of the sequence.
>>> seq([1, 2, 3, 4]).take(2)
[1, 2]
:param n: number of elements to take
:return: first n elements of sequence | [
"Take",
"the",
"first",
"n",
"elements",
"of",
"the",
"sequence",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L405-L418 | train | 207,054 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.count | def count(self, func):
"""
Counts the number of elements in the sequence which satisfy the predicate func.
>>> seq([-1, -2, 1, 2]).count(lambda x: x > 0)
2
:param func: predicate to count elements on
:return: count of elements that satisfy predicate
"""
n = 0
for element in self:
if func(element):
n += 1
return n | python | def count(self, func):
"""
Counts the number of elements in the sequence which satisfy the predicate func.
>>> seq([-1, -2, 1, 2]).count(lambda x: x > 0)
2
:param func: predicate to count elements on
:return: count of elements that satisfy predicate
"""
n = 0
for element in self:
if func(element):
n += 1
return n | [
"def",
"count",
"(",
"self",
",",
"func",
")",
":",
"n",
"=",
"0",
"for",
"element",
"in",
"self",
":",
"if",
"func",
"(",
"element",
")",
":",
"n",
"+=",
"1",
"return",
"n"
] | Counts the number of elements in the sequence which satisfy the predicate func.
>>> seq([-1, -2, 1, 2]).count(lambda x: x > 0)
2
:param func: predicate to count elements on
:return: count of elements that satisfy predicate | [
"Counts",
"the",
"number",
"of",
"elements",
"in",
"the",
"sequence",
"which",
"satisfy",
"the",
"predicate",
"func",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L580-L594 | train | 207,055 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.reduce | def reduce(self, func, *initial):
"""
Reduce sequence of elements using func. API mirrors functools.reduce
>>> seq([1, 2, 3]).reduce(lambda x, y: x + y)
6
:param func: two parameter, associative reduce function
:param initial: single optional argument acting as initial value
:return: reduced value using func
"""
if len(initial) == 0:
return _wrap(reduce(func, self))
elif len(initial) == 1:
return _wrap(reduce(func, self, initial[0]))
else:
raise ValueError('reduce takes exactly one optional parameter for initial value') | python | def reduce(self, func, *initial):
"""
Reduce sequence of elements using func. API mirrors functools.reduce
>>> seq([1, 2, 3]).reduce(lambda x, y: x + y)
6
:param func: two parameter, associative reduce function
:param initial: single optional argument acting as initial value
:return: reduced value using func
"""
if len(initial) == 0:
return _wrap(reduce(func, self))
elif len(initial) == 1:
return _wrap(reduce(func, self, initial[0]))
else:
raise ValueError('reduce takes exactly one optional parameter for initial value') | [
"def",
"reduce",
"(",
"self",
",",
"func",
",",
"*",
"initial",
")",
":",
"if",
"len",
"(",
"initial",
")",
"==",
"0",
":",
"return",
"_wrap",
"(",
"reduce",
"(",
"func",
",",
"self",
")",
")",
"elif",
"len",
"(",
"initial",
")",
"==",
"1",
":"... | Reduce sequence of elements using func. API mirrors functools.reduce
>>> seq([1, 2, 3]).reduce(lambda x, y: x + y)
6
:param func: two parameter, associative reduce function
:param initial: single optional argument acting as initial value
:return: reduced value using func | [
"Reduce",
"sequence",
"of",
"elements",
"using",
"func",
".",
"API",
"mirrors",
"functools",
".",
"reduce"
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L923-L939 | train | 207,056 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.product | def product(self, projection=None):
"""
Takes product of elements in sequence.
>>> seq([1, 2, 3, 4]).product()
24
>>> seq([]).product()
1
>>> seq([(1, 2), (1, 3), (1, 4)]).product(lambda x: x[0])
1
:param projection: function to project on the sequence before taking the product
:return: product of elements in sequence
"""
if self.empty():
if projection:
return projection(1)
else:
return 1
if self.size() == 1:
if projection:
return projection(self.first())
else:
return self.first()
if projection:
return self.map(projection).reduce(mul)
else:
return self.reduce(mul) | python | def product(self, projection=None):
"""
Takes product of elements in sequence.
>>> seq([1, 2, 3, 4]).product()
24
>>> seq([]).product()
1
>>> seq([(1, 2), (1, 3), (1, 4)]).product(lambda x: x[0])
1
:param projection: function to project on the sequence before taking the product
:return: product of elements in sequence
"""
if self.empty():
if projection:
return projection(1)
else:
return 1
if self.size() == 1:
if projection:
return projection(self.first())
else:
return self.first()
if projection:
return self.map(projection).reduce(mul)
else:
return self.reduce(mul) | [
"def",
"product",
"(",
"self",
",",
"projection",
"=",
"None",
")",
":",
"if",
"self",
".",
"empty",
"(",
")",
":",
"if",
"projection",
":",
"return",
"projection",
"(",
"1",
")",
"else",
":",
"return",
"1",
"if",
"self",
".",
"size",
"(",
")",
"... | Takes product of elements in sequence.
>>> seq([1, 2, 3, 4]).product()
24
>>> seq([]).product()
1
>>> seq([(1, 2), (1, 3), (1, 4)]).product(lambda x: x[0])
1
:param projection: function to project on the sequence before taking the product
:return: product of elements in sequence | [
"Takes",
"product",
"of",
"elements",
"in",
"sequence",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L969-L999 | train | 207,057 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.sum | def sum(self, projection=None):
"""
Takes sum of elements in sequence.
>>> seq([1, 2, 3, 4]).sum()
10
>>> seq([(1, 2), (1, 3), (1, 4)]).sum(lambda x: x[0])
3
:param projection: function to project on the sequence before taking the sum
:return: sum of elements in sequence
"""
if projection:
return sum(self.map(projection))
else:
return sum(self) | python | def sum(self, projection=None):
"""
Takes sum of elements in sequence.
>>> seq([1, 2, 3, 4]).sum()
10
>>> seq([(1, 2), (1, 3), (1, 4)]).sum(lambda x: x[0])
3
:param projection: function to project on the sequence before taking the sum
:return: sum of elements in sequence
"""
if projection:
return sum(self.map(projection))
else:
return sum(self) | [
"def",
"sum",
"(",
"self",
",",
"projection",
"=",
"None",
")",
":",
"if",
"projection",
":",
"return",
"sum",
"(",
"self",
".",
"map",
"(",
"projection",
")",
")",
"else",
":",
"return",
"sum",
"(",
"self",
")"
] | Takes sum of elements in sequence.
>>> seq([1, 2, 3, 4]).sum()
10
>>> seq([(1, 2), (1, 3), (1, 4)]).sum(lambda x: x[0])
3
:param projection: function to project on the sequence before taking the sum
:return: sum of elements in sequence | [
"Takes",
"sum",
"of",
"elements",
"in",
"sequence",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1001-L1017 | train | 207,058 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.average | def average(self, projection=None):
"""
Takes the average of elements in the sequence
>>> seq([1, 2]).average()
1.5
>>> seq([('a', 1), ('b', 2)]).average(lambda x: x[1])
:param projection: function to project on the sequence before taking the average
:return: average of elements in the sequence
"""
length = self.size()
if projection:
return sum(self.map(projection)) / length
else:
return sum(self) / length | python | def average(self, projection=None):
"""
Takes the average of elements in the sequence
>>> seq([1, 2]).average()
1.5
>>> seq([('a', 1), ('b', 2)]).average(lambda x: x[1])
:param projection: function to project on the sequence before taking the average
:return: average of elements in the sequence
"""
length = self.size()
if projection:
return sum(self.map(projection)) / length
else:
return sum(self) / length | [
"def",
"average",
"(",
"self",
",",
"projection",
"=",
"None",
")",
":",
"length",
"=",
"self",
".",
"size",
"(",
")",
"if",
"projection",
":",
"return",
"sum",
"(",
"self",
".",
"map",
"(",
"projection",
")",
")",
"/",
"length",
"else",
":",
"retu... | Takes the average of elements in the sequence
>>> seq([1, 2]).average()
1.5
>>> seq([('a', 1), ('b', 2)]).average(lambda x: x[1])
:param projection: function to project on the sequence before taking the average
:return: average of elements in the sequence | [
"Takes",
"the",
"average",
"of",
"elements",
"in",
"the",
"sequence"
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1019-L1035 | train | 207,059 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.sliding | def sliding(self, size, step=1):
"""
Groups elements in fixed size blocks by passing a sliding window over them.
The last window has at least one element but may have less than size elements
:param size: size of sliding window
:param step: step size between windows
:return: sequence of sliding windows
"""
return self._transform(transformations.sliding_t(_wrap, size, step)) | python | def sliding(self, size, step=1):
"""
Groups elements in fixed size blocks by passing a sliding window over them.
The last window has at least one element but may have less than size elements
:param size: size of sliding window
:param step: step size between windows
:return: sequence of sliding windows
"""
return self._transform(transformations.sliding_t(_wrap, size, step)) | [
"def",
"sliding",
"(",
"self",
",",
"size",
",",
"step",
"=",
"1",
")",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"sliding_t",
"(",
"_wrap",
",",
"size",
",",
"step",
")",
")"
] | Groups elements in fixed size blocks by passing a sliding window over them.
The last window has at least one element but may have less than size elements
:param size: size of sliding window
:param step: step size between windows
:return: sequence of sliding windows | [
"Groups",
"elements",
"in",
"fixed",
"size",
"blocks",
"by",
"passing",
"a",
"sliding",
"window",
"over",
"them",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1263-L1273 | train | 207,060 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.sorted | def sorted(self, key=None, reverse=False):
"""
Uses python sort and its passed arguments to sort the input.
>>> seq([2, 1, 4, 3]).sorted()
[1, 2, 3, 4]
:param key: sort using key function
:param reverse: return list reversed or not
:return: sorted sequence
"""
return self._transform(transformations.sorted_t(key=key, reverse=reverse)) | python | def sorted(self, key=None, reverse=False):
"""
Uses python sort and its passed arguments to sort the input.
>>> seq([2, 1, 4, 3]).sorted()
[1, 2, 3, 4]
:param key: sort using key function
:param reverse: return list reversed or not
:return: sorted sequence
"""
return self._transform(transformations.sorted_t(key=key, reverse=reverse)) | [
"def",
"sorted",
"(",
"self",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"sorted_t",
"(",
"key",
"=",
"key",
",",
"reverse",
"=",
"reverse",
")",
")"
] | Uses python sort and its passed arguments to sort the input.
>>> seq([2, 1, 4, 3]).sorted()
[1, 2, 3, 4]
:param key: sort using key function
:param reverse: return list reversed or not
:return: sorted sequence | [
"Uses",
"python",
"sort",
"and",
"its",
"passed",
"arguments",
"to",
"sort",
"the",
"input",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1275-L1286 | train | 207,061 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.slice | def slice(self, start, until):
"""
Takes a slice of the sequence starting at start and until but not including until.
>>> seq([1, 2, 3, 4]).slice(1, 2)
[2]
>>> seq([1, 2, 3, 4]).slice(1, 3)
[2, 3]
:param start: starting index
:param until: ending index
:return: slice including start until but not including until
"""
return self._transform(transformations.slice_t(start, until)) | python | def slice(self, start, until):
"""
Takes a slice of the sequence starting at start and until but not including until.
>>> seq([1, 2, 3, 4]).slice(1, 2)
[2]
>>> seq([1, 2, 3, 4]).slice(1, 3)
[2, 3]
:param start: starting index
:param until: ending index
:return: slice including start until but not including until
"""
return self._transform(transformations.slice_t(start, until)) | [
"def",
"slice",
"(",
"self",
",",
"start",
",",
"until",
")",
":",
"return",
"self",
".",
"_transform",
"(",
"transformations",
".",
"slice_t",
"(",
"start",
",",
"until",
")",
")"
] | Takes a slice of the sequence starting at start and until but not including until.
>>> seq([1, 2, 3, 4]).slice(1, 2)
[2]
>>> seq([1, 2, 3, 4]).slice(1, 3)
[2, 3]
:param start: starting index
:param until: ending index
:return: slice including start until but not including until | [
"Takes",
"a",
"slice",
"of",
"the",
"sequence",
"starting",
"at",
"start",
"and",
"until",
"but",
"not",
"including",
"until",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1332-L1345 | train | 207,062 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.to_list | def to_list(self, n=None):
"""
Converts sequence to list of elements.
>>> type(seq([]).to_list())
list
>>> type(seq([]))
functional.pipeline.Sequence
>>> seq([1, 2, 3]).to_list()
[1, 2, 3]
:param n: Take n elements of sequence if not None
:return: list of elements in sequence
"""
if n is None:
self.cache()
return self._base_sequence
else:
return self.cache().take(n).list() | python | def to_list(self, n=None):
"""
Converts sequence to list of elements.
>>> type(seq([]).to_list())
list
>>> type(seq([]))
functional.pipeline.Sequence
>>> seq([1, 2, 3]).to_list()
[1, 2, 3]
:param n: Take n elements of sequence if not None
:return: list of elements in sequence
"""
if n is None:
self.cache()
return self._base_sequence
else:
return self.cache().take(n).list() | [
"def",
"to_list",
"(",
"self",
",",
"n",
"=",
"None",
")",
":",
"if",
"n",
"is",
"None",
":",
"self",
".",
"cache",
"(",
")",
"return",
"self",
".",
"_base_sequence",
"else",
":",
"return",
"self",
".",
"cache",
"(",
")",
".",
"take",
"(",
"n",
... | Converts sequence to list of elements.
>>> type(seq([]).to_list())
list
>>> type(seq([]))
functional.pipeline.Sequence
>>> seq([1, 2, 3]).to_list()
[1, 2, 3]
:param n: Take n elements of sequence if not None
:return: list of elements in sequence | [
"Converts",
"sequence",
"to",
"list",
"of",
"elements",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1347-L1367 | train | 207,063 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.to_jsonl | def to_jsonl(self, path, mode='wb', compression=None):
"""
Saves the sequence to a jsonl file. Each element is mapped using json.dumps then written
with a newline separating each element.
:param path: path to write file
:param mode: mode to write in, defaults to 'w' to overwrite contents
:param compression: compression format
"""
with universal_write_open(path, mode=mode, compression=compression) as output:
output.write((self.map(json.dumps).make_string('\n') + '\n').encode('utf-8')) | python | def to_jsonl(self, path, mode='wb', compression=None):
"""
Saves the sequence to a jsonl file. Each element is mapped using json.dumps then written
with a newline separating each element.
:param path: path to write file
:param mode: mode to write in, defaults to 'w' to overwrite contents
:param compression: compression format
"""
with universal_write_open(path, mode=mode, compression=compression) as output:
output.write((self.map(json.dumps).make_string('\n') + '\n').encode('utf-8')) | [
"def",
"to_jsonl",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'wb'",
",",
"compression",
"=",
"None",
")",
":",
"with",
"universal_write_open",
"(",
"path",
",",
"mode",
"=",
"mode",
",",
"compression",
"=",
"compression",
")",
"as",
"output",
":",
"... | Saves the sequence to a jsonl file. Each element is mapped using json.dumps then written
with a newline separating each element.
:param path: path to write file
:param mode: mode to write in, defaults to 'w' to overwrite contents
:param compression: compression format | [
"Saves",
"the",
"sequence",
"to",
"a",
"jsonl",
"file",
".",
"Each",
"element",
"is",
"mapped",
"using",
"json",
".",
"dumps",
"then",
"written",
"with",
"a",
"newline",
"separating",
"each",
"element",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1497-L1507 | train | 207,064 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.to_csv | def to_csv(self, path, mode=WRITE_MODE, dialect='excel', compression=None,
newline='', **fmtparams):
"""
Saves the sequence to a csv file. Each element should be an iterable which will be expanded
to the elements of each row.
:param path: path to write file
:param mode: file open mode
:param dialect: passed to csv.writer
:param fmtparams: passed to csv.writer
"""
if 'b' in mode:
newline = None
with universal_write_open(path, mode=mode, compression=compression,
newline=newline) as output:
csv_writer = csv.writer(output, dialect=dialect, **fmtparams)
for row in self:
csv_writer.writerow([six.u(str(element)) for element in row]) | python | def to_csv(self, path, mode=WRITE_MODE, dialect='excel', compression=None,
newline='', **fmtparams):
"""
Saves the sequence to a csv file. Each element should be an iterable which will be expanded
to the elements of each row.
:param path: path to write file
:param mode: file open mode
:param dialect: passed to csv.writer
:param fmtparams: passed to csv.writer
"""
if 'b' in mode:
newline = None
with universal_write_open(path, mode=mode, compression=compression,
newline=newline) as output:
csv_writer = csv.writer(output, dialect=dialect, **fmtparams)
for row in self:
csv_writer.writerow([six.u(str(element)) for element in row]) | [
"def",
"to_csv",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"WRITE_MODE",
",",
"dialect",
"=",
"'excel'",
",",
"compression",
"=",
"None",
",",
"newline",
"=",
"''",
",",
"*",
"*",
"fmtparams",
")",
":",
"if",
"'b'",
"in",
"mode",
":",
"newline",
... | Saves the sequence to a csv file. Each element should be an iterable which will be expanded
to the elements of each row.
:param path: path to write file
:param mode: file open mode
:param dialect: passed to csv.writer
:param fmtparams: passed to csv.writer | [
"Saves",
"the",
"sequence",
"to",
"a",
"csv",
"file",
".",
"Each",
"element",
"should",
"be",
"an",
"iterable",
"which",
"will",
"be",
"expanded",
"to",
"the",
"elements",
"of",
"each",
"row",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1525-L1544 | train | 207,065 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence._to_sqlite3_by_table | def _to_sqlite3_by_table(self, conn, table_name):
"""
Saves the sequence to the specified table of sqlite3 database.
Each element can be a dictionary, namedtuple, tuple or list.
Target table must be created in advance.
:param conn: path or sqlite connection, cursor
:param table_name: table name string
"""
def _insert_item(item):
if isinstance(item, dict):
cols = ', '.join(item.keys())
placeholders = ', '.join('?' * len(item))
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, cols, placeholders)
conn.execute(sql, tuple(item.values()))
elif is_namedtuple(item):
cols = ', '.join(item._fields)
placeholders = ', '.join('?' * len(item))
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, cols, placeholders)
conn.execute(sql, item)
elif isinstance(item, (list, tuple)):
placeholders = ', '.join('?' * len(item))
sql = 'INSERT INTO {} VALUES ({})'.format(table_name, placeholders)
conn.execute(sql, item)
else:
raise TypeError('item must be one of dict, namedtuple, tuple or list got {}'
.format(type(item)))
self.for_each(_insert_item) | python | def _to_sqlite3_by_table(self, conn, table_name):
"""
Saves the sequence to the specified table of sqlite3 database.
Each element can be a dictionary, namedtuple, tuple or list.
Target table must be created in advance.
:param conn: path or sqlite connection, cursor
:param table_name: table name string
"""
def _insert_item(item):
if isinstance(item, dict):
cols = ', '.join(item.keys())
placeholders = ', '.join('?' * len(item))
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, cols, placeholders)
conn.execute(sql, tuple(item.values()))
elif is_namedtuple(item):
cols = ', '.join(item._fields)
placeholders = ', '.join('?' * len(item))
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, cols, placeholders)
conn.execute(sql, item)
elif isinstance(item, (list, tuple)):
placeholders = ', '.join('?' * len(item))
sql = 'INSERT INTO {} VALUES ({})'.format(table_name, placeholders)
conn.execute(sql, item)
else:
raise TypeError('item must be one of dict, namedtuple, tuple or list got {}'
.format(type(item)))
self.for_each(_insert_item) | [
"def",
"_to_sqlite3_by_table",
"(",
"self",
",",
"conn",
",",
"table_name",
")",
":",
"def",
"_insert_item",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"cols",
"=",
"', '",
".",
"join",
"(",
"item",
".",
"keys",
"(... | Saves the sequence to the specified table of sqlite3 database.
Each element can be a dictionary, namedtuple, tuple or list.
Target table must be created in advance.
:param conn: path or sqlite connection, cursor
:param table_name: table name string | [
"Saves",
"the",
"sequence",
"to",
"the",
"specified",
"table",
"of",
"sqlite3",
"database",
".",
"Each",
"element",
"can",
"be",
"a",
"dictionary",
"namedtuple",
"tuple",
"or",
"list",
".",
"Target",
"table",
"must",
"be",
"created",
"in",
"advance",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1557-L1585 | train | 207,066 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.to_sqlite3 | def to_sqlite3(self, conn, target, *args, **kwargs):
"""
Saves the sequence to sqlite3 database.
Target table must be created in advance.
The table schema is inferred from the elements in the sequence
if only target table name is supplied.
>>> seq([(1, 'Tom'), (2, 'Jack')])\
.to_sqlite3('users.db', 'INSERT INTO user (id, name) VALUES (?, ?)')
>>> seq([{'id': 1, 'name': 'Tom'}, {'id': 2, 'name': 'Jack'}]).to_sqlite3(conn, 'user')
:param conn: path or sqlite connection, cursor
:param target: SQL query string or table name
:param args: passed to sqlite3.connect
:param kwargs: passed to sqlite3.connect
"""
# pylint: disable=no-member
insert_regex = re.compile(r'(insert|update)\s+into', flags=re.IGNORECASE)
if insert_regex.match(target):
insert_f = self._to_sqlite3_by_query
else:
insert_f = self._to_sqlite3_by_table
if isinstance(conn, (sqlite3.Connection, sqlite3.Cursor)):
insert_f(conn, target)
conn.commit()
elif isinstance(conn, str):
with sqlite3.connect(conn, *args, **kwargs) as input_conn:
insert_f(input_conn, target)
input_conn.commit()
else:
raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor') | python | def to_sqlite3(self, conn, target, *args, **kwargs):
"""
Saves the sequence to sqlite3 database.
Target table must be created in advance.
The table schema is inferred from the elements in the sequence
if only target table name is supplied.
>>> seq([(1, 'Tom'), (2, 'Jack')])\
.to_sqlite3('users.db', 'INSERT INTO user (id, name) VALUES (?, ?)')
>>> seq([{'id': 1, 'name': 'Tom'}, {'id': 2, 'name': 'Jack'}]).to_sqlite3(conn, 'user')
:param conn: path or sqlite connection, cursor
:param target: SQL query string or table name
:param args: passed to sqlite3.connect
:param kwargs: passed to sqlite3.connect
"""
# pylint: disable=no-member
insert_regex = re.compile(r'(insert|update)\s+into', flags=re.IGNORECASE)
if insert_regex.match(target):
insert_f = self._to_sqlite3_by_query
else:
insert_f = self._to_sqlite3_by_table
if isinstance(conn, (sqlite3.Connection, sqlite3.Cursor)):
insert_f(conn, target)
conn.commit()
elif isinstance(conn, str):
with sqlite3.connect(conn, *args, **kwargs) as input_conn:
insert_f(input_conn, target)
input_conn.commit()
else:
raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor') | [
"def",
"to_sqlite3",
"(",
"self",
",",
"conn",
",",
"target",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=no-member",
"insert_regex",
"=",
"re",
".",
"compile",
"(",
"r'(insert|update)\\s+into'",
",",
"flags",
"=",
"re",
".",
"I... | Saves the sequence to sqlite3 database.
Target table must be created in advance.
The table schema is inferred from the elements in the sequence
if only target table name is supplied.
>>> seq([(1, 'Tom'), (2, 'Jack')])\
.to_sqlite3('users.db', 'INSERT INTO user (id, name) VALUES (?, ?)')
>>> seq([{'id': 1, 'name': 'Tom'}, {'id': 2, 'name': 'Jack'}]).to_sqlite3(conn, 'user')
:param conn: path or sqlite connection, cursor
:param target: SQL query string or table name
:param args: passed to sqlite3.connect
:param kwargs: passed to sqlite3.connect | [
"Saves",
"the",
"sequence",
"to",
"sqlite3",
"database",
".",
"Target",
"table",
"must",
"be",
"created",
"in",
"advance",
".",
"The",
"table",
"schema",
"is",
"inferred",
"from",
"the",
"elements",
"in",
"the",
"sequence",
"if",
"only",
"target",
"table",
... | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1587-L1619 | train | 207,067 |
EntilZha/PyFunctional | functional/pipeline.py | Sequence.to_pandas | def to_pandas(self, columns=None):
# pylint: disable=import-error
"""
Converts sequence to a pandas DataFrame using pandas.DataFrame.from_records
:param columns: columns for pandas to use
:return: DataFrame of sequence
"""
import pandas
return pandas.DataFrame.from_records(self.to_list(), columns=columns) | python | def to_pandas(self, columns=None):
# pylint: disable=import-error
"""
Converts sequence to a pandas DataFrame using pandas.DataFrame.from_records
:param columns: columns for pandas to use
:return: DataFrame of sequence
"""
import pandas
return pandas.DataFrame.from_records(self.to_list(), columns=columns) | [
"def",
"to_pandas",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"# pylint: disable=import-error",
"import",
"pandas",
"return",
"pandas",
".",
"DataFrame",
".",
"from_records",
"(",
"self",
".",
"to_list",
"(",
")",
",",
"columns",
"=",
"columns",
")... | Converts sequence to a pandas DataFrame using pandas.DataFrame.from_records
:param columns: columns for pandas to use
:return: DataFrame of sequence | [
"Converts",
"sequence",
"to",
"a",
"pandas",
"DataFrame",
"using",
"pandas",
".",
"DataFrame",
".",
"from_records"
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1621-L1630 | train | 207,068 |
EntilZha/PyFunctional | functional/streams.py | Stream.open | def open(self, path, delimiter=None, mode='r', buffering=-1, encoding=None, errors=None,
newline=None):
"""
Reads and parses input files as defined.
If delimiter is not None, then the file is read in bulk then split on it. If it is None
(the default), then the file is parsed as sequence of lines. The rest of the options are
passed directly to builtins.open with the exception that write/append file modes is not
allowed.
>>> seq.open('examples/gear_list.txt').take(1)
[u'tent\\n']
:param path: path to file
:param delimiter: delimiter to split joined text on. if None, defaults to per line split
:param mode: file open mode
:param buffering: passed to builtins.open
:param encoding: passed to builtins.open
:param errors: passed to builtins.open
:param newline: passed to builtins.open
:return: output of file depending on options wrapped in a Sequence via seq
"""
if not re.match('^[rbt]{1,3}$', mode):
raise ValueError('mode argument must be only have r, b, and t')
file_open = get_read_function(path, self.disable_compression)
file = file_open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,
newline=newline)
if delimiter is None:
return self(file)
else:
return self(''.join(list(file)).split(delimiter)) | python | def open(self, path, delimiter=None, mode='r', buffering=-1, encoding=None, errors=None,
newline=None):
"""
Reads and parses input files as defined.
If delimiter is not None, then the file is read in bulk then split on it. If it is None
(the default), then the file is parsed as sequence of lines. The rest of the options are
passed directly to builtins.open with the exception that write/append file modes is not
allowed.
>>> seq.open('examples/gear_list.txt').take(1)
[u'tent\\n']
:param path: path to file
:param delimiter: delimiter to split joined text on. if None, defaults to per line split
:param mode: file open mode
:param buffering: passed to builtins.open
:param encoding: passed to builtins.open
:param errors: passed to builtins.open
:param newline: passed to builtins.open
:return: output of file depending on options wrapped in a Sequence via seq
"""
if not re.match('^[rbt]{1,3}$', mode):
raise ValueError('mode argument must be only have r, b, and t')
file_open = get_read_function(path, self.disable_compression)
file = file_open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,
newline=newline)
if delimiter is None:
return self(file)
else:
return self(''.join(list(file)).split(delimiter)) | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"delimiter",
"=",
"None",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"if",
"not",
"re",
... | Reads and parses input files as defined.
If delimiter is not None, then the file is read in bulk then split on it. If it is None
(the default), then the file is parsed as sequence of lines. The rest of the options are
passed directly to builtins.open with the exception that write/append file modes is not
allowed.
>>> seq.open('examples/gear_list.txt').take(1)
[u'tent\\n']
:param path: path to file
:param delimiter: delimiter to split joined text on. if None, defaults to per line split
:param mode: file open mode
:param buffering: passed to builtins.open
:param encoding: passed to builtins.open
:param errors: passed to builtins.open
:param newline: passed to builtins.open
:return: output of file depending on options wrapped in a Sequence via seq | [
"Reads",
"and",
"parses",
"input",
"files",
"as",
"defined",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/streams.py#L69-L100 | train | 207,069 |
EntilZha/PyFunctional | functional/streams.py | Stream.csv | def csv(self, csv_file, dialect='excel', **fmt_params):
"""
Reads and parses the input of a csv stream or file.
csv_file can be a filepath or an object that implements the iterator interface
(defines next() or __next__() depending on python version).
>>> seq.csv('examples/camping_purchases.csv').take(2)
[['1', 'tent', '300'], ['2', 'food', '100']]
:param csv_file: path to file or iterator object
:param dialect: dialect of csv, passed to csv.reader
:param fmt_params: options passed to csv.reader
:return: Sequence wrapping csv file
"""
if isinstance(csv_file, str):
file_open = get_read_function(csv_file, self.disable_compression)
input_file = file_open(csv_file)
elif hasattr(csv_file, 'next') or hasattr(csv_file, '__next__'):
input_file = csv_file
else:
raise ValueError('csv_file must be a file path or implement the iterator interface')
csv_input = csvapi.reader(input_file, dialect=dialect, **fmt_params)
return self(csv_input).cache(delete_lineage=True) | python | def csv(self, csv_file, dialect='excel', **fmt_params):
"""
Reads and parses the input of a csv stream or file.
csv_file can be a filepath or an object that implements the iterator interface
(defines next() or __next__() depending on python version).
>>> seq.csv('examples/camping_purchases.csv').take(2)
[['1', 'tent', '300'], ['2', 'food', '100']]
:param csv_file: path to file or iterator object
:param dialect: dialect of csv, passed to csv.reader
:param fmt_params: options passed to csv.reader
:return: Sequence wrapping csv file
"""
if isinstance(csv_file, str):
file_open = get_read_function(csv_file, self.disable_compression)
input_file = file_open(csv_file)
elif hasattr(csv_file, 'next') or hasattr(csv_file, '__next__'):
input_file = csv_file
else:
raise ValueError('csv_file must be a file path or implement the iterator interface')
csv_input = csvapi.reader(input_file, dialect=dialect, **fmt_params)
return self(csv_input).cache(delete_lineage=True) | [
"def",
"csv",
"(",
"self",
",",
"csv_file",
",",
"dialect",
"=",
"'excel'",
",",
"*",
"*",
"fmt_params",
")",
":",
"if",
"isinstance",
"(",
"csv_file",
",",
"str",
")",
":",
"file_open",
"=",
"get_read_function",
"(",
"csv_file",
",",
"self",
".",
"dis... | Reads and parses the input of a csv stream or file.
csv_file can be a filepath or an object that implements the iterator interface
(defines next() or __next__() depending on python version).
>>> seq.csv('examples/camping_purchases.csv').take(2)
[['1', 'tent', '300'], ['2', 'food', '100']]
:param csv_file: path to file or iterator object
:param dialect: dialect of csv, passed to csv.reader
:param fmt_params: options passed to csv.reader
:return: Sequence wrapping csv file | [
"Reads",
"and",
"parses",
"the",
"input",
"of",
"a",
"csv",
"stream",
"or",
"file",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/streams.py#L114-L138 | train | 207,070 |
EntilZha/PyFunctional | functional/streams.py | Stream.jsonl | def jsonl(self, jsonl_file):
"""
Reads and parses the input of a jsonl file stream or file.
Jsonl formatted files must have a single valid json value on each line which is parsed by
the python json module.
>>> seq.jsonl('examples/chat_logs.jsonl').first()
{u'date': u'10/09', u'message': u'hello anyone there?', u'user': u'bob'}
:param jsonl_file: path or file containing jsonl content
:return: Sequence wrapping jsonl file
"""
if isinstance(jsonl_file, str):
file_open = get_read_function(jsonl_file, self.disable_compression)
input_file = file_open(jsonl_file)
else:
input_file = jsonl_file
return self(input_file).map(jsonapi.loads).cache(delete_lineage=True) | python | def jsonl(self, jsonl_file):
"""
Reads and parses the input of a jsonl file stream or file.
Jsonl formatted files must have a single valid json value on each line which is parsed by
the python json module.
>>> seq.jsonl('examples/chat_logs.jsonl').first()
{u'date': u'10/09', u'message': u'hello anyone there?', u'user': u'bob'}
:param jsonl_file: path or file containing jsonl content
:return: Sequence wrapping jsonl file
"""
if isinstance(jsonl_file, str):
file_open = get_read_function(jsonl_file, self.disable_compression)
input_file = file_open(jsonl_file)
else:
input_file = jsonl_file
return self(input_file).map(jsonapi.loads).cache(delete_lineage=True) | [
"def",
"jsonl",
"(",
"self",
",",
"jsonl_file",
")",
":",
"if",
"isinstance",
"(",
"jsonl_file",
",",
"str",
")",
":",
"file_open",
"=",
"get_read_function",
"(",
"jsonl_file",
",",
"self",
".",
"disable_compression",
")",
"input_file",
"=",
"file_open",
"("... | Reads and parses the input of a jsonl file stream or file.
Jsonl formatted files must have a single valid json value on each line which is parsed by
the python json module.
>>> seq.jsonl('examples/chat_logs.jsonl').first()
{u'date': u'10/09', u'message': u'hello anyone there?', u'user': u'bob'}
:param jsonl_file: path or file containing jsonl content
:return: Sequence wrapping jsonl file | [
"Reads",
"and",
"parses",
"the",
"input",
"of",
"a",
"jsonl",
"file",
"stream",
"or",
"file",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/streams.py#L154-L172 | train | 207,071 |
EntilZha/PyFunctional | functional/streams.py | Stream.json | def json(self, json_file):
"""
Reads and parses the input of a json file handler or file.
Json files are parsed differently depending on if the root is a dictionary or an array.
1) If the json's root is a dictionary, these are parsed into a sequence of (Key, Value)
pairs
2) If the json's root is an array, these are parsed into a sequence
of entries
>>> seq.json('examples/users.json').first()
[u'sarah', {u'date_created': u'08/08', u'news_email': True, u'email': u'sarah@gmail.com'}]
:param json_file: path or file containing json content
:return: Sequence wrapping jsonl file
"""
if isinstance(json_file, str):
file_open = get_read_function(json_file, self.disable_compression)
input_file = file_open(json_file)
json_input = jsonapi.load(input_file)
elif hasattr(json_file, 'read'):
json_input = jsonapi.load(json_file)
else:
raise ValueError('json_file must be a file path or implement the iterator interface')
if isinstance(json_input, list):
return self(json_input)
else:
return self(six.viewitems(json_input)) | python | def json(self, json_file):
"""
Reads and parses the input of a json file handler or file.
Json files are parsed differently depending on if the root is a dictionary or an array.
1) If the json's root is a dictionary, these are parsed into a sequence of (Key, Value)
pairs
2) If the json's root is an array, these are parsed into a sequence
of entries
>>> seq.json('examples/users.json').first()
[u'sarah', {u'date_created': u'08/08', u'news_email': True, u'email': u'sarah@gmail.com'}]
:param json_file: path or file containing json content
:return: Sequence wrapping jsonl file
"""
if isinstance(json_file, str):
file_open = get_read_function(json_file, self.disable_compression)
input_file = file_open(json_file)
json_input = jsonapi.load(input_file)
elif hasattr(json_file, 'read'):
json_input = jsonapi.load(json_file)
else:
raise ValueError('json_file must be a file path or implement the iterator interface')
if isinstance(json_input, list):
return self(json_input)
else:
return self(six.viewitems(json_input)) | [
"def",
"json",
"(",
"self",
",",
"json_file",
")",
":",
"if",
"isinstance",
"(",
"json_file",
",",
"str",
")",
":",
"file_open",
"=",
"get_read_function",
"(",
"json_file",
",",
"self",
".",
"disable_compression",
")",
"input_file",
"=",
"file_open",
"(",
... | Reads and parses the input of a json file handler or file.
Json files are parsed differently depending on if the root is a dictionary or an array.
1) If the json's root is a dictionary, these are parsed into a sequence of (Key, Value)
pairs
2) If the json's root is an array, these are parsed into a sequence
of entries
>>> seq.json('examples/users.json').first()
[u'sarah', {u'date_created': u'08/08', u'news_email': True, u'email': u'sarah@gmail.com'}]
:param json_file: path or file containing json content
:return: Sequence wrapping jsonl file | [
"Reads",
"and",
"parses",
"the",
"input",
"of",
"a",
"json",
"file",
"handler",
"or",
"file",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/streams.py#L174-L204 | train | 207,072 |
EntilZha/PyFunctional | functional/streams.py | Stream.sqlite3 | def sqlite3(self, conn, sql, parameters=None, *args, **kwargs):
"""
Reads input by querying from a sqlite database.
>>> seq.sqlite3('examples/users.db', 'select id, name from users where id = 1;').first()
[(1, 'Tom')]
:param conn: path or sqlite connection, cursor
:param sql: SQL query string
:param parameters: Parameters for sql query
:return: Sequence wrapping SQL cursor
"""
if parameters is None:
parameters = ()
if isinstance(conn, (sqlite3api.Connection, sqlite3api.Cursor)):
return self(conn.execute(sql, parameters))
elif isinstance(conn, str):
with sqlite3api.connect(conn, *args, **kwargs) as input_conn:
return self(input_conn.execute(sql, parameters))
else:
raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor') | python | def sqlite3(self, conn, sql, parameters=None, *args, **kwargs):
"""
Reads input by querying from a sqlite database.
>>> seq.sqlite3('examples/users.db', 'select id, name from users where id = 1;').first()
[(1, 'Tom')]
:param conn: path or sqlite connection, cursor
:param sql: SQL query string
:param parameters: Parameters for sql query
:return: Sequence wrapping SQL cursor
"""
if parameters is None:
parameters = ()
if isinstance(conn, (sqlite3api.Connection, sqlite3api.Cursor)):
return self(conn.execute(sql, parameters))
elif isinstance(conn, str):
with sqlite3api.connect(conn, *args, **kwargs) as input_conn:
return self(input_conn.execute(sql, parameters))
else:
raise ValueError('conn must be a must be a file path or sqlite3 Connection/Cursor') | [
"def",
"sqlite3",
"(",
"self",
",",
"conn",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"(",
")",
"if",
"isinstance",
"(",
"conn",
",",
... | Reads input by querying from a sqlite database.
>>> seq.sqlite3('examples/users.db', 'select id, name from users where id = 1;').first()
[(1, 'Tom')]
:param conn: path or sqlite connection, cursor
:param sql: SQL query string
:param parameters: Parameters for sql query
:return: Sequence wrapping SQL cursor | [
"Reads",
"input",
"by",
"querying",
"from",
"a",
"sqlite",
"database",
"."
] | ac04e4a8552b0c464a7f492f7c9862424867b63e | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/streams.py#L207-L229 | train | 207,073 |
aio-libs/janus | janus/__init__.py | _AsyncQueueProxy.full | def full(self):
"""Return True if there are maxsize items in the queue.
Note: if the Queue was initialized with maxsize=0 (the default),
then full() is never True.
"""
if self._parent._maxsize <= 0:
return False
else:
return self.qsize() >= self._parent._maxsize | python | def full(self):
"""Return True if there are maxsize items in the queue.
Note: if the Queue was initialized with maxsize=0 (the default),
then full() is never True.
"""
if self._parent._maxsize <= 0:
return False
else:
return self.qsize() >= self._parent._maxsize | [
"def",
"full",
"(",
"self",
")",
":",
"if",
"self",
".",
"_parent",
".",
"_maxsize",
"<=",
"0",
":",
"return",
"False",
"else",
":",
"return",
"self",
".",
"qsize",
"(",
")",
">=",
"self",
".",
"_parent",
".",
"_maxsize"
] | Return True if there are maxsize items in the queue.
Note: if the Queue was initialized with maxsize=0 (the default),
then full() is never True. | [
"Return",
"True",
"if",
"there",
"are",
"maxsize",
"items",
"in",
"the",
"queue",
"."
] | 8dc80530db1144fbd1dba75d4a1c1a54bb520c21 | https://github.com/aio-libs/janus/blob/8dc80530db1144fbd1dba75d4a1c1a54bb520c21/janus/__init__.py#L373-L382 | train | 207,074 |
aio-libs/janus | janus/__init__.py | _AsyncQueueProxy.join | async def join(self):
"""Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer calls task_done() to
indicate that the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
while True:
with self._parent._sync_mutex:
if self._parent._unfinished_tasks == 0:
break
await self._parent._finished.wait() | python | async def join(self):
"""Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer calls task_done() to
indicate that the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
while True:
with self._parent._sync_mutex:
if self._parent._unfinished_tasks == 0:
break
await self._parent._finished.wait() | [
"async",
"def",
"join",
"(",
"self",
")",
":",
"while",
"True",
":",
"with",
"self",
".",
"_parent",
".",
"_sync_mutex",
":",
"if",
"self",
".",
"_parent",
".",
"_unfinished_tasks",
"==",
"0",
":",
"break",
"await",
"self",
".",
"_parent",
".",
"_finis... | Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer calls task_done() to
indicate that the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks. | [
"Block",
"until",
"all",
"items",
"in",
"the",
"queue",
"have",
"been",
"gotten",
"and",
"processed",
"."
] | 8dc80530db1144fbd1dba75d4a1c1a54bb520c21 | https://github.com/aio-libs/janus/blob/8dc80530db1144fbd1dba75d4a1c1a54bb520c21/janus/__init__.py#L501-L513 | train | 207,075 |
mocobeta/janome | janome/dic.py | UserDictionary.save | def save(self, to_dir, compressionlevel=9):
u"""
Save compressed compiled dictionary data.
:param to_dir: directory to save dictionary data
:compressionlevel: (Optional) gzip compression level. default is 9
"""
if os.path.exists(to_dir) and not os.path.isdir(to_dir):
raise Exception('Not a directory : %s' % to_dir)
elif not os.path.exists(to_dir):
os.makedirs(to_dir, mode=int('0755', 8))
_save(os.path.join(to_dir, FILE_USER_FST_DATA), self.compiledFST[0], compressionlevel)
_save(os.path.join(to_dir, FILE_USER_ENTRIES_DATA), pickle.dumps(self.entries), compressionlevel) | python | def save(self, to_dir, compressionlevel=9):
u"""
Save compressed compiled dictionary data.
:param to_dir: directory to save dictionary data
:compressionlevel: (Optional) gzip compression level. default is 9
"""
if os.path.exists(to_dir) and not os.path.isdir(to_dir):
raise Exception('Not a directory : %s' % to_dir)
elif not os.path.exists(to_dir):
os.makedirs(to_dir, mode=int('0755', 8))
_save(os.path.join(to_dir, FILE_USER_FST_DATA), self.compiledFST[0], compressionlevel)
_save(os.path.join(to_dir, FILE_USER_ENTRIES_DATA), pickle.dumps(self.entries), compressionlevel) | [
"def",
"save",
"(",
"self",
",",
"to_dir",
",",
"compressionlevel",
"=",
"9",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"to_dir",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"to_dir",
")",
":",
"raise",
"Exception",
"(",
... | u"""
Save compressed compiled dictionary data.
:param to_dir: directory to save dictionary data
:compressionlevel: (Optional) gzip compression level. default is 9 | [
"u",
"Save",
"compressed",
"compiled",
"dictionary",
"data",
"."
] | 6faab0fc943d41a66348f2d86e1e67792bb4dbf2 | https://github.com/mocobeta/janome/blob/6faab0fc943d41a66348f2d86e1e67792bb4dbf2/janome/dic.py#L447-L459 | train | 207,076 |
mocobeta/janome | janome/analyzer.py | Analyzer.analyze | def analyze(self, text):
u"""
Analyze the input text with custom CharFilters, Tokenizer and TokenFilters.
:param text: unicode string to be tokenized
:return: token generator. emitted element type depends on the output of the last TokenFilter. (e.g., ExtractAttributeFilter emits strings.)
"""
for cfilter in self.char_filters:
text = cfilter.filter(text)
tokens = self.tokenizer.tokenize(text, stream=True, wakati=False)
for tfilter in self.token_filters:
tokens = tfilter.filter(tokens)
return tokens | python | def analyze(self, text):
u"""
Analyze the input text with custom CharFilters, Tokenizer and TokenFilters.
:param text: unicode string to be tokenized
:return: token generator. emitted element type depends on the output of the last TokenFilter. (e.g., ExtractAttributeFilter emits strings.)
"""
for cfilter in self.char_filters:
text = cfilter.filter(text)
tokens = self.tokenizer.tokenize(text, stream=True, wakati=False)
for tfilter in self.token_filters:
tokens = tfilter.filter(tokens)
return tokens | [
"def",
"analyze",
"(",
"self",
",",
"text",
")",
":",
"for",
"cfilter",
"in",
"self",
".",
"char_filters",
":",
"text",
"=",
"cfilter",
".",
"filter",
"(",
"text",
")",
"tokens",
"=",
"self",
".",
"tokenizer",
".",
"tokenize",
"(",
"text",
",",
"stre... | u"""
Analyze the input text with custom CharFilters, Tokenizer and TokenFilters.
:param text: unicode string to be tokenized
:return: token generator. emitted element type depends on the output of the last TokenFilter. (e.g., ExtractAttributeFilter emits strings.) | [
"u",
"Analyze",
"the",
"input",
"text",
"with",
"custom",
"CharFilters",
"Tokenizer",
"and",
"TokenFilters",
"."
] | 6faab0fc943d41a66348f2d86e1e67792bb4dbf2 | https://github.com/mocobeta/janome/blob/6faab0fc943d41a66348f2d86e1e67792bb4dbf2/janome/analyzer.py#L93-L106 | train | 207,077 |
mocobeta/janome | janome/fst.py | compileFST | def compileFST(fst):
u"""
convert FST to byte array representing arcs
"""
arcs = []
address = {}
pos = 0
for (num, s) in enumerate(fst.dictionary.values()):
for i, (c, v) in enumerate(sorted(s.trans_map.items(), reverse=True)):
bary = bytearray()
flag = 0
output_size, output = 0, bytes()
if i == 0:
flag += FLAG_LAST_ARC
if v['output']:
flag += FLAG_ARC_HAS_OUTPUT
output_size = len(v['output'])
output = v['output']
# encode flag, label, output_size, output, relative target address
bary += pack('b', flag)
if PY3:
bary += pack('B', c)
else:
bary += pack('c', c)
if output_size > 0:
bary += pack('I', output_size)
bary += output
next_addr = address.get(v['state'].id)
assert next_addr is not None
target = (pos + len(bary) + 4) - next_addr
assert target > 0
bary += pack('I', target)
# add the arc represented in bytes
if PY3:
arcs.append(bytes(bary))
else:
arcs.append(b''.join(chr(b) for b in bary))
# address count up
pos += len(bary)
if s.is_final():
bary = bytearray()
# final state
flag = FLAG_FINAL_ARC
output_count = 0
if s.final_output and any(len(e) > 0 for e in s.final_output):
# the arc has final output
flag += FLAG_ARC_HAS_FINAL_OUTPUT
output_count = len(s.final_output)
if not s.trans_map:
flag += FLAG_LAST_ARC
# encode flag, output size, output
bary += pack('b', flag)
if output_count:
bary += pack('I', output_count)
for out in s.final_output:
output_size = len(out)
bary += pack('I', output_size)
if output_size:
bary += out
# add the arc represented in bytes
if PY3:
arcs.append(bytes(bary))
else:
arcs.append(b''.join(chr(b) for b in bary))
# address count up
pos += len(bary)
address[s.id] = pos
logger.debug('compiled arcs size: %d' % len(arcs))
arcs.reverse()
return b''.join(arcs) | python | def compileFST(fst):
u"""
convert FST to byte array representing arcs
"""
arcs = []
address = {}
pos = 0
for (num, s) in enumerate(fst.dictionary.values()):
for i, (c, v) in enumerate(sorted(s.trans_map.items(), reverse=True)):
bary = bytearray()
flag = 0
output_size, output = 0, bytes()
if i == 0:
flag += FLAG_LAST_ARC
if v['output']:
flag += FLAG_ARC_HAS_OUTPUT
output_size = len(v['output'])
output = v['output']
# encode flag, label, output_size, output, relative target address
bary += pack('b', flag)
if PY3:
bary += pack('B', c)
else:
bary += pack('c', c)
if output_size > 0:
bary += pack('I', output_size)
bary += output
next_addr = address.get(v['state'].id)
assert next_addr is not None
target = (pos + len(bary) + 4) - next_addr
assert target > 0
bary += pack('I', target)
# add the arc represented in bytes
if PY3:
arcs.append(bytes(bary))
else:
arcs.append(b''.join(chr(b) for b in bary))
# address count up
pos += len(bary)
if s.is_final():
bary = bytearray()
# final state
flag = FLAG_FINAL_ARC
output_count = 0
if s.final_output and any(len(e) > 0 for e in s.final_output):
# the arc has final output
flag += FLAG_ARC_HAS_FINAL_OUTPUT
output_count = len(s.final_output)
if not s.trans_map:
flag += FLAG_LAST_ARC
# encode flag, output size, output
bary += pack('b', flag)
if output_count:
bary += pack('I', output_count)
for out in s.final_output:
output_size = len(out)
bary += pack('I', output_size)
if output_size:
bary += out
# add the arc represented in bytes
if PY3:
arcs.append(bytes(bary))
else:
arcs.append(b''.join(chr(b) for b in bary))
# address count up
pos += len(bary)
address[s.id] = pos
logger.debug('compiled arcs size: %d' % len(arcs))
arcs.reverse()
return b''.join(arcs) | [
"def",
"compileFST",
"(",
"fst",
")",
":",
"arcs",
"=",
"[",
"]",
"address",
"=",
"{",
"}",
"pos",
"=",
"0",
"for",
"(",
"num",
",",
"s",
")",
"in",
"enumerate",
"(",
"fst",
".",
"dictionary",
".",
"values",
"(",
")",
")",
":",
"for",
"i",
",... | u"""
convert FST to byte array representing arcs | [
"u",
"convert",
"FST",
"to",
"byte",
"array",
"representing",
"arcs"
] | 6faab0fc943d41a66348f2d86e1e67792bb4dbf2 | https://github.com/mocobeta/janome/blob/6faab0fc943d41a66348f2d86e1e67792bb4dbf2/janome/fst.py#L291-L361 | train | 207,078 |
mocobeta/janome | janome/tokenizer.py | Tokenizer.tokenize | def tokenize(self, text, stream=False, wakati=False, baseform_unk=True, dotfile=''):
u"""
Tokenize the input text.
:param text: unicode string to be tokenized
:param stream: (Optional) if given True use stream mode. default is False.
:param wakati: (Optinal) if given True returns surface forms only. default is False.
:param baseform_unk: (Optional) if given True sets base_form attribute for unknown tokens. default is True.
:param dotfile: (Optional) if specified, graphviz dot file is output to the path for later visualizing of the lattice graph. This option is ignored when the input length is larger than MAX_CHUNK_SIZE or running on stream mode.
:return: list of tokens (stream=False, wakati=False) or token generator (stream=True, wakati=False) or list of string (stream=False, wakati=True) or string generator (stream=True, wakati=True)
"""
if self.wakati:
wakati = True
if stream:
return self.__tokenize_stream(text, wakati, baseform_unk, '')
elif dotfile and len(text) < Tokenizer.MAX_CHUNK_SIZE:
return list(self.__tokenize_stream(text, wakati, baseform_unk, dotfile))
else:
return list(self.__tokenize_stream(text, wakati, baseform_unk, '')) | python | def tokenize(self, text, stream=False, wakati=False, baseform_unk=True, dotfile=''):
u"""
Tokenize the input text.
:param text: unicode string to be tokenized
:param stream: (Optional) if given True use stream mode. default is False.
:param wakati: (Optinal) if given True returns surface forms only. default is False.
:param baseform_unk: (Optional) if given True sets base_form attribute for unknown tokens. default is True.
:param dotfile: (Optional) if specified, graphviz dot file is output to the path for later visualizing of the lattice graph. This option is ignored when the input length is larger than MAX_CHUNK_SIZE or running on stream mode.
:return: list of tokens (stream=False, wakati=False) or token generator (stream=True, wakati=False) or list of string (stream=False, wakati=True) or string generator (stream=True, wakati=True)
"""
if self.wakati:
wakati = True
if stream:
return self.__tokenize_stream(text, wakati, baseform_unk, '')
elif dotfile and len(text) < Tokenizer.MAX_CHUNK_SIZE:
return list(self.__tokenize_stream(text, wakati, baseform_unk, dotfile))
else:
return list(self.__tokenize_stream(text, wakati, baseform_unk, '')) | [
"def",
"tokenize",
"(",
"self",
",",
"text",
",",
"stream",
"=",
"False",
",",
"wakati",
"=",
"False",
",",
"baseform_unk",
"=",
"True",
",",
"dotfile",
"=",
"''",
")",
":",
"if",
"self",
".",
"wakati",
":",
"wakati",
"=",
"True",
"if",
"stream",
"... | u"""
Tokenize the input text.
:param text: unicode string to be tokenized
:param stream: (Optional) if given True use stream mode. default is False.
:param wakati: (Optinal) if given True returns surface forms only. default is False.
:param baseform_unk: (Optional) if given True sets base_form attribute for unknown tokens. default is True.
:param dotfile: (Optional) if specified, graphviz dot file is output to the path for later visualizing of the lattice graph. This option is ignored when the input length is larger than MAX_CHUNK_SIZE or running on stream mode.
:return: list of tokens (stream=False, wakati=False) or token generator (stream=True, wakati=False) or list of string (stream=False, wakati=True) or string generator (stream=True, wakati=True) | [
"u",
"Tokenize",
"the",
"input",
"text",
"."
] | 6faab0fc943d41a66348f2d86e1e67792bb4dbf2 | https://github.com/mocobeta/janome/blob/6faab0fc943d41a66348f2d86e1e67792bb4dbf2/janome/tokenizer.py#L178-L197 | train | 207,079 |
un33k/django-ipware | ipware/ip.py | get_ip | def get_ip(request, real_ip_only=False, right_most_proxy=False):
"""
Returns client's best-matched ip-address, or None
@deprecated - Do not edit
"""
best_matched_ip = None
warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning)
for key in defs.IPWARE_META_PRECEDENCE_ORDER:
value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
if value is not None and value != '':
ips = [ip.strip().lower() for ip in value.split(',')]
if right_most_proxy and len(ips) > 1:
ips = reversed(ips)
for ip_str in ips:
if ip_str and is_valid_ip(ip_str):
if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):
return ip_str
if not real_ip_only:
loopback = defs.IPWARE_LOOPBACK_PREFIX
if best_matched_ip is None:
best_matched_ip = ip_str
elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):
best_matched_ip = ip_str
return best_matched_ip | python | def get_ip(request, real_ip_only=False, right_most_proxy=False):
"""
Returns client's best-matched ip-address, or None
@deprecated - Do not edit
"""
best_matched_ip = None
warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning)
for key in defs.IPWARE_META_PRECEDENCE_ORDER:
value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
if value is not None and value != '':
ips = [ip.strip().lower() for ip in value.split(',')]
if right_most_proxy and len(ips) > 1:
ips = reversed(ips)
for ip_str in ips:
if ip_str and is_valid_ip(ip_str):
if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):
return ip_str
if not real_ip_only:
loopback = defs.IPWARE_LOOPBACK_PREFIX
if best_matched_ip is None:
best_matched_ip = ip_str
elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):
best_matched_ip = ip_str
return best_matched_ip | [
"def",
"get_ip",
"(",
"request",
",",
"real_ip_only",
"=",
"False",
",",
"right_most_proxy",
"=",
"False",
")",
":",
"best_matched_ip",
"=",
"None",
"warnings",
".",
"warn",
"(",
"'get_ip is deprecated and will be removed in 3.0.'",
",",
"DeprecationWarning",
")",
"... | Returns client's best-matched ip-address, or None
@deprecated - Do not edit | [
"Returns",
"client",
"s",
"best",
"-",
"matched",
"ip",
"-",
"address",
"or",
"None"
] | dc6b754137d1bb7d056ac206a6e0443aa3ed68dc | https://github.com/un33k/django-ipware/blob/dc6b754137d1bb7d056ac206a6e0443aa3ed68dc/ipware/ip.py#L14-L37 | train | 207,080 |
un33k/django-ipware | ipware/ip.py | get_real_ip | def get_real_ip(request, right_most_proxy=False):
"""
Returns client's best-matched `real` `externally-routable` ip-address, or None
@deprecated - Do not edit
"""
warnings.warn('get_real_ip is deprecated and will be removed in 3.0.', DeprecationWarning)
return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy) | python | def get_real_ip(request, right_most_proxy=False):
"""
Returns client's best-matched `real` `externally-routable` ip-address, or None
@deprecated - Do not edit
"""
warnings.warn('get_real_ip is deprecated and will be removed in 3.0.', DeprecationWarning)
return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy) | [
"def",
"get_real_ip",
"(",
"request",
",",
"right_most_proxy",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'get_real_ip is deprecated and will be removed in 3.0.'",
",",
"DeprecationWarning",
")",
"return",
"get_ip",
"(",
"request",
",",
"real_ip_only",
"="... | Returns client's best-matched `real` `externally-routable` ip-address, or None
@deprecated - Do not edit | [
"Returns",
"client",
"s",
"best",
"-",
"matched",
"real",
"externally",
"-",
"routable",
"ip",
"-",
"address",
"or",
"None"
] | dc6b754137d1bb7d056ac206a6e0443aa3ed68dc | https://github.com/un33k/django-ipware/blob/dc6b754137d1bb7d056ac206a6e0443aa3ed68dc/ipware/ip.py#L40-L46 | train | 207,081 |
un33k/django-ipware | ipware/utils.py | is_valid_ipv6 | def is_valid_ipv6(ip_str):
"""
Check the validity of an IPv6 address
"""
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
return False
return True | python | def is_valid_ipv6(ip_str):
"""
Check the validity of an IPv6 address
"""
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
return False
return True | [
"def",
"is_valid_ipv6",
"(",
"ip_str",
")",
":",
"try",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"ip_str",
")",
"except",
"socket",
".",
"error",
":",
"return",
"False",
"return",
"True"
] | Check the validity of an IPv6 address | [
"Check",
"the",
"validity",
"of",
"an",
"IPv6",
"address"
] | dc6b754137d1bb7d056ac206a6e0443aa3ed68dc | https://github.com/un33k/django-ipware/blob/dc6b754137d1bb7d056ac206a6e0443aa3ed68dc/ipware/utils.py#L23-L31 | train | 207,082 |
un33k/django-ipware | ipware/utils.py | get_request_meta | def get_request_meta(request, key):
"""
Given a key, it returns a cleaned up version of the value from request.META, or None
"""
value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
if value == '':
return None
return value | python | def get_request_meta(request, key):
"""
Given a key, it returns a cleaned up version of the value from request.META, or None
"""
value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
if value == '':
return None
return value | [
"def",
"get_request_meta",
"(",
"request",
",",
"key",
")",
":",
"value",
"=",
"request",
".",
"META",
".",
"get",
"(",
"key",
",",
"request",
".",
"META",
".",
"get",
"(",
"key",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
",",
"''",
")",
")",
... | Given a key, it returns a cleaned up version of the value from request.META, or None | [
"Given",
"a",
"key",
"it",
"returns",
"a",
"cleaned",
"up",
"version",
"of",
"the",
"value",
"from",
"request",
".",
"META",
"or",
"None"
] | dc6b754137d1bb7d056ac206a6e0443aa3ed68dc | https://github.com/un33k/django-ipware/blob/dc6b754137d1bb7d056ac206a6e0443aa3ed68dc/ipware/utils.py#L62-L69 | train | 207,083 |
un33k/django-ipware | ipware/utils.py | get_ips_from_string | def get_ips_from_string(ip_str):
"""
Given a string, it returns a list of one or more valid IP addresses
"""
ip_list = []
for ip in ip_str.split(','):
clean_ip = ip.strip().lower()
if clean_ip:
ip_list.append(clean_ip)
ip_count = len(ip_list)
if ip_count > 0:
if is_valid_ip(ip_list[0]) and is_valid_ip(ip_list[-1]):
return ip_list, ip_count
return [], 0 | python | def get_ips_from_string(ip_str):
"""
Given a string, it returns a list of one or more valid IP addresses
"""
ip_list = []
for ip in ip_str.split(','):
clean_ip = ip.strip().lower()
if clean_ip:
ip_list.append(clean_ip)
ip_count = len(ip_list)
if ip_count > 0:
if is_valid_ip(ip_list[0]) and is_valid_ip(ip_list[-1]):
return ip_list, ip_count
return [], 0 | [
"def",
"get_ips_from_string",
"(",
"ip_str",
")",
":",
"ip_list",
"=",
"[",
"]",
"for",
"ip",
"in",
"ip_str",
".",
"split",
"(",
"','",
")",
":",
"clean_ip",
"=",
"ip",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"clean_ip",
":",
"ip_list... | Given a string, it returns a list of one or more valid IP addresses | [
"Given",
"a",
"string",
"it",
"returns",
"a",
"list",
"of",
"one",
"or",
"more",
"valid",
"IP",
"addresses"
] | dc6b754137d1bb7d056ac206a6e0443aa3ed68dc | https://github.com/un33k/django-ipware/blob/dc6b754137d1bb7d056ac206a6e0443aa3ed68dc/ipware/utils.py#L72-L88 | train | 207,084 |
defunkt/pystache | pystache/commands/render.py | parse_args | def parse_args(sys_argv, usage):
"""
Return an OptionParser for the script.
"""
args = sys_argv[1:]
parser = OptionParser(usage=usage)
options, args = parser.parse_args(args)
template, context = args
return template, context | python | def parse_args(sys_argv, usage):
"""
Return an OptionParser for the script.
"""
args = sys_argv[1:]
parser = OptionParser(usage=usage)
options, args = parser.parse_args(args)
template, context = args
return template, context | [
"def",
"parse_args",
"(",
"sys_argv",
",",
"usage",
")",
":",
"args",
"=",
"sys_argv",
"[",
"1",
":",
"]",
"parser",
"=",
"OptionParser",
"(",
"usage",
"=",
"usage",
")",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"te... | Return an OptionParser for the script. | [
"Return",
"an",
"OptionParser",
"for",
"the",
"script",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/commands/render.py#L52-L64 | train | 207,085 |
defunkt/pystache | pystache/init.py | render | def render(template, context=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
return renderer.render(template, context, **kwargs) | python | def render(template, context=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
return renderer.render(template, context, **kwargs) | [
"def",
"render",
"(",
"template",
",",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer",
"=",
"Renderer",
"(",
")",
"return",
"renderer",
".",
"render",
"(",
"template",
",",
"context",
",",
"*",
"*",
"kwargs",
")"
] | Return the given template string rendered using the given context. | [
"Return",
"the",
"given",
"template",
"string",
"rendered",
"using",
"the",
"given",
"context",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/init.py#L13-L19 | train | 207,086 |
defunkt/pystache | pystache/context.py | _get_value | def _get_value(context, key):
"""
Retrieve a key's value from a context item.
Returns _NOT_FOUND if the key does not exist.
The ContextStack.get() docstring documents this function's intended behavior.
"""
if isinstance(context, dict):
# Then we consider the argument a "hash" for the purposes of the spec.
#
# We do a membership test to avoid using exceptions for flow control
# (e.g. catching KeyError).
if key in context:
return context[key]
elif type(context).__module__ != _BUILTIN_MODULE:
# Then we consider the argument an "object" for the purposes of
# the spec.
#
# The elif test above lets us avoid treating instances of built-in
# types like integers and strings as objects (cf. issue #81).
# Instances of user-defined classes on the other hand, for example,
# are considered objects by the test above.
try:
attr = getattr(context, key)
except AttributeError:
# TODO: distinguish the case of the attribute not existing from
# an AttributeError being raised by the call to the attribute.
# See the following issue for implementation ideas:
# http://bugs.python.org/issue7559
pass
else:
# TODO: consider using EAFP here instead.
# http://docs.python.org/glossary.html#term-eafp
if callable(attr):
return attr()
return attr
return _NOT_FOUND | python | def _get_value(context, key):
"""
Retrieve a key's value from a context item.
Returns _NOT_FOUND if the key does not exist.
The ContextStack.get() docstring documents this function's intended behavior.
"""
if isinstance(context, dict):
# Then we consider the argument a "hash" for the purposes of the spec.
#
# We do a membership test to avoid using exceptions for flow control
# (e.g. catching KeyError).
if key in context:
return context[key]
elif type(context).__module__ != _BUILTIN_MODULE:
# Then we consider the argument an "object" for the purposes of
# the spec.
#
# The elif test above lets us avoid treating instances of built-in
# types like integers and strings as objects (cf. issue #81).
# Instances of user-defined classes on the other hand, for example,
# are considered objects by the test above.
try:
attr = getattr(context, key)
except AttributeError:
# TODO: distinguish the case of the attribute not existing from
# an AttributeError being raised by the call to the attribute.
# See the following issue for implementation ideas:
# http://bugs.python.org/issue7559
pass
else:
# TODO: consider using EAFP here instead.
# http://docs.python.org/glossary.html#term-eafp
if callable(attr):
return attr()
return attr
return _NOT_FOUND | [
"def",
"_get_value",
"(",
"context",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"context",
",",
"dict",
")",
":",
"# Then we consider the argument a \"hash\" for the purposes of the spec.",
"#",
"# We do a membership test to avoid using exceptions for flow control",
"# (e.g... | Retrieve a key's value from a context item.
Returns _NOT_FOUND if the key does not exist.
The ContextStack.get() docstring documents this function's intended behavior. | [
"Retrieve",
"a",
"key",
"s",
"value",
"from",
"a",
"context",
"item",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/context.py#L37-L76 | train | 207,087 |
defunkt/pystache | pystache/context.py | ContextStack.create | def create(*context, **kwargs):
"""
Build a ContextStack instance from a sequence of context-like items.
This factory-style method is more general than the ContextStack class's
constructor in that, unlike the constructor, the argument list
can itself contain ContextStack instances.
Here is an example illustrating various aspects of this method:
>>> obj1 = {'animal': 'cat', 'vegetable': 'carrot', 'mineral': 'copper'}
>>> obj2 = ContextStack({'vegetable': 'spinach', 'mineral': 'silver'})
>>>
>>> context = ContextStack.create(obj1, None, obj2, mineral='gold')
>>>
>>> context.get('animal')
'cat'
>>> context.get('vegetable')
'spinach'
>>> context.get('mineral')
'gold'
Arguments:
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments will be skipped. Items in the *context list are
added to the stack in order so that later items in the argument
list take precedence over earlier items. This behavior is the
same as the constructor's.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list. This behavior is the same as
the constructor's.
"""
items = context
context = ContextStack()
for item in items:
if item is None:
continue
if isinstance(item, ContextStack):
context._stack.extend(item._stack)
else:
context.push(item)
if kwargs:
context.push(kwargs)
return context | python | def create(*context, **kwargs):
"""
Build a ContextStack instance from a sequence of context-like items.
This factory-style method is more general than the ContextStack class's
constructor in that, unlike the constructor, the argument list
can itself contain ContextStack instances.
Here is an example illustrating various aspects of this method:
>>> obj1 = {'animal': 'cat', 'vegetable': 'carrot', 'mineral': 'copper'}
>>> obj2 = ContextStack({'vegetable': 'spinach', 'mineral': 'silver'})
>>>
>>> context = ContextStack.create(obj1, None, obj2, mineral='gold')
>>>
>>> context.get('animal')
'cat'
>>> context.get('vegetable')
'spinach'
>>> context.get('mineral')
'gold'
Arguments:
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments will be skipped. Items in the *context list are
added to the stack in order so that later items in the argument
list take precedence over earlier items. This behavior is the
same as the constructor's.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list. This behavior is the same as
the constructor's.
"""
items = context
context = ContextStack()
for item in items:
if item is None:
continue
if isinstance(item, ContextStack):
context._stack.extend(item._stack)
else:
context.push(item)
if kwargs:
context.push(kwargs)
return context | [
"def",
"create",
"(",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
"=",
"context",
"context",
"=",
"ContextStack",
"(",
")",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"is",
"None",
":",
"continue",
"if",
"isinstance",
"(",
"item... | Build a ContextStack instance from a sequence of context-like items.
This factory-style method is more general than the ContextStack class's
constructor in that, unlike the constructor, the argument list
can itself contain ContextStack instances.
Here is an example illustrating various aspects of this method:
>>> obj1 = {'animal': 'cat', 'vegetable': 'carrot', 'mineral': 'copper'}
>>> obj2 = ContextStack({'vegetable': 'spinach', 'mineral': 'silver'})
>>>
>>> context = ContextStack.create(obj1, None, obj2, mineral='gold')
>>>
>>> context.get('animal')
'cat'
>>> context.get('vegetable')
'spinach'
>>> context.get('mineral')
'gold'
Arguments:
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments will be skipped. Items in the *context list are
added to the stack in order so that later items in the argument
list take precedence over earlier items. This behavior is the
same as the constructor's.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list. This behavior is the same as
the constructor's. | [
"Build",
"a",
"ContextStack",
"instance",
"from",
"a",
"sequence",
"of",
"context",
"-",
"like",
"items",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/context.py#L146-L199 | train | 207,088 |
defunkt/pystache | pystache/context.py | ContextStack.get | def get(self, name):
"""
Resolve a dotted name against the current context stack.
This function follows the rules outlined in the section of the
spec regarding tag interpolation. This function returns the value
as is and does not coerce the return value to a string.
Arguments:
name: a dotted or non-dotted name.
default: the value to return if name resolution fails at any point.
Defaults to the empty string per the Mustache spec.
This method queries items in the stack in order from last-added
objects to first (last in, first out). The value returned is
the value of the key in the first item that contains the key.
If the key is not found in any item in the stack, then the default
value is returned. The default value defaults to None.
In accordance with the spec, this method queries items in the
stack for a key differently depending on whether the item is a
hash, object, or neither (as defined in the module docstring):
(1) Hash: if the item is a hash, then the key's value is the
dictionary value of the key. If the dictionary doesn't contain
the key, then the key is considered not found.
(2) Object: if the item is an an object, then the method looks for
an attribute with the same name as the key. If an attribute
with that name exists, the value of the attribute is returned.
If the attribute is callable, however (i.e. if the attribute
is a method), then the attribute is called with no arguments
and that value is returned. If there is no attribute with
the same name as the key, then the key is considered not found.
(3) Neither: if the item is neither a hash nor an object, then
the key is considered not found.
*Caution*:
Callables are handled differently depending on whether they are
dictionary values, as in (1) above, or attributes, as in (2).
The former are returned as-is, while the latter are first
called and that value returned.
Here is an example to illustrate:
>>> def greet():
... return "Hi Bob!"
>>>
>>> class Greeter(object):
... greet = None
>>>
>>> dct = {'greet': greet}
>>> obj = Greeter()
>>> obj.greet = greet
>>>
>>> dct['greet'] is obj.greet
True
>>> ContextStack(dct).get('greet') #doctest: +ELLIPSIS
<function greet at 0x...>
>>> ContextStack(obj).get('greet')
'Hi Bob!'
TODO: explain the rationale for this difference in treatment.
"""
if name == '.':
try:
return self.top()
except IndexError:
raise KeyNotFoundError(".", "empty context stack")
parts = name.split('.')
try:
result = self._get_simple(parts[0])
except KeyNotFoundError:
raise KeyNotFoundError(name, "first part")
for part in parts[1:]:
# The full context stack is not used to resolve the remaining parts.
# From the spec--
#
# 5) If any name parts were retained in step 1, each should be
# resolved against a context stack containing only the result
# from the former resolution. If any part fails resolution, the
# result should be considered falsey, and should interpolate as
# the empty string.
#
# TODO: make sure we have a test case for the above point.
result = _get_value(result, part)
# TODO: consider using EAFP here instead.
# http://docs.python.org/glossary.html#term-eafp
if result is _NOT_FOUND:
raise KeyNotFoundError(name, "missing %s" % repr(part))
return result | python | def get(self, name):
"""
Resolve a dotted name against the current context stack.
This function follows the rules outlined in the section of the
spec regarding tag interpolation. This function returns the value
as is and does not coerce the return value to a string.
Arguments:
name: a dotted or non-dotted name.
default: the value to return if name resolution fails at any point.
Defaults to the empty string per the Mustache spec.
This method queries items in the stack in order from last-added
objects to first (last in, first out). The value returned is
the value of the key in the first item that contains the key.
If the key is not found in any item in the stack, then the default
value is returned. The default value defaults to None.
In accordance with the spec, this method queries items in the
stack for a key differently depending on whether the item is a
hash, object, or neither (as defined in the module docstring):
(1) Hash: if the item is a hash, then the key's value is the
dictionary value of the key. If the dictionary doesn't contain
the key, then the key is considered not found.
(2) Object: if the item is an an object, then the method looks for
an attribute with the same name as the key. If an attribute
with that name exists, the value of the attribute is returned.
If the attribute is callable, however (i.e. if the attribute
is a method), then the attribute is called with no arguments
and that value is returned. If there is no attribute with
the same name as the key, then the key is considered not found.
(3) Neither: if the item is neither a hash nor an object, then
the key is considered not found.
*Caution*:
Callables are handled differently depending on whether they are
dictionary values, as in (1) above, or attributes, as in (2).
The former are returned as-is, while the latter are first
called and that value returned.
Here is an example to illustrate:
>>> def greet():
... return "Hi Bob!"
>>>
>>> class Greeter(object):
... greet = None
>>>
>>> dct = {'greet': greet}
>>> obj = Greeter()
>>> obj.greet = greet
>>>
>>> dct['greet'] is obj.greet
True
>>> ContextStack(dct).get('greet') #doctest: +ELLIPSIS
<function greet at 0x...>
>>> ContextStack(obj).get('greet')
'Hi Bob!'
TODO: explain the rationale for this difference in treatment.
"""
if name == '.':
try:
return self.top()
except IndexError:
raise KeyNotFoundError(".", "empty context stack")
parts = name.split('.')
try:
result = self._get_simple(parts[0])
except KeyNotFoundError:
raise KeyNotFoundError(name, "first part")
for part in parts[1:]:
# The full context stack is not used to resolve the remaining parts.
# From the spec--
#
# 5) If any name parts were retained in step 1, each should be
# resolved against a context stack containing only the result
# from the former resolution. If any part fails resolution, the
# result should be considered falsey, and should interpolate as
# the empty string.
#
# TODO: make sure we have a test case for the above point.
result = _get_value(result, part)
# TODO: consider using EAFP here instead.
# http://docs.python.org/glossary.html#term-eafp
if result is _NOT_FOUND:
raise KeyNotFoundError(name, "missing %s" % repr(part))
return result | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"==",
"'.'",
":",
"try",
":",
"return",
"self",
".",
"top",
"(",
")",
"except",
"IndexError",
":",
"raise",
"KeyNotFoundError",
"(",
"\".\"",
",",
"\"empty context stack\"",
")",
"parts",
... | Resolve a dotted name against the current context stack.
This function follows the rules outlined in the section of the
spec regarding tag interpolation. This function returns the value
as is and does not coerce the return value to a string.
Arguments:
name: a dotted or non-dotted name.
default: the value to return if name resolution fails at any point.
Defaults to the empty string per the Mustache spec.
This method queries items in the stack in order from last-added
objects to first (last in, first out). The value returned is
the value of the key in the first item that contains the key.
If the key is not found in any item in the stack, then the default
value is returned. The default value defaults to None.
In accordance with the spec, this method queries items in the
stack for a key differently depending on whether the item is a
hash, object, or neither (as defined in the module docstring):
(1) Hash: if the item is a hash, then the key's value is the
dictionary value of the key. If the dictionary doesn't contain
the key, then the key is considered not found.
(2) Object: if the item is an an object, then the method looks for
an attribute with the same name as the key. If an attribute
with that name exists, the value of the attribute is returned.
If the attribute is callable, however (i.e. if the attribute
is a method), then the attribute is called with no arguments
and that value is returned. If there is no attribute with
the same name as the key, then the key is considered not found.
(3) Neither: if the item is neither a hash nor an object, then
the key is considered not found.
*Caution*:
Callables are handled differently depending on whether they are
dictionary values, as in (1) above, or attributes, as in (2).
The former are returned as-is, while the latter are first
called and that value returned.
Here is an example to illustrate:
>>> def greet():
... return "Hi Bob!"
>>>
>>> class Greeter(object):
... greet = None
>>>
>>> dct = {'greet': greet}
>>> obj = Greeter()
>>> obj.greet = greet
>>>
>>> dct['greet'] is obj.greet
True
>>> ContextStack(dct).get('greet') #doctest: +ELLIPSIS
<function greet at 0x...>
>>> ContextStack(obj).get('greet')
'Hi Bob!'
TODO: explain the rationale for this difference in treatment. | [
"Resolve",
"a",
"dotted",
"name",
"against",
"the",
"current",
"context",
"stack",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/context.py#L203-L302 | train | 207,089 |
defunkt/pystache | pystache/context.py | ContextStack._get_simple | def _get_simple(self, name):
"""
Query the stack for a non-dotted name.
"""
for item in reversed(self._stack):
result = _get_value(item, name)
if result is not _NOT_FOUND:
return result
raise KeyNotFoundError(name, "part missing") | python | def _get_simple(self, name):
"""
Query the stack for a non-dotted name.
"""
for item in reversed(self._stack):
result = _get_value(item, name)
if result is not _NOT_FOUND:
return result
raise KeyNotFoundError(name, "part missing") | [
"def",
"_get_simple",
"(",
"self",
",",
"name",
")",
":",
"for",
"item",
"in",
"reversed",
"(",
"self",
".",
"_stack",
")",
":",
"result",
"=",
"_get_value",
"(",
"item",
",",
"name",
")",
"if",
"result",
"is",
"not",
"_NOT_FOUND",
":",
"return",
"re... | Query the stack for a non-dotted name. | [
"Query",
"the",
"stack",
"for",
"a",
"non",
"-",
"dotted",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/context.py#L304-L314 | train | 207,090 |
defunkt/pystache | pystache/renderer.py | Renderer._to_unicode_soft | def _to_unicode_soft(self, s):
"""
Convert a basestring to unicode, preserving any unicode subclass.
"""
# We type-check to avoid "TypeError: decoding Unicode is not supported".
# We avoid the Python ternary operator for Python 2.4 support.
if isinstance(s, unicode):
return s
return self.unicode(s) | python | def _to_unicode_soft(self, s):
"""
Convert a basestring to unicode, preserving any unicode subclass.
"""
# We type-check to avoid "TypeError: decoding Unicode is not supported".
# We avoid the Python ternary operator for Python 2.4 support.
if isinstance(s, unicode):
return s
return self.unicode(s) | [
"def",
"_to_unicode_soft",
"(",
"self",
",",
"s",
")",
":",
"# We type-check to avoid \"TypeError: decoding Unicode is not supported\".",
"# We avoid the Python ternary operator for Python 2.4 support.",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"s",
"... | Convert a basestring to unicode, preserving any unicode subclass. | [
"Convert",
"a",
"basestring",
"to",
"unicode",
"preserving",
"any",
"unicode",
"subclass",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L173-L182 | train | 207,091 |
defunkt/pystache | pystache/renderer.py | Renderer.unicode | def unicode(self, b, encoding=None):
"""
Convert a byte string to unicode, using string_encoding and decode_errors.
Arguments:
b: a byte string.
encoding: the name of an encoding. Defaults to the string_encoding
attribute for this instance.
Raises:
TypeError: Because this method calls Python's built-in unicode()
function, this method raises the following exception if the
given string is already unicode:
TypeError: decoding Unicode is not supported
"""
if encoding is None:
encoding = self.string_encoding
# TODO: Wrap UnicodeDecodeErrors with a message about setting
# the string_encoding and decode_errors attributes.
return unicode(b, encoding, self.decode_errors) | python | def unicode(self, b, encoding=None):
"""
Convert a byte string to unicode, using string_encoding and decode_errors.
Arguments:
b: a byte string.
encoding: the name of an encoding. Defaults to the string_encoding
attribute for this instance.
Raises:
TypeError: Because this method calls Python's built-in unicode()
function, this method raises the following exception if the
given string is already unicode:
TypeError: decoding Unicode is not supported
"""
if encoding is None:
encoding = self.string_encoding
# TODO: Wrap UnicodeDecodeErrors with a message about setting
# the string_encoding and decode_errors attributes.
return unicode(b, encoding, self.decode_errors) | [
"def",
"unicode",
"(",
"self",
",",
"b",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"self",
".",
"string_encoding",
"# TODO: Wrap UnicodeDecodeErrors with a message about setting",
"# the string_encoding and decode_erro... | Convert a byte string to unicode, using string_encoding and decode_errors.
Arguments:
b: a byte string.
encoding: the name of an encoding. Defaults to the string_encoding
attribute for this instance.
Raises:
TypeError: Because this method calls Python's built-in unicode()
function, this method raises the following exception if the
given string is already unicode:
TypeError: decoding Unicode is not supported | [
"Convert",
"a",
"byte",
"string",
"to",
"unicode",
"using",
"string_encoding",
"and",
"decode_errors",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L200-L225 | train | 207,092 |
defunkt/pystache | pystache/renderer.py | Renderer._make_loader | def _make_loader(self):
"""
Create a Loader instance using current attributes.
"""
return Loader(file_encoding=self.file_encoding, extension=self.file_extension,
to_unicode=self.unicode, search_dirs=self.search_dirs) | python | def _make_loader(self):
"""
Create a Loader instance using current attributes.
"""
return Loader(file_encoding=self.file_encoding, extension=self.file_extension,
to_unicode=self.unicode, search_dirs=self.search_dirs) | [
"def",
"_make_loader",
"(",
"self",
")",
":",
"return",
"Loader",
"(",
"file_encoding",
"=",
"self",
".",
"file_encoding",
",",
"extension",
"=",
"self",
".",
"file_extension",
",",
"to_unicode",
"=",
"self",
".",
"unicode",
",",
"search_dirs",
"=",
"self",
... | Create a Loader instance using current attributes. | [
"Create",
"a",
"Loader",
"instance",
"using",
"current",
"attributes",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L227-L233 | train | 207,093 |
defunkt/pystache | pystache/renderer.py | Renderer._make_load_template | def _make_load_template(self):
"""
Return a function that loads a template by name.
"""
loader = self._make_loader()
def load_template(template_name):
return loader.load_name(template_name)
return load_template | python | def _make_load_template(self):
"""
Return a function that loads a template by name.
"""
loader = self._make_loader()
def load_template(template_name):
return loader.load_name(template_name)
return load_template | [
"def",
"_make_load_template",
"(",
"self",
")",
":",
"loader",
"=",
"self",
".",
"_make_loader",
"(",
")",
"def",
"load_template",
"(",
"template_name",
")",
":",
"return",
"loader",
".",
"load_name",
"(",
"template_name",
")",
"return",
"load_template"
] | Return a function that loads a template by name. | [
"Return",
"a",
"function",
"that",
"loads",
"a",
"template",
"by",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L235-L245 | train | 207,094 |
defunkt/pystache | pystache/renderer.py | Renderer._make_load_partial | def _make_load_partial(self):
"""
Return a function that loads a partial by name.
"""
if self.partials is None:
return self._make_load_template()
# Otherwise, create a function from the custom partial loader.
partials = self.partials
def load_partial(name):
# TODO: consider using EAFP here instead.
# http://docs.python.org/glossary.html#term-eafp
# This would mean requiring that the custom partial loader
# raise a KeyError on name not found.
template = partials.get(name)
if template is None:
raise TemplateNotFoundError("Name %s not found in partials: %s" %
(repr(name), type(partials)))
# RenderEngine requires that the return value be unicode.
return self._to_unicode_hard(template)
return load_partial | python | def _make_load_partial(self):
"""
Return a function that loads a partial by name.
"""
if self.partials is None:
return self._make_load_template()
# Otherwise, create a function from the custom partial loader.
partials = self.partials
def load_partial(name):
# TODO: consider using EAFP here instead.
# http://docs.python.org/glossary.html#term-eafp
# This would mean requiring that the custom partial loader
# raise a KeyError on name not found.
template = partials.get(name)
if template is None:
raise TemplateNotFoundError("Name %s not found in partials: %s" %
(repr(name), type(partials)))
# RenderEngine requires that the return value be unicode.
return self._to_unicode_hard(template)
return load_partial | [
"def",
"_make_load_partial",
"(",
"self",
")",
":",
"if",
"self",
".",
"partials",
"is",
"None",
":",
"return",
"self",
".",
"_make_load_template",
"(",
")",
"# Otherwise, create a function from the custom partial loader.",
"partials",
"=",
"self",
".",
"partials",
... | Return a function that loads a partial by name. | [
"Return",
"a",
"function",
"that",
"loads",
"a",
"partial",
"by",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L247-L271 | train | 207,095 |
defunkt/pystache | pystache/renderer.py | Renderer._is_missing_tags_strict | def _is_missing_tags_strict(self):
"""
Return whether missing_tags is set to strict.
"""
val = self.missing_tags
if val == MissingTags.strict:
return True
elif val == MissingTags.ignore:
return False
raise Exception("Unsupported 'missing_tags' value: %s" % repr(val)) | python | def _is_missing_tags_strict(self):
"""
Return whether missing_tags is set to strict.
"""
val = self.missing_tags
if val == MissingTags.strict:
return True
elif val == MissingTags.ignore:
return False
raise Exception("Unsupported 'missing_tags' value: %s" % repr(val)) | [
"def",
"_is_missing_tags_strict",
"(",
"self",
")",
":",
"val",
"=",
"self",
".",
"missing_tags",
"if",
"val",
"==",
"MissingTags",
".",
"strict",
":",
"return",
"True",
"elif",
"val",
"==",
"MissingTags",
".",
"ignore",
":",
"return",
"False",
"raise",
"E... | Return whether missing_tags is set to strict. | [
"Return",
"whether",
"missing_tags",
"is",
"set",
"to",
"strict",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L273-L285 | train | 207,096 |
defunkt/pystache | pystache/renderer.py | Renderer._make_render_engine | def _make_render_engine(self):
"""
Return a RenderEngine instance for rendering.
"""
resolve_context = self._make_resolve_context()
resolve_partial = self._make_resolve_partial()
engine = RenderEngine(literal=self._to_unicode_hard,
escape=self._escape_to_unicode,
resolve_context=resolve_context,
resolve_partial=resolve_partial,
to_str=self.str_coerce)
return engine | python | def _make_render_engine(self):
"""
Return a RenderEngine instance for rendering.
"""
resolve_context = self._make_resolve_context()
resolve_partial = self._make_resolve_partial()
engine = RenderEngine(literal=self._to_unicode_hard,
escape=self._escape_to_unicode,
resolve_context=resolve_context,
resolve_partial=resolve_partial,
to_str=self.str_coerce)
return engine | [
"def",
"_make_render_engine",
"(",
"self",
")",
":",
"resolve_context",
"=",
"self",
".",
"_make_resolve_context",
"(",
")",
"resolve_partial",
"=",
"self",
".",
"_make_resolve_partial",
"(",
")",
"engine",
"=",
"RenderEngine",
"(",
"literal",
"=",
"self",
".",
... | Return a RenderEngine instance for rendering. | [
"Return",
"a",
"RenderEngine",
"instance",
"for",
"rendering",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L323-L336 | train | 207,097 |
defunkt/pystache | pystache/renderer.py | Renderer._render_object | def _render_object(self, obj, *context, **kwargs):
"""
Render the template associated with the given object.
"""
loader = self._make_loader()
# TODO: consider an approach that does not require using an if
# block here. For example, perhaps this class's loader can be
# a SpecLoader in all cases, and the SpecLoader instance can
# check the object's type. Or perhaps Loader and SpecLoader
# can be refactored to implement the same interface.
if isinstance(obj, TemplateSpec):
loader = SpecLoader(loader)
template = loader.load(obj)
else:
template = loader.load_object(obj)
context = [obj] + list(context)
return self._render_string(template, *context, **kwargs) | python | def _render_object(self, obj, *context, **kwargs):
"""
Render the template associated with the given object.
"""
loader = self._make_loader()
# TODO: consider an approach that does not require using an if
# block here. For example, perhaps this class's loader can be
# a SpecLoader in all cases, and the SpecLoader instance can
# check the object's type. Or perhaps Loader and SpecLoader
# can be refactored to implement the same interface.
if isinstance(obj, TemplateSpec):
loader = SpecLoader(loader)
template = loader.load(obj)
else:
template = loader.load_object(obj)
context = [obj] + list(context)
return self._render_string(template, *context, **kwargs) | [
"def",
"_render_object",
"(",
"self",
",",
"obj",
",",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"loader",
"=",
"self",
".",
"_make_loader",
"(",
")",
"# TODO: consider an approach that does not require using an if",
"# block here. For example, perhaps this ... | Render the template associated with the given object. | [
"Render",
"the",
"template",
"associated",
"with",
"the",
"given",
"object",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L347-L367 | train | 207,098 |
defunkt/pystache | pystache/renderer.py | Renderer.render_name | def render_name(self, template_name, *context, **kwargs):
"""
Render the template with the given name using the given context.
See the render() docstring for more information.
"""
loader = self._make_loader()
template = loader.load_name(template_name)
return self._render_string(template, *context, **kwargs) | python | def render_name(self, template_name, *context, **kwargs):
"""
Render the template with the given name using the given context.
See the render() docstring for more information.
"""
loader = self._make_loader()
template = loader.load_name(template_name)
return self._render_string(template, *context, **kwargs) | [
"def",
"render_name",
"(",
"self",
",",
"template_name",
",",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"loader",
"=",
"self",
".",
"_make_loader",
"(",
")",
"template",
"=",
"loader",
".",
"load_name",
"(",
"template_name",
")",
"return",
"self... | Render the template with the given name using the given context.
See the render() docstring for more information. | [
"Render",
"the",
"template",
"with",
"the",
"given",
"name",
"using",
"the",
"given",
"context",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L369-L378 | train | 207,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.