id
int32 0
252k
| 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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
246,200 |
ryanjdillon/pyotelem
|
pyotelem/dsp.py
|
findzc
|
def findzc(x, thresh, t_max=None):
'''
Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting a zero-crossing.
t_max: (int)
maximum duration in samples between threshold crossings.
Returns
-------
zc: ndarray
Array containing the start **zc_s**, finish **zc_f** and direction **S**
of zero crossings
where:
* zc_s: the cue of the first threshold-crossing in samples
* zc_f: the cue of the second threshold-crossing in samples
* S: the sign of each zero-crossing (1 = positive-going, -1 = negative-going).
Notes
-----
This routine is a reimplementation of Mark Johnson's Dtag toolbox method
and tested against the Matlab version to be sure it has the same result.
'''
import numpy
# positive threshold: p (over) n (under)
pt_p = x > thresh
pt_n = ~pt_p
# negative threshold: p (over) n (under)
nt_n = x < -thresh
nt_p = ~nt_n
# Over positive threshold +thresh
# neg to pos
pt_np = (pt_p[:-1] & pt_n[1:]).nonzero()[0]
# pos to neg
pt_pn = (pt_n[:-1] & pt_p[1:]).nonzero()[0] + 1
# Over positive threshold +thresh
# neg to pos
nt_np = (nt_p[:-1] & nt_n[1:]).nonzero()[0] + 1
# pos to neg
nt_pn = (nt_n[:-1] & nt_p[1:]).nonzero()[0]
# Concat indices, order sequentially
ind_all = numpy.hstack((pt_np, nt_np, pt_pn, nt_pn))
ind_all.sort()
# Omit rows where just touching but not crossing
crossing_mask = ~(numpy.diff(numpy.sign(x[ind_all])) == 0)
# Append a False to make the same length as ind_all
crossing_mask = numpy.hstack((crossing_mask, False))
# Get 1st and 2nd crossings
ind_1stx = ind_all[crossing_mask]
ind_2ndx = ind_all[numpy.where(crossing_mask)[0]+1]
# TODO odd option to replace with NaNs rather than delete?
# Delete indices that do not have a second crossing
del_ind = numpy.where(ind_2ndx > len(x)-1)[0]
for i in del_ind:
ind_1stx = numpy.delete(ind_1stx, i)
ind_2ndx = numpy.delete(ind_1stx, i)
# Get direction/sign of crossing
signs = numpy.sign(x[ind_1stx])*-1
# Add column of direction and transpose
zc = numpy.vstack((ind_1stx, ind_2ndx, signs)).T
# TODO not mentioned in docstring, remove?
#x_norm? = ((x[:, 1] * zc[:, 0]) - (x[:, 0] * zc[:, 1])) / x[:, 1] - x[:, 0]
if t_max:
zc = zc[zc[:, 1] - zc[:, 0] <= t_max, :]
return zc.astype(int)
|
python
|
def findzc(x, thresh, t_max=None):
'''
Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting a zero-crossing.
t_max: (int)
maximum duration in samples between threshold crossings.
Returns
-------
zc: ndarray
Array containing the start **zc_s**, finish **zc_f** and direction **S**
of zero crossings
where:
* zc_s: the cue of the first threshold-crossing in samples
* zc_f: the cue of the second threshold-crossing in samples
* S: the sign of each zero-crossing (1 = positive-going, -1 = negative-going).
Notes
-----
This routine is a reimplementation of Mark Johnson's Dtag toolbox method
and tested against the Matlab version to be sure it has the same result.
'''
import numpy
# positive threshold: p (over) n (under)
pt_p = x > thresh
pt_n = ~pt_p
# negative threshold: p (over) n (under)
nt_n = x < -thresh
nt_p = ~nt_n
# Over positive threshold +thresh
# neg to pos
pt_np = (pt_p[:-1] & pt_n[1:]).nonzero()[0]
# pos to neg
pt_pn = (pt_n[:-1] & pt_p[1:]).nonzero()[0] + 1
# Over positive threshold +thresh
# neg to pos
nt_np = (nt_p[:-1] & nt_n[1:]).nonzero()[0] + 1
# pos to neg
nt_pn = (nt_n[:-1] & nt_p[1:]).nonzero()[0]
# Concat indices, order sequentially
ind_all = numpy.hstack((pt_np, nt_np, pt_pn, nt_pn))
ind_all.sort()
# Omit rows where just touching but not crossing
crossing_mask = ~(numpy.diff(numpy.sign(x[ind_all])) == 0)
# Append a False to make the same length as ind_all
crossing_mask = numpy.hstack((crossing_mask, False))
# Get 1st and 2nd crossings
ind_1stx = ind_all[crossing_mask]
ind_2ndx = ind_all[numpy.where(crossing_mask)[0]+1]
# TODO odd option to replace with NaNs rather than delete?
# Delete indices that do not have a second crossing
del_ind = numpy.where(ind_2ndx > len(x)-1)[0]
for i in del_ind:
ind_1stx = numpy.delete(ind_1stx, i)
ind_2ndx = numpy.delete(ind_1stx, i)
# Get direction/sign of crossing
signs = numpy.sign(x[ind_1stx])*-1
# Add column of direction and transpose
zc = numpy.vstack((ind_1stx, ind_2ndx, signs)).T
# TODO not mentioned in docstring, remove?
#x_norm? = ((x[:, 1] * zc[:, 0]) - (x[:, 0] * zc[:, 1])) / x[:, 1] - x[:, 0]
if t_max:
zc = zc[zc[:, 1] - zc[:, 0] <= t_max, :]
return zc.astype(int)
|
[
"def",
"findzc",
"(",
"x",
",",
"thresh",
",",
"t_max",
"=",
"None",
")",
":",
"import",
"numpy",
"# positive threshold: p (over) n (under)",
"pt_p",
"=",
"x",
">",
"thresh",
"pt_n",
"=",
"~",
"pt_p",
"# negative threshold: p (over) n (under)",
"nt_n",
"=",
"x",
"<",
"-",
"thresh",
"nt_p",
"=",
"~",
"nt_n",
"# Over positive threshold +thresh",
"# neg to pos",
"pt_np",
"=",
"(",
"pt_p",
"[",
":",
"-",
"1",
"]",
"&",
"pt_n",
"[",
"1",
":",
"]",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"# pos to neg",
"pt_pn",
"=",
"(",
"pt_n",
"[",
":",
"-",
"1",
"]",
"&",
"pt_p",
"[",
"1",
":",
"]",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"+",
"1",
"# Over positive threshold +thresh",
"# neg to pos",
"nt_np",
"=",
"(",
"nt_p",
"[",
":",
"-",
"1",
"]",
"&",
"nt_n",
"[",
"1",
":",
"]",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"+",
"1",
"# pos to neg",
"nt_pn",
"=",
"(",
"nt_n",
"[",
":",
"-",
"1",
"]",
"&",
"nt_p",
"[",
"1",
":",
"]",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"# Concat indices, order sequentially",
"ind_all",
"=",
"numpy",
".",
"hstack",
"(",
"(",
"pt_np",
",",
"nt_np",
",",
"pt_pn",
",",
"nt_pn",
")",
")",
"ind_all",
".",
"sort",
"(",
")",
"# Omit rows where just touching but not crossing",
"crossing_mask",
"=",
"~",
"(",
"numpy",
".",
"diff",
"(",
"numpy",
".",
"sign",
"(",
"x",
"[",
"ind_all",
"]",
")",
")",
"==",
"0",
")",
"# Append a False to make the same length as ind_all",
"crossing_mask",
"=",
"numpy",
".",
"hstack",
"(",
"(",
"crossing_mask",
",",
"False",
")",
")",
"# Get 1st and 2nd crossings",
"ind_1stx",
"=",
"ind_all",
"[",
"crossing_mask",
"]",
"ind_2ndx",
"=",
"ind_all",
"[",
"numpy",
".",
"where",
"(",
"crossing_mask",
")",
"[",
"0",
"]",
"+",
"1",
"]",
"# TODO odd option to replace with NaNs rather than delete?",
"# Delete indices that do not have a second crossing",
"del_ind",
"=",
"numpy",
".",
"where",
"(",
"ind_2ndx",
">",
"len",
"(",
"x",
")",
"-",
"1",
")",
"[",
"0",
"]",
"for",
"i",
"in",
"del_ind",
":",
"ind_1stx",
"=",
"numpy",
".",
"delete",
"(",
"ind_1stx",
",",
"i",
")",
"ind_2ndx",
"=",
"numpy",
".",
"delete",
"(",
"ind_1stx",
",",
"i",
")",
"# Get direction/sign of crossing",
"signs",
"=",
"numpy",
".",
"sign",
"(",
"x",
"[",
"ind_1stx",
"]",
")",
"*",
"-",
"1",
"# Add column of direction and transpose",
"zc",
"=",
"numpy",
".",
"vstack",
"(",
"(",
"ind_1stx",
",",
"ind_2ndx",
",",
"signs",
")",
")",
".",
"T",
"# TODO not mentioned in docstring, remove?",
"#x_norm? = ((x[:, 1] * zc[:, 0]) - (x[:, 0] * zc[:, 1])) / x[:, 1] - x[:, 0]",
"if",
"t_max",
":",
"zc",
"=",
"zc",
"[",
"zc",
"[",
":",
",",
"1",
"]",
"-",
"zc",
"[",
":",
",",
"0",
"]",
"<=",
"t_max",
",",
":",
"]",
"return",
"zc",
".",
"astype",
"(",
"int",
")"
] |
Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting a zero-crossing.
t_max: (int)
maximum duration in samples between threshold crossings.
Returns
-------
zc: ndarray
Array containing the start **zc_s**, finish **zc_f** and direction **S**
of zero crossings
where:
* zc_s: the cue of the first threshold-crossing in samples
* zc_f: the cue of the second threshold-crossing in samples
* S: the sign of each zero-crossing (1 = positive-going, -1 = negative-going).
Notes
-----
This routine is a reimplementation of Mark Johnson's Dtag toolbox method
and tested against the Matlab version to be sure it has the same result.
|
[
"Find",
"cues",
"to",
"each",
"zero",
"-",
"crossing",
"in",
"vector",
"x",
"."
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L27-L113
|
246,201 |
ryanjdillon/pyotelem
|
pyotelem/dsp.py
|
butter_filter
|
def butter_filter(cutoff, fs, order=5, btype='low'):
'''Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' creates a low-frequency filter and
'high' creates a high-frequency filter (Default 'low).
Returns
-------
b: ndarray
Numerator polynomials of the IIR butter filter
a: ndarray
Denominator polynomials of the IIR butter filter
Notes
-----
This function was adapted from the following StackOverflow answer:
http://stackoverflow.com/a/25192640/943773
'''
import scipy.signal
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = scipy.signal.butter(order, normal_cutoff, btype=btype, analog=False)
return b, a
|
python
|
def butter_filter(cutoff, fs, order=5, btype='low'):
'''Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' creates a low-frequency filter and
'high' creates a high-frequency filter (Default 'low).
Returns
-------
b: ndarray
Numerator polynomials of the IIR butter filter
a: ndarray
Denominator polynomials of the IIR butter filter
Notes
-----
This function was adapted from the following StackOverflow answer:
http://stackoverflow.com/a/25192640/943773
'''
import scipy.signal
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = scipy.signal.butter(order, normal_cutoff, btype=btype, analog=False)
return b, a
|
[
"def",
"butter_filter",
"(",
"cutoff",
",",
"fs",
",",
"order",
"=",
"5",
",",
"btype",
"=",
"'low'",
")",
":",
"import",
"scipy",
".",
"signal",
"nyq",
"=",
"0.5",
"*",
"fs",
"normal_cutoff",
"=",
"cutoff",
"/",
"nyq",
"b",
",",
"a",
"=",
"scipy",
".",
"signal",
".",
"butter",
"(",
"order",
",",
"normal_cutoff",
",",
"btype",
"=",
"btype",
",",
"analog",
"=",
"False",
")",
"return",
"b",
",",
"a"
] |
Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' creates a low-frequency filter and
'high' creates a high-frequency filter (Default 'low).
Returns
-------
b: ndarray
Numerator polynomials of the IIR butter filter
a: ndarray
Denominator polynomials of the IIR butter filter
Notes
-----
This function was adapted from the following StackOverflow answer:
http://stackoverflow.com/a/25192640/943773
|
[
"Create",
"a",
"digital",
"butter",
"fileter",
"with",
"cutoff",
"frequency",
"in",
"Hz"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L116-L147
|
246,202 |
ryanjdillon/pyotelem
|
pyotelem/dsp.py
|
butter_apply
|
def butter_apply(b, a, data):
'''Apply filter with filtfilt to allign filtereted data with input
The filter is applied once forward and once backward to give it linear
phase, using Gustafsson's method to give the same length as the original
signal.
Args
----
b: ndarray
Numerator polynomials of the IIR butter filter
a: ndarray
Denominator polynomials of the IIR butter filter
Returns
-------
x: ndarray
Filtered data with linear phase
Notes
-----
This function was adapted from the following StackOverflow answer:
http://stackoverflow.com/a/25192640/943773
'''
import scipy.signal
return scipy.signal.filtfilt(b, a, data, method='gust')
|
python
|
def butter_apply(b, a, data):
'''Apply filter with filtfilt to allign filtereted data with input
The filter is applied once forward and once backward to give it linear
phase, using Gustafsson's method to give the same length as the original
signal.
Args
----
b: ndarray
Numerator polynomials of the IIR butter filter
a: ndarray
Denominator polynomials of the IIR butter filter
Returns
-------
x: ndarray
Filtered data with linear phase
Notes
-----
This function was adapted from the following StackOverflow answer:
http://stackoverflow.com/a/25192640/943773
'''
import scipy.signal
return scipy.signal.filtfilt(b, a, data, method='gust')
|
[
"def",
"butter_apply",
"(",
"b",
",",
"a",
",",
"data",
")",
":",
"import",
"scipy",
".",
"signal",
"return",
"scipy",
".",
"signal",
".",
"filtfilt",
"(",
"b",
",",
"a",
",",
"data",
",",
"method",
"=",
"'gust'",
")"
] |
Apply filter with filtfilt to allign filtereted data with input
The filter is applied once forward and once backward to give it linear
phase, using Gustafsson's method to give the same length as the original
signal.
Args
----
b: ndarray
Numerator polynomials of the IIR butter filter
a: ndarray
Denominator polynomials of the IIR butter filter
Returns
-------
x: ndarray
Filtered data with linear phase
Notes
-----
This function was adapted from the following StackOverflow answer:
http://stackoverflow.com/a/25192640/943773
|
[
"Apply",
"filter",
"with",
"filtfilt",
"to",
"allign",
"filtereted",
"data",
"with",
"input"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L150-L176
|
246,203 |
ryanjdillon/pyotelem
|
pyotelem/dsp.py
|
calc_PSD_welch
|
def calc_PSD_welch(x, fs, nperseg):
'''Caclulate power spectral density with Welch's method
Args
----
x: ndarray
sample array
fs: float
sampling frequency (1/dt)
Returns
-------
f_welch: ndarray
Discrete frequencies
S_xx_welch: ndarray
Estimated PSD at discrete frequencies `f_welch`
P_welch: ndarray
Signal power (integrated PSD)
df_welch: ndarray
Delta between discreet frequencies `f_welch`
'''
import numpy
import scipy.signal
# Code source and description of FFT, DFT, etc.
# http://stackoverflow.com/a/33251324/943773
dt = 1/fs
N = len(x)
times = numpy.arange(N) / fs
# Estimate PSD `S_xx_welch` at discrete frequencies `f_welch`
f_welch, S_xx_welch = scipy.signal.welch(x, fs=fs, nperseg=nperseg)
# Integrate PSD over spectral bandwidth
# to obtain signal power `P_welch`
df_welch = f_welch[1] - f_welch[0]
P_welch = numpy.sum(S_xx_welch) * df_welch
return f_welch, S_xx_welch, P_welch, df_welch
|
python
|
def calc_PSD_welch(x, fs, nperseg):
'''Caclulate power spectral density with Welch's method
Args
----
x: ndarray
sample array
fs: float
sampling frequency (1/dt)
Returns
-------
f_welch: ndarray
Discrete frequencies
S_xx_welch: ndarray
Estimated PSD at discrete frequencies `f_welch`
P_welch: ndarray
Signal power (integrated PSD)
df_welch: ndarray
Delta between discreet frequencies `f_welch`
'''
import numpy
import scipy.signal
# Code source and description of FFT, DFT, etc.
# http://stackoverflow.com/a/33251324/943773
dt = 1/fs
N = len(x)
times = numpy.arange(N) / fs
# Estimate PSD `S_xx_welch` at discrete frequencies `f_welch`
f_welch, S_xx_welch = scipy.signal.welch(x, fs=fs, nperseg=nperseg)
# Integrate PSD over spectral bandwidth
# to obtain signal power `P_welch`
df_welch = f_welch[1] - f_welch[0]
P_welch = numpy.sum(S_xx_welch) * df_welch
return f_welch, S_xx_welch, P_welch, df_welch
|
[
"def",
"calc_PSD_welch",
"(",
"x",
",",
"fs",
",",
"nperseg",
")",
":",
"import",
"numpy",
"import",
"scipy",
".",
"signal",
"# Code source and description of FFT, DFT, etc.",
"# http://stackoverflow.com/a/33251324/943773",
"dt",
"=",
"1",
"/",
"fs",
"N",
"=",
"len",
"(",
"x",
")",
"times",
"=",
"numpy",
".",
"arange",
"(",
"N",
")",
"/",
"fs",
"# Estimate PSD `S_xx_welch` at discrete frequencies `f_welch`",
"f_welch",
",",
"S_xx_welch",
"=",
"scipy",
".",
"signal",
".",
"welch",
"(",
"x",
",",
"fs",
"=",
"fs",
",",
"nperseg",
"=",
"nperseg",
")",
"# Integrate PSD over spectral bandwidth",
"# to obtain signal power `P_welch`",
"df_welch",
"=",
"f_welch",
"[",
"1",
"]",
"-",
"f_welch",
"[",
"0",
"]",
"P_welch",
"=",
"numpy",
".",
"sum",
"(",
"S_xx_welch",
")",
"*",
"df_welch",
"return",
"f_welch",
",",
"S_xx_welch",
",",
"P_welch",
",",
"df_welch"
] |
Caclulate power spectral density with Welch's method
Args
----
x: ndarray
sample array
fs: float
sampling frequency (1/dt)
Returns
-------
f_welch: ndarray
Discrete frequencies
S_xx_welch: ndarray
Estimated PSD at discrete frequencies `f_welch`
P_welch: ndarray
Signal power (integrated PSD)
df_welch: ndarray
Delta between discreet frequencies `f_welch`
|
[
"Caclulate",
"power",
"spectral",
"density",
"with",
"Welch",
"s",
"method"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L179-L217
|
246,204 |
ryanjdillon/pyotelem
|
pyotelem/dsp.py
|
simple_peakfinder
|
def simple_peakfinder(x, y, delta):
'''Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
delta: float
minimum change in `y` since previous peak to be considered new peak.
It should be positive and it's absolute value taken to ensure this.
x: ndarray
corresponding x-axis positions to y array
Returns
-------
max_ind: ndarray
Indices of local maxima
min_ind: ndarray
Indices of local minima
Example
-------
max_ind, min_ind = simple_peakfinder(x, y, delta)
# get values of `y` at local maxima
local_max = y[max_ind]
Notes
-----
Matlab Author: Eli Billauer http://billauer.co.il/peakdet.html
Python translation: Chris Muktar https://gist.github.com/endolith/250860
Python cleanup: Ryan J. Dillon
'''
import numpy
y = numpy.asarray(y)
max_ind = list()
min_ind = list()
local_min = numpy.inf
local_max = -numpy.inf
local_min_pos = numpy.nan
local_max_pos = numpy.nan
lookformax = True
for i in range(len(y)):
if y[i] > local_max:
local_max = y[i]
local_max_pos = x[i]
if y[i] < local_min:
local_min = y[i]
local_min_pos = x[i]
if lookformax:
if y[i] < local_max-abs(delta):
max_ind.append(local_max_pos)
local_min = y[i]
local_min_pos = x[i]
lookformax = False
else:
if y[i] > local_min+abs(delta):
min_ind.append(local_min_pos)
local_max = y[i]
local_max_pos = x[i]
lookformax = True
return numpy.array(max_ind), numpy.array(min_ind)
|
python
|
def simple_peakfinder(x, y, delta):
'''Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
delta: float
minimum change in `y` since previous peak to be considered new peak.
It should be positive and it's absolute value taken to ensure this.
x: ndarray
corresponding x-axis positions to y array
Returns
-------
max_ind: ndarray
Indices of local maxima
min_ind: ndarray
Indices of local minima
Example
-------
max_ind, min_ind = simple_peakfinder(x, y, delta)
# get values of `y` at local maxima
local_max = y[max_ind]
Notes
-----
Matlab Author: Eli Billauer http://billauer.co.il/peakdet.html
Python translation: Chris Muktar https://gist.github.com/endolith/250860
Python cleanup: Ryan J. Dillon
'''
import numpy
y = numpy.asarray(y)
max_ind = list()
min_ind = list()
local_min = numpy.inf
local_max = -numpy.inf
local_min_pos = numpy.nan
local_max_pos = numpy.nan
lookformax = True
for i in range(len(y)):
if y[i] > local_max:
local_max = y[i]
local_max_pos = x[i]
if y[i] < local_min:
local_min = y[i]
local_min_pos = x[i]
if lookformax:
if y[i] < local_max-abs(delta):
max_ind.append(local_max_pos)
local_min = y[i]
local_min_pos = x[i]
lookformax = False
else:
if y[i] > local_min+abs(delta):
min_ind.append(local_min_pos)
local_max = y[i]
local_max_pos = x[i]
lookformax = True
return numpy.array(max_ind), numpy.array(min_ind)
|
[
"def",
"simple_peakfinder",
"(",
"x",
",",
"y",
",",
"delta",
")",
":",
"import",
"numpy",
"y",
"=",
"numpy",
".",
"asarray",
"(",
"y",
")",
"max_ind",
"=",
"list",
"(",
")",
"min_ind",
"=",
"list",
"(",
")",
"local_min",
"=",
"numpy",
".",
"inf",
"local_max",
"=",
"-",
"numpy",
".",
"inf",
"local_min_pos",
"=",
"numpy",
".",
"nan",
"local_max_pos",
"=",
"numpy",
".",
"nan",
"lookformax",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"y",
")",
")",
":",
"if",
"y",
"[",
"i",
"]",
">",
"local_max",
":",
"local_max",
"=",
"y",
"[",
"i",
"]",
"local_max_pos",
"=",
"x",
"[",
"i",
"]",
"if",
"y",
"[",
"i",
"]",
"<",
"local_min",
":",
"local_min",
"=",
"y",
"[",
"i",
"]",
"local_min_pos",
"=",
"x",
"[",
"i",
"]",
"if",
"lookformax",
":",
"if",
"y",
"[",
"i",
"]",
"<",
"local_max",
"-",
"abs",
"(",
"delta",
")",
":",
"max_ind",
".",
"append",
"(",
"local_max_pos",
")",
"local_min",
"=",
"y",
"[",
"i",
"]",
"local_min_pos",
"=",
"x",
"[",
"i",
"]",
"lookformax",
"=",
"False",
"else",
":",
"if",
"y",
"[",
"i",
"]",
">",
"local_min",
"+",
"abs",
"(",
"delta",
")",
":",
"min_ind",
".",
"append",
"(",
"local_min_pos",
")",
"local_max",
"=",
"y",
"[",
"i",
"]",
"local_max_pos",
"=",
"x",
"[",
"i",
"]",
"lookformax",
"=",
"True",
"return",
"numpy",
".",
"array",
"(",
"max_ind",
")",
",",
"numpy",
".",
"array",
"(",
"min_ind",
")"
] |
Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
delta: float
minimum change in `y` since previous peak to be considered new peak.
It should be positive and it's absolute value taken to ensure this.
x: ndarray
corresponding x-axis positions to y array
Returns
-------
max_ind: ndarray
Indices of local maxima
min_ind: ndarray
Indices of local minima
Example
-------
max_ind, min_ind = simple_peakfinder(x, y, delta)
# get values of `y` at local maxima
local_max = y[max_ind]
Notes
-----
Matlab Author: Eli Billauer http://billauer.co.il/peakdet.html
Python translation: Chris Muktar https://gist.github.com/endolith/250860
Python cleanup: Ryan J. Dillon
|
[
"Detect",
"local",
"maxima",
"and",
"minima",
"in",
"a",
"vector"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L220-L293
|
246,205 |
brews/carbonferret
|
carbonferret/core.py
|
find_near
|
def find_near(lat, lon, *, n=10, session=None):
"""Return n results for a given latitude and longitude"""
search_params = {'npoints': n, 'clat': lat, 'clon': lon,
'Columns[]': ['Subregion', 'Notes', 'CollectionYear',
'ReservoirAge', 'ReservoirErr', 'C14age',
'C14err', 'LabID', 'Delta13C', 'nextime',
'Genus', 'Species', 'Feeding', 'Name']}
resp = _query_near(session=session, **search_params)
df = _response_to_dataframe(resp)
df_clean = _clean_dataframe(df)
return df_clean
|
python
|
def find_near(lat, lon, *, n=10, session=None):
"""Return n results for a given latitude and longitude"""
search_params = {'npoints': n, 'clat': lat, 'clon': lon,
'Columns[]': ['Subregion', 'Notes', 'CollectionYear',
'ReservoirAge', 'ReservoirErr', 'C14age',
'C14err', 'LabID', 'Delta13C', 'nextime',
'Genus', 'Species', 'Feeding', 'Name']}
resp = _query_near(session=session, **search_params)
df = _response_to_dataframe(resp)
df_clean = _clean_dataframe(df)
return df_clean
|
[
"def",
"find_near",
"(",
"lat",
",",
"lon",
",",
"*",
",",
"n",
"=",
"10",
",",
"session",
"=",
"None",
")",
":",
"search_params",
"=",
"{",
"'npoints'",
":",
"n",
",",
"'clat'",
":",
"lat",
",",
"'clon'",
":",
"lon",
",",
"'Columns[]'",
":",
"[",
"'Subregion'",
",",
"'Notes'",
",",
"'CollectionYear'",
",",
"'ReservoirAge'",
",",
"'ReservoirErr'",
",",
"'C14age'",
",",
"'C14err'",
",",
"'LabID'",
",",
"'Delta13C'",
",",
"'nextime'",
",",
"'Genus'",
",",
"'Species'",
",",
"'Feeding'",
",",
"'Name'",
"]",
"}",
"resp",
"=",
"_query_near",
"(",
"session",
"=",
"session",
",",
"*",
"*",
"search_params",
")",
"df",
"=",
"_response_to_dataframe",
"(",
"resp",
")",
"df_clean",
"=",
"_clean_dataframe",
"(",
"df",
")",
"return",
"df_clean"
] |
Return n results for a given latitude and longitude
|
[
"Return",
"n",
"results",
"for",
"a",
"given",
"latitude",
"and",
"longitude"
] |
afbf901178b328bbc770129adc35c1403404b197
|
https://github.com/brews/carbonferret/blob/afbf901178b328bbc770129adc35c1403404b197/carbonferret/core.py#L5-L15
|
246,206 |
brews/carbonferret
|
carbonferret/core.py
|
_query_near
|
def _query_near(*, session=None, **kwargs):
"""Query marine database with given query string values and keys"""
url_endpoint = 'http://calib.org/marine/index.html'
if session is not None:
resp = session.get(url_endpoint, params=kwargs)
else:
with requests.Session() as s:
# Need to get the index page before query. Otherwise get bad query response that seems legit.
s.get('http://calib.org/marine/index.html')
resp = s.get(url_endpoint, params=kwargs)
return resp
|
python
|
def _query_near(*, session=None, **kwargs):
"""Query marine database with given query string values and keys"""
url_endpoint = 'http://calib.org/marine/index.html'
if session is not None:
resp = session.get(url_endpoint, params=kwargs)
else:
with requests.Session() as s:
# Need to get the index page before query. Otherwise get bad query response that seems legit.
s.get('http://calib.org/marine/index.html')
resp = s.get(url_endpoint, params=kwargs)
return resp
|
[
"def",
"_query_near",
"(",
"*",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url_endpoint",
"=",
"'http://calib.org/marine/index.html'",
"if",
"session",
"is",
"not",
"None",
":",
"resp",
"=",
"session",
".",
"get",
"(",
"url_endpoint",
",",
"params",
"=",
"kwargs",
")",
"else",
":",
"with",
"requests",
".",
"Session",
"(",
")",
"as",
"s",
":",
"# Need to get the index page before query. Otherwise get bad query response that seems legit.",
"s",
".",
"get",
"(",
"'http://calib.org/marine/index.html'",
")",
"resp",
"=",
"s",
".",
"get",
"(",
"url_endpoint",
",",
"params",
"=",
"kwargs",
")",
"return",
"resp"
] |
Query marine database with given query string values and keys
|
[
"Query",
"marine",
"database",
"with",
"given",
"query",
"string",
"values",
"and",
"keys"
] |
afbf901178b328bbc770129adc35c1403404b197
|
https://github.com/brews/carbonferret/blob/afbf901178b328bbc770129adc35c1403404b197/carbonferret/core.py#L18-L28
|
246,207 |
klen/muffin-debugtoolbar
|
muffin_debugtoolbar/panels.py
|
DebugPanel.render_content
|
def render_content(self):
"""Render the panel's content."""
if not self.has_content:
return ""
template = self.template
if isinstance(self.template, str):
template = self.app.ps.jinja2.env.get_template(self.template)
context = self.render_vars()
content = template.render(app=self.app, request=self.request, **context)
return content
|
python
|
def render_content(self):
"""Render the panel's content."""
if not self.has_content:
return ""
template = self.template
if isinstance(self.template, str):
template = self.app.ps.jinja2.env.get_template(self.template)
context = self.render_vars()
content = template.render(app=self.app, request=self.request, **context)
return content
|
[
"def",
"render_content",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_content",
":",
"return",
"\"\"",
"template",
"=",
"self",
".",
"template",
"if",
"isinstance",
"(",
"self",
".",
"template",
",",
"str",
")",
":",
"template",
"=",
"self",
".",
"app",
".",
"ps",
".",
"jinja2",
".",
"env",
".",
"get_template",
"(",
"self",
".",
"template",
")",
"context",
"=",
"self",
".",
"render_vars",
"(",
")",
"content",
"=",
"template",
".",
"render",
"(",
"app",
"=",
"self",
".",
"app",
",",
"request",
"=",
"self",
".",
"request",
",",
"*",
"*",
"context",
")",
"return",
"content"
] |
Render the panel's content.
|
[
"Render",
"the",
"panel",
"s",
"content",
"."
] |
b650b35fbe2035888f6bba5dac3073ef01c94dc6
|
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/panels.py#L57-L66
|
246,208 |
klen/muffin-debugtoolbar
|
muffin_debugtoolbar/panels.py
|
HeaderDebugPanel.process_response
|
def process_response(self, response):
"""Store response headers."""
self.response_headers = [(k, v) for k, v in sorted(response.headers.items())]
|
python
|
def process_response(self, response):
"""Store response headers."""
self.response_headers = [(k, v) for k, v in sorted(response.headers.items())]
|
[
"def",
"process_response",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"response_headers",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"response",
".",
"headers",
".",
"items",
"(",
")",
")",
"]"
] |
Store response headers.
|
[
"Store",
"response",
"headers",
"."
] |
b650b35fbe2035888f6bba5dac3073ef01c94dc6
|
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/panels.py#L88-L90
|
246,209 |
tbobm/devscripts
|
devscripts/devscripts.py
|
retry
|
def retry(exception_to_check, tries=5, delay=5, multiplier=2):
'''Tries to call the wrapped function again, after an incremental delay
:param exception_to_check: Exception(s) to check for, before retrying.
:type exception_to_check: Exception
:param tries: Number of time to retry before failling.
:type tries: int
:param delay: time in second to sleep before retrying.
:type delay: int
:param multiplier: multiply the delay each time the exception_to_check
occurs.
:type multiplier: int
'''
def deco_retry(func):
'''Creates the retry decorator'''
@wraps(func)
def func_retry(*args, **kwargs):
'''Actual wrapped function'''
if multiplier >= 1 is not True:
raise ValueError(
'multiplier = {}. It has to be superior to 1.'.format(
multiplier
)
)
mtries, mdelay = tries, delay
while mtries > 1:
try:
return func(*args, **kwargs)
except exception_to_check as err:
message = "%s, retrying in %d seconds..." % (
str(err), mdelay)
print(message)
sleep(mdelay)
mtries -= 1
mdelay *= multiplier
return func(*args, **kwargs)
return func_retry
return deco_retry
|
python
|
def retry(exception_to_check, tries=5, delay=5, multiplier=2):
'''Tries to call the wrapped function again, after an incremental delay
:param exception_to_check: Exception(s) to check for, before retrying.
:type exception_to_check: Exception
:param tries: Number of time to retry before failling.
:type tries: int
:param delay: time in second to sleep before retrying.
:type delay: int
:param multiplier: multiply the delay each time the exception_to_check
occurs.
:type multiplier: int
'''
def deco_retry(func):
'''Creates the retry decorator'''
@wraps(func)
def func_retry(*args, **kwargs):
'''Actual wrapped function'''
if multiplier >= 1 is not True:
raise ValueError(
'multiplier = {}. It has to be superior to 1.'.format(
multiplier
)
)
mtries, mdelay = tries, delay
while mtries > 1:
try:
return func(*args, **kwargs)
except exception_to_check as err:
message = "%s, retrying in %d seconds..." % (
str(err), mdelay)
print(message)
sleep(mdelay)
mtries -= 1
mdelay *= multiplier
return func(*args, **kwargs)
return func_retry
return deco_retry
|
[
"def",
"retry",
"(",
"exception_to_check",
",",
"tries",
"=",
"5",
",",
"delay",
"=",
"5",
",",
"multiplier",
"=",
"2",
")",
":",
"def",
"deco_retry",
"(",
"func",
")",
":",
"'''Creates the retry decorator'''",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_retry",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'''Actual wrapped function'''",
"if",
"multiplier",
">=",
"1",
"is",
"not",
"True",
":",
"raise",
"ValueError",
"(",
"'multiplier = {}. It has to be superior to 1.'",
".",
"format",
"(",
"multiplier",
")",
")",
"mtries",
",",
"mdelay",
"=",
"tries",
",",
"delay",
"while",
"mtries",
">",
"1",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"exception_to_check",
"as",
"err",
":",
"message",
"=",
"\"%s, retrying in %d seconds...\"",
"%",
"(",
"str",
"(",
"err",
")",
",",
"mdelay",
")",
"print",
"(",
"message",
")",
"sleep",
"(",
"mdelay",
")",
"mtries",
"-=",
"1",
"mdelay",
"*=",
"multiplier",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"func_retry",
"return",
"deco_retry"
] |
Tries to call the wrapped function again, after an incremental delay
:param exception_to_check: Exception(s) to check for, before retrying.
:type exception_to_check: Exception
:param tries: Number of time to retry before failling.
:type tries: int
:param delay: time in second to sleep before retrying.
:type delay: int
:param multiplier: multiply the delay each time the exception_to_check
occurs.
:type multiplier: int
|
[
"Tries",
"to",
"call",
"the",
"wrapped",
"function",
"again",
"after",
"an",
"incremental",
"delay"
] |
beb23371ba80739afb5474766e8049ead3837925
|
https://github.com/tbobm/devscripts/blob/beb23371ba80739afb5474766e8049ead3837925/devscripts/devscripts.py#L10-L49
|
246,210 |
eddiejessup/agaro
|
agaro/measure_utils.py
|
get_average_measure
|
def get_average_measure(dirname, measure_func, t_steady=None):
"""
Calculate a measure of a model in an output directory, averaged over
all times when the model is at steady-state.
Parameters
----------
dirname: str
Output directory
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
t_steady: None or float
Time to consider the model to be at steady-state.
`None` means just consider the latest time.
Returns
-------
measure: numpy.ndarray
Measure.
measure_errs: numpy.ndarray
Measure uncertainty.
If no averaging is done, this is taken from the measure_func.
Otherwise, the standard error over all samples is used.
"""
if t_steady is None:
meas, meas_err = measure_func(get_recent_model(dirname))
return meas, meas_err
else:
ms = [filename_to_model(fname) for fname in get_filenames(dirname)]
ms_steady = [m for m in ms if m.t > t_steady]
meas_list = [measure_func(m) for m in ms_steady]
meases, meas_errs = zip(*meas_list)
return np.mean(meases), sem(meases)
|
python
|
def get_average_measure(dirname, measure_func, t_steady=None):
"""
Calculate a measure of a model in an output directory, averaged over
all times when the model is at steady-state.
Parameters
----------
dirname: str
Output directory
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
t_steady: None or float
Time to consider the model to be at steady-state.
`None` means just consider the latest time.
Returns
-------
measure: numpy.ndarray
Measure.
measure_errs: numpy.ndarray
Measure uncertainty.
If no averaging is done, this is taken from the measure_func.
Otherwise, the standard error over all samples is used.
"""
if t_steady is None:
meas, meas_err = measure_func(get_recent_model(dirname))
return meas, meas_err
else:
ms = [filename_to_model(fname) for fname in get_filenames(dirname)]
ms_steady = [m for m in ms if m.t > t_steady]
meas_list = [measure_func(m) for m in ms_steady]
meases, meas_errs = zip(*meas_list)
return np.mean(meases), sem(meases)
|
[
"def",
"get_average_measure",
"(",
"dirname",
",",
"measure_func",
",",
"t_steady",
"=",
"None",
")",
":",
"if",
"t_steady",
"is",
"None",
":",
"meas",
",",
"meas_err",
"=",
"measure_func",
"(",
"get_recent_model",
"(",
"dirname",
")",
")",
"return",
"meas",
",",
"meas_err",
"else",
":",
"ms",
"=",
"[",
"filename_to_model",
"(",
"fname",
")",
"for",
"fname",
"in",
"get_filenames",
"(",
"dirname",
")",
"]",
"ms_steady",
"=",
"[",
"m",
"for",
"m",
"in",
"ms",
"if",
"m",
".",
"t",
">",
"t_steady",
"]",
"meas_list",
"=",
"[",
"measure_func",
"(",
"m",
")",
"for",
"m",
"in",
"ms_steady",
"]",
"meases",
",",
"meas_errs",
"=",
"zip",
"(",
"*",
"meas_list",
")",
"return",
"np",
".",
"mean",
"(",
"meases",
")",
",",
"sem",
"(",
"meases",
")"
] |
Calculate a measure of a model in an output directory, averaged over
all times when the model is at steady-state.
Parameters
----------
dirname: str
Output directory
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
t_steady: None or float
Time to consider the model to be at steady-state.
`None` means just consider the latest time.
Returns
-------
measure: numpy.ndarray
Measure.
measure_errs: numpy.ndarray
Measure uncertainty.
If no averaging is done, this is taken from the measure_func.
Otherwise, the standard error over all samples is used.
|
[
"Calculate",
"a",
"measure",
"of",
"a",
"model",
"in",
"an",
"output",
"directory",
"averaged",
"over",
"all",
"times",
"when",
"the",
"model",
"is",
"at",
"steady",
"-",
"state",
"."
] |
b2feb45d6129d749088c70b3e9290af7ca7c7d33
|
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L9-L42
|
246,211 |
eddiejessup/agaro
|
agaro/measure_utils.py
|
measures
|
def measures(dirnames, measure_func, t_steady=None):
"""Calculate a measure of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
t_steady: None or float
Time to consider the model to be at steady-state.
The measure will be averaged over all later times.
`None` means just consider the latest time.
Returns
-------
measures: numpy.ndarray
Measures.
measure_errs: numpy.ndarray
Uncertainties.
"""
measures, measure_errs = [], []
for dirname in dirnames:
meas, meas_err = get_average_measure(dirname, measure_func, t_steady)
measures.append(meas)
measure_errs.append(meas_err)
return np.array(measures), np.array(measure_errs)
|
python
|
def measures(dirnames, measure_func, t_steady=None):
"""Calculate a measure of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
t_steady: None or float
Time to consider the model to be at steady-state.
The measure will be averaged over all later times.
`None` means just consider the latest time.
Returns
-------
measures: numpy.ndarray
Measures.
measure_errs: numpy.ndarray
Uncertainties.
"""
measures, measure_errs = [], []
for dirname in dirnames:
meas, meas_err = get_average_measure(dirname, measure_func, t_steady)
measures.append(meas)
measure_errs.append(meas_err)
return np.array(measures), np.array(measure_errs)
|
[
"def",
"measures",
"(",
"dirnames",
",",
"measure_func",
",",
"t_steady",
"=",
"None",
")",
":",
"measures",
",",
"measure_errs",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"dirname",
"in",
"dirnames",
":",
"meas",
",",
"meas_err",
"=",
"get_average_measure",
"(",
"dirname",
",",
"measure_func",
",",
"t_steady",
")",
"measures",
".",
"append",
"(",
"meas",
")",
"measure_errs",
".",
"append",
"(",
"meas_err",
")",
"return",
"np",
".",
"array",
"(",
"measures",
")",
",",
"np",
".",
"array",
"(",
"measure_errs",
")"
] |
Calculate a measure of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
t_steady: None or float
Time to consider the model to be at steady-state.
The measure will be averaged over all later times.
`None` means just consider the latest time.
Returns
-------
measures: numpy.ndarray
Measures.
measure_errs: numpy.ndarray
Uncertainties.
|
[
"Calculate",
"a",
"measure",
"of",
"a",
"set",
"of",
"model",
"output",
"directories",
"for",
"a",
"measure",
"function",
"which",
"returns",
"an",
"associated",
"uncertainty",
"."
] |
b2feb45d6129d749088c70b3e9290af7ca7c7d33
|
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L45-L73
|
246,212 |
eddiejessup/agaro
|
agaro/measure_utils.py
|
params
|
def params(dirnames, param_func, t_steady=None):
"""Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the parameter of interest.
Returns
-------
params: numpy.ndarray
Parameters.
"""
return np.array([param_func(get_recent_model(d)) for d in dirnames])
|
python
|
def params(dirnames, param_func, t_steady=None):
"""Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the parameter of interest.
Returns
-------
params: numpy.ndarray
Parameters.
"""
return np.array([param_func(get_recent_model(d)) for d in dirnames])
|
[
"def",
"params",
"(",
"dirnames",
",",
"param_func",
",",
"t_steady",
"=",
"None",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"param_func",
"(",
"get_recent_model",
"(",
"d",
")",
")",
"for",
"d",
"in",
"dirnames",
"]",
")"
] |
Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the parameter of interest.
Returns
-------
params: numpy.ndarray
Parameters.
|
[
"Calculate",
"a",
"parameter",
"of",
"a",
"set",
"of",
"model",
"output",
"directories",
"for",
"a",
"measure",
"function",
"which",
"returns",
"an",
"associated",
"uncertainty",
"."
] |
b2feb45d6129d749088c70b3e9290af7ca7c7d33
|
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L76-L93
|
246,213 |
eddiejessup/agaro
|
agaro/measure_utils.py
|
t_measures
|
def t_measures(dirname, time_func, measure_func):
"""Calculate a measure over time for a single output directory,
and its uncertainty.
Parameters
----------
dirname: str
Path to a model output directory.
time_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns its time.
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
Returns
-------
ts: np.ndarray
Times.
measures: np.ndarray
Measures.
measure_errs: np.ndarray
Measure uncertainties.
"""
ts, measures, measure_errs = [], [], []
for fname in get_filenames(dirname):
m = filename_to_model(fname)
ts.append(time_func(m))
meas, meas_err = measure_func(m)
measures.append(meas)
measure_errs.append(meas_err)
return np.array(ts), np.array(measures), np.array(measure_errs)
|
python
|
def t_measures(dirname, time_func, measure_func):
"""Calculate a measure over time for a single output directory,
and its uncertainty.
Parameters
----------
dirname: str
Path to a model output directory.
time_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns its time.
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
Returns
-------
ts: np.ndarray
Times.
measures: np.ndarray
Measures.
measure_errs: np.ndarray
Measure uncertainties.
"""
ts, measures, measure_errs = [], [], []
for fname in get_filenames(dirname):
m = filename_to_model(fname)
ts.append(time_func(m))
meas, meas_err = measure_func(m)
measures.append(meas)
measure_errs.append(meas_err)
return np.array(ts), np.array(measures), np.array(measure_errs)
|
[
"def",
"t_measures",
"(",
"dirname",
",",
"time_func",
",",
"measure_func",
")",
":",
"ts",
",",
"measures",
",",
"measure_errs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"fname",
"in",
"get_filenames",
"(",
"dirname",
")",
":",
"m",
"=",
"filename_to_model",
"(",
"fname",
")",
"ts",
".",
"append",
"(",
"time_func",
"(",
"m",
")",
")",
"meas",
",",
"meas_err",
"=",
"measure_func",
"(",
"m",
")",
"measures",
".",
"append",
"(",
"meas",
")",
"measure_errs",
".",
"append",
"(",
"meas_err",
")",
"return",
"np",
".",
"array",
"(",
"ts",
")",
",",
"np",
".",
"array",
"(",
"measures",
")",
",",
"np",
".",
"array",
"(",
"measure_errs",
")"
] |
Calculate a measure over time for a single output directory,
and its uncertainty.
Parameters
----------
dirname: str
Path to a model output directory.
time_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns its time.
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the measure of interest, and its uncertainty.
Returns
-------
ts: np.ndarray
Times.
measures: np.ndarray
Measures.
measure_errs: np.ndarray
Measure uncertainties.
|
[
"Calculate",
"a",
"measure",
"over",
"time",
"for",
"a",
"single",
"output",
"directory",
"and",
"its",
"uncertainty",
"."
] |
b2feb45d6129d749088c70b3e9290af7ca7c7d33
|
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L96-L127
|
246,214 |
eddiejessup/agaro
|
agaro/measure_utils.py
|
group_by_key
|
def group_by_key(dirnames, key):
"""Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
For each value of `key` that is found at least once in the models, a
list of the output directories where `key` is that value.
"""
groups = defaultdict(lambda: [])
for dirname in dirnames:
m = get_recent_model(dirname)
groups[m.__dict__[key]].append(dirname)
return dict(groups)
|
python
|
def group_by_key(dirnames, key):
"""Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
For each value of `key` that is found at least once in the models, a
list of the output directories where `key` is that value.
"""
groups = defaultdict(lambda: [])
for dirname in dirnames:
m = get_recent_model(dirname)
groups[m.__dict__[key]].append(dirname)
return dict(groups)
|
[
"def",
"group_by_key",
"(",
"dirnames",
",",
"key",
")",
":",
"groups",
"=",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"for",
"dirname",
"in",
"dirnames",
":",
"m",
"=",
"get_recent_model",
"(",
"dirname",
")",
"groups",
"[",
"m",
".",
"__dict__",
"[",
"key",
"]",
"]",
".",
"append",
"(",
"dirname",
")",
"return",
"dict",
"(",
"groups",
")"
] |
Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
For each value of `key` that is found at least once in the models, a
list of the output directories where `key` is that value.
|
[
"Group",
"a",
"set",
"of",
"output",
"directories",
"according",
"to",
"a",
"model",
"parameter",
"."
] |
b2feb45d6129d749088c70b3e9290af7ca7c7d33
|
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L130-L150
|
246,215 |
limiear/soyprice
|
soyprice/bots/statistic.py
|
VariableRegression.pearson_correlation
|
def pearson_correlation(self):
x, y, dt = self.data
X, Y = np.array(x), np.array(y)
''' Compute Pearson Correlation Coefficient. '''
# Normalise X and Y
X -= X.mean(0)
Y -= Y.mean(0)
# Standardise X and Y
X /= X.std(0)
Y /= Y.std(0)
# Compute mean product
return (np.mean(X*Y) ** 2) * 100
|
python
|
def pearson_correlation(self):
x, y, dt = self.data
X, Y = np.array(x), np.array(y)
''' Compute Pearson Correlation Coefficient. '''
# Normalise X and Y
X -= X.mean(0)
Y -= Y.mean(0)
# Standardise X and Y
X /= X.std(0)
Y /= Y.std(0)
# Compute mean product
return (np.mean(X*Y) ** 2) * 100
|
[
"def",
"pearson_correlation",
"(",
"self",
")",
":",
"x",
",",
"y",
",",
"dt",
"=",
"self",
".",
"data",
"X",
",",
"Y",
"=",
"np",
".",
"array",
"(",
"x",
")",
",",
"np",
".",
"array",
"(",
"y",
")",
"# Normalise X and Y",
"X",
"-=",
"X",
".",
"mean",
"(",
"0",
")",
"Y",
"-=",
"Y",
".",
"mean",
"(",
"0",
")",
"# Standardise X and Y",
"X",
"/=",
"X",
".",
"std",
"(",
"0",
")",
"Y",
"/=",
"Y",
".",
"std",
"(",
"0",
")",
"# Compute mean product",
"return",
"(",
"np",
".",
"mean",
"(",
"X",
"*",
"Y",
")",
"**",
"2",
")",
"*",
"100"
] |
Compute Pearson Correlation Coefficient.
|
[
"Compute",
"Pearson",
"Correlation",
"Coefficient",
"."
] |
b7f8847b1ab4ba7d9e654135321c5598c7d1aeb1
|
https://github.com/limiear/soyprice/blob/b7f8847b1ab4ba7d9e654135321c5598c7d1aeb1/soyprice/bots/statistic.py#L147-L158
|
246,216 |
pjuren/pyokit
|
src/pyokit/io/bedIterators.py
|
intervalTrees
|
def intervalTrees(reffh, scoreType=int, verbose=False):
"""
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file/stream must be BED.
:param scoreType: The data type for scores (the fifth column) in the BED
file.
:param verbose: output progress messages to sys.stderr if True
"""
if type(reffh).__name__ == "str":
fh = open(reffh)
else:
fh = reffh
# load all the regions and split them into lists for each chrom
elements = {}
if verbose and fh != sys.stdin:
totalLines = linesInFile(fh.name)
pind = ProgressIndicator(totalToDo=totalLines,
messagePrefix="completed",
messageSuffix="of loading " + fh.name)
for element in BEDIterator(fh, scoreType=scoreType, verbose=verbose):
if element.chrom not in elements:
elements[element.chrom] = []
elements[element.chrom].append(element)
if verbose and fh != sys.stdin:
pind.done += 1
pind.showProgress()
# create an interval tree for each list
trees = {}
if verbose:
totalLines = len(elements)
pind = ProgressIndicator(totalToDo=totalLines,
messagePrefix="completed",
messageSuffix="of making interval trees")
for chrom in elements:
trees[chrom] = IntervalTree(elements[chrom], openEnded=True)
if verbose:
pind.done += 1
pind.showProgress()
return trees
|
python
|
def intervalTrees(reffh, scoreType=int, verbose=False):
"""
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file/stream must be BED.
:param scoreType: The data type for scores (the fifth column) in the BED
file.
:param verbose: output progress messages to sys.stderr if True
"""
if type(reffh).__name__ == "str":
fh = open(reffh)
else:
fh = reffh
# load all the regions and split them into lists for each chrom
elements = {}
if verbose and fh != sys.stdin:
totalLines = linesInFile(fh.name)
pind = ProgressIndicator(totalToDo=totalLines,
messagePrefix="completed",
messageSuffix="of loading " + fh.name)
for element in BEDIterator(fh, scoreType=scoreType, verbose=verbose):
if element.chrom not in elements:
elements[element.chrom] = []
elements[element.chrom].append(element)
if verbose and fh != sys.stdin:
pind.done += 1
pind.showProgress()
# create an interval tree for each list
trees = {}
if verbose:
totalLines = len(elements)
pind = ProgressIndicator(totalToDo=totalLines,
messagePrefix="completed",
messageSuffix="of making interval trees")
for chrom in elements:
trees[chrom] = IntervalTree(elements[chrom], openEnded=True)
if verbose:
pind.done += 1
pind.showProgress()
return trees
|
[
"def",
"intervalTrees",
"(",
"reffh",
",",
"scoreType",
"=",
"int",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"type",
"(",
"reffh",
")",
".",
"__name__",
"==",
"\"str\"",
":",
"fh",
"=",
"open",
"(",
"reffh",
")",
"else",
":",
"fh",
"=",
"reffh",
"# load all the regions and split them into lists for each chrom",
"elements",
"=",
"{",
"}",
"if",
"verbose",
"and",
"fh",
"!=",
"sys",
".",
"stdin",
":",
"totalLines",
"=",
"linesInFile",
"(",
"fh",
".",
"name",
")",
"pind",
"=",
"ProgressIndicator",
"(",
"totalToDo",
"=",
"totalLines",
",",
"messagePrefix",
"=",
"\"completed\"",
",",
"messageSuffix",
"=",
"\"of loading \"",
"+",
"fh",
".",
"name",
")",
"for",
"element",
"in",
"BEDIterator",
"(",
"fh",
",",
"scoreType",
"=",
"scoreType",
",",
"verbose",
"=",
"verbose",
")",
":",
"if",
"element",
".",
"chrom",
"not",
"in",
"elements",
":",
"elements",
"[",
"element",
".",
"chrom",
"]",
"=",
"[",
"]",
"elements",
"[",
"element",
".",
"chrom",
"]",
".",
"append",
"(",
"element",
")",
"if",
"verbose",
"and",
"fh",
"!=",
"sys",
".",
"stdin",
":",
"pind",
".",
"done",
"+=",
"1",
"pind",
".",
"showProgress",
"(",
")",
"# create an interval tree for each list",
"trees",
"=",
"{",
"}",
"if",
"verbose",
":",
"totalLines",
"=",
"len",
"(",
"elements",
")",
"pind",
"=",
"ProgressIndicator",
"(",
"totalToDo",
"=",
"totalLines",
",",
"messagePrefix",
"=",
"\"completed\"",
",",
"messageSuffix",
"=",
"\"of making interval trees\"",
")",
"for",
"chrom",
"in",
"elements",
":",
"trees",
"[",
"chrom",
"]",
"=",
"IntervalTree",
"(",
"elements",
"[",
"chrom",
"]",
",",
"openEnded",
"=",
"True",
")",
"if",
"verbose",
":",
"pind",
".",
"done",
"+=",
"1",
"pind",
".",
"showProgress",
"(",
")",
"return",
"trees"
] |
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file/stream must be BED.
:param scoreType: The data type for scores (the fifth column) in the BED
file.
:param verbose: output progress messages to sys.stderr if True
|
[
"Build",
"a",
"dictionary",
"of",
"interval",
"trees",
"indexed",
"by",
"chrom",
"from",
"a",
"BED",
"stream",
"or",
"file"
] |
fddae123b5d817daa39496183f19c000d9c3791f
|
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/bedIterators.py#L62-L107
|
246,217 |
pjuren/pyokit
|
src/pyokit/io/bedIterators.py
|
BEDIterator
|
def BEDIterator(filehandle, sortedby=None, verbose=False, scoreType=int,
dropAfter=None):
"""
Get an iterator for a BED file
:param filehandle: this can be either a string, or a stream-like object. In
the former case, it is treated as a filename. The format
of the file/stream must be BED.
:param sortedby: if None, order is not checked.
if == ITERATOR_SORTED_START, elements in file must
be sorted by chrom and start index (an exception
is raised if they are not)
if == ITERATOR_SORTED_END, element must be sorted
by chrom and end index.
:param verbose: if True, output additional progress messages to stderr
:param scoreType: The data type for scores (the fifth column) in the BED
file.
:param dropAfter: an int indicating that any fields after and including this
field should be ignored as they don't conform to the BED
format. By default, None, meaning we use all fields. Index
from zero.
:return: iterator where subsequent calls to next() yield the next BED
element in the stream as a GenomicInterval object.
"""
chromsSeen = set()
prev = None
if type(filehandle).__name__ == "str":
filehandle = open(filehandle)
if verbose:
try:
pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name),
messagePrefix="completed",
messageSuffix="of processing " +
filehandle.name)
except (AttributeError, OSError) as e:
sys.stderr.write("BEDIterator -- warning: " +
"unable to show progress for stream")
verbose = False
for line in filehandle:
if verbose:
pind.done = filehandle.tell()
pind.showProgress()
if line.strip() == "":
continue
try:
e = parseBEDString(line, scoreType, dropAfter=dropAfter)
except GenomicIntervalError as e:
raise BEDError(str(e) + " on line " + line)
# sorting by name?
if ((sortedby == ITERATOR_SORTED_NAME and prev is not None) and
(prev.name > e.name)):
raise BEDError("bed file " + filehandle.name +
" not sorted by element name" +
" found " + e.name + " after " +
prev.name)
# first item
if prev is None:
chromsSeen.add(e.chrom)
# on same chrom as the prev item, make sure order is right
if prev is not None and sortedby is not None and e.chrom == prev.chrom:
if sortedby == ITERATOR_SORTED_START and prev.start > e.start:
raise BEDError("bed file " + filehandle.name +
" not sorted by start index - saw item " +
str(prev) + " before " + str(e))
if sortedby == ITERATOR_SORTED_END and prev.end > e.end:
raise BEDError("bed file " + filehandle.name +
" not sorted by end index - saw item " +
str(prev) + " before " + str(e))
# starting a new chrom.. make sure we haven't already seen it
if prev is not None and prev.chrom != e.chrom:
if (sortedby == ITERATOR_SORTED_START or
sortedby == ITERATOR_SORTED_END or
sortedby == ITERATOR_SORTED_CHROM) and\
(e.chrom in chromsSeen or prev.chrom > e.chrom):
try:
e_fn = filehandle.name
except AttributeError:
e_fn = "UNNAMED STREAM"
raise BEDError("BED file " + e_fn + " not sorted by chrom")
chromsSeen.add(e.chrom)
# all good..
yield e
prev = e
|
python
|
def BEDIterator(filehandle, sortedby=None, verbose=False, scoreType=int,
dropAfter=None):
"""
Get an iterator for a BED file
:param filehandle: this can be either a string, or a stream-like object. In
the former case, it is treated as a filename. The format
of the file/stream must be BED.
:param sortedby: if None, order is not checked.
if == ITERATOR_SORTED_START, elements in file must
be sorted by chrom and start index (an exception
is raised if they are not)
if == ITERATOR_SORTED_END, element must be sorted
by chrom and end index.
:param verbose: if True, output additional progress messages to stderr
:param scoreType: The data type for scores (the fifth column) in the BED
file.
:param dropAfter: an int indicating that any fields after and including this
field should be ignored as they don't conform to the BED
format. By default, None, meaning we use all fields. Index
from zero.
:return: iterator where subsequent calls to next() yield the next BED
element in the stream as a GenomicInterval object.
"""
chromsSeen = set()
prev = None
if type(filehandle).__name__ == "str":
filehandle = open(filehandle)
if verbose:
try:
pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name),
messagePrefix="completed",
messageSuffix="of processing " +
filehandle.name)
except (AttributeError, OSError) as e:
sys.stderr.write("BEDIterator -- warning: " +
"unable to show progress for stream")
verbose = False
for line in filehandle:
if verbose:
pind.done = filehandle.tell()
pind.showProgress()
if line.strip() == "":
continue
try:
e = parseBEDString(line, scoreType, dropAfter=dropAfter)
except GenomicIntervalError as e:
raise BEDError(str(e) + " on line " + line)
# sorting by name?
if ((sortedby == ITERATOR_SORTED_NAME and prev is not None) and
(prev.name > e.name)):
raise BEDError("bed file " + filehandle.name +
" not sorted by element name" +
" found " + e.name + " after " +
prev.name)
# first item
if prev is None:
chromsSeen.add(e.chrom)
# on same chrom as the prev item, make sure order is right
if prev is not None and sortedby is not None and e.chrom == prev.chrom:
if sortedby == ITERATOR_SORTED_START and prev.start > e.start:
raise BEDError("bed file " + filehandle.name +
" not sorted by start index - saw item " +
str(prev) + " before " + str(e))
if sortedby == ITERATOR_SORTED_END and prev.end > e.end:
raise BEDError("bed file " + filehandle.name +
" not sorted by end index - saw item " +
str(prev) + " before " + str(e))
# starting a new chrom.. make sure we haven't already seen it
if prev is not None and prev.chrom != e.chrom:
if (sortedby == ITERATOR_SORTED_START or
sortedby == ITERATOR_SORTED_END or
sortedby == ITERATOR_SORTED_CHROM) and\
(e.chrom in chromsSeen or prev.chrom > e.chrom):
try:
e_fn = filehandle.name
except AttributeError:
e_fn = "UNNAMED STREAM"
raise BEDError("BED file " + e_fn + " not sorted by chrom")
chromsSeen.add(e.chrom)
# all good..
yield e
prev = e
|
[
"def",
"BEDIterator",
"(",
"filehandle",
",",
"sortedby",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"scoreType",
"=",
"int",
",",
"dropAfter",
"=",
"None",
")",
":",
"chromsSeen",
"=",
"set",
"(",
")",
"prev",
"=",
"None",
"if",
"type",
"(",
"filehandle",
")",
".",
"__name__",
"==",
"\"str\"",
":",
"filehandle",
"=",
"open",
"(",
"filehandle",
")",
"if",
"verbose",
":",
"try",
":",
"pind",
"=",
"ProgressIndicator",
"(",
"totalToDo",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filehandle",
".",
"name",
")",
",",
"messagePrefix",
"=",
"\"completed\"",
",",
"messageSuffix",
"=",
"\"of processing \"",
"+",
"filehandle",
".",
"name",
")",
"except",
"(",
"AttributeError",
",",
"OSError",
")",
"as",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"BEDIterator -- warning: \"",
"+",
"\"unable to show progress for stream\"",
")",
"verbose",
"=",
"False",
"for",
"line",
"in",
"filehandle",
":",
"if",
"verbose",
":",
"pind",
".",
"done",
"=",
"filehandle",
".",
"tell",
"(",
")",
"pind",
".",
"showProgress",
"(",
")",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"\"\"",
":",
"continue",
"try",
":",
"e",
"=",
"parseBEDString",
"(",
"line",
",",
"scoreType",
",",
"dropAfter",
"=",
"dropAfter",
")",
"except",
"GenomicIntervalError",
"as",
"e",
":",
"raise",
"BEDError",
"(",
"str",
"(",
"e",
")",
"+",
"\" on line \"",
"+",
"line",
")",
"# sorting by name?",
"if",
"(",
"(",
"sortedby",
"==",
"ITERATOR_SORTED_NAME",
"and",
"prev",
"is",
"not",
"None",
")",
"and",
"(",
"prev",
".",
"name",
">",
"e",
".",
"name",
")",
")",
":",
"raise",
"BEDError",
"(",
"\"bed file \"",
"+",
"filehandle",
".",
"name",
"+",
"\" not sorted by element name\"",
"+",
"\" found \"",
"+",
"e",
".",
"name",
"+",
"\" after \"",
"+",
"prev",
".",
"name",
")",
"# first item",
"if",
"prev",
"is",
"None",
":",
"chromsSeen",
".",
"add",
"(",
"e",
".",
"chrom",
")",
"# on same chrom as the prev item, make sure order is right",
"if",
"prev",
"is",
"not",
"None",
"and",
"sortedby",
"is",
"not",
"None",
"and",
"e",
".",
"chrom",
"==",
"prev",
".",
"chrom",
":",
"if",
"sortedby",
"==",
"ITERATOR_SORTED_START",
"and",
"prev",
".",
"start",
">",
"e",
".",
"start",
":",
"raise",
"BEDError",
"(",
"\"bed file \"",
"+",
"filehandle",
".",
"name",
"+",
"\" not sorted by start index - saw item \"",
"+",
"str",
"(",
"prev",
")",
"+",
"\" before \"",
"+",
"str",
"(",
"e",
")",
")",
"if",
"sortedby",
"==",
"ITERATOR_SORTED_END",
"and",
"prev",
".",
"end",
">",
"e",
".",
"end",
":",
"raise",
"BEDError",
"(",
"\"bed file \"",
"+",
"filehandle",
".",
"name",
"+",
"\" not sorted by end index - saw item \"",
"+",
"str",
"(",
"prev",
")",
"+",
"\" before \"",
"+",
"str",
"(",
"e",
")",
")",
"# starting a new chrom.. make sure we haven't already seen it",
"if",
"prev",
"is",
"not",
"None",
"and",
"prev",
".",
"chrom",
"!=",
"e",
".",
"chrom",
":",
"if",
"(",
"sortedby",
"==",
"ITERATOR_SORTED_START",
"or",
"sortedby",
"==",
"ITERATOR_SORTED_END",
"or",
"sortedby",
"==",
"ITERATOR_SORTED_CHROM",
")",
"and",
"(",
"e",
".",
"chrom",
"in",
"chromsSeen",
"or",
"prev",
".",
"chrom",
">",
"e",
".",
"chrom",
")",
":",
"try",
":",
"e_fn",
"=",
"filehandle",
".",
"name",
"except",
"AttributeError",
":",
"e_fn",
"=",
"\"UNNAMED STREAM\"",
"raise",
"BEDError",
"(",
"\"BED file \"",
"+",
"e_fn",
"+",
"\" not sorted by chrom\"",
")",
"chromsSeen",
".",
"add",
"(",
"e",
".",
"chrom",
")",
"# all good..",
"yield",
"e",
"prev",
"=",
"e"
] |
Get an iterator for a BED file
:param filehandle: this can be either a string, or a stream-like object. In
the former case, it is treated as a filename. The format
of the file/stream must be BED.
:param sortedby: if None, order is not checked.
if == ITERATOR_SORTED_START, elements in file must
be sorted by chrom and start index (an exception
is raised if they are not)
if == ITERATOR_SORTED_END, element must be sorted
by chrom and end index.
:param verbose: if True, output additional progress messages to stderr
:param scoreType: The data type for scores (the fifth column) in the BED
file.
:param dropAfter: an int indicating that any fields after and including this
field should be ignored as they don't conform to the BED
format. By default, None, meaning we use all fields. Index
from zero.
:return: iterator where subsequent calls to next() yield the next BED
element in the stream as a GenomicInterval object.
|
[
"Get",
"an",
"iterator",
"for",
"a",
"BED",
"file"
] |
fddae123b5d817daa39496183f19c000d9c3791f
|
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/bedIterators.py#L114-L204
|
246,218 |
tBaxter/django-fretboard
|
fretboard/signals.py
|
update_forum_votes
|
def update_forum_votes(sender, **kwargs):
"""
When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property
"""
vote = kwargs['instance']
if vote.content_type.app_label != "fretboard":
return
if vote.content_type.model == "topic":
t = get_model('fretboard', 'Topic').objects.get(id=vote.object.id)
t.votes = t.score()
t.save(update_fields=['votes'])
elif vote.content_type.model == "post":
p = get_model('fretboard', 'Post').objects.get(id=vote.object.id)
p.votes = p.score()
p.save(update_fields=['votes'])
|
python
|
def update_forum_votes(sender, **kwargs):
"""
When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property
"""
vote = kwargs['instance']
if vote.content_type.app_label != "fretboard":
return
if vote.content_type.model == "topic":
t = get_model('fretboard', 'Topic').objects.get(id=vote.object.id)
t.votes = t.score()
t.save(update_fields=['votes'])
elif vote.content_type.model == "post":
p = get_model('fretboard', 'Post').objects.get(id=vote.object.id)
p.votes = p.score()
p.save(update_fields=['votes'])
|
[
"def",
"update_forum_votes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"vote",
"=",
"kwargs",
"[",
"'instance'",
"]",
"if",
"vote",
".",
"content_type",
".",
"app_label",
"!=",
"\"fretboard\"",
":",
"return",
"if",
"vote",
".",
"content_type",
".",
"model",
"==",
"\"topic\"",
":",
"t",
"=",
"get_model",
"(",
"'fretboard'",
",",
"'Topic'",
")",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"vote",
".",
"object",
".",
"id",
")",
"t",
".",
"votes",
"=",
"t",
".",
"score",
"(",
")",
"t",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'votes'",
"]",
")",
"elif",
"vote",
".",
"content_type",
".",
"model",
"==",
"\"post\"",
":",
"p",
"=",
"get_model",
"(",
"'fretboard'",
",",
"'Post'",
")",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"vote",
".",
"object",
".",
"id",
")",
"p",
".",
"votes",
"=",
"p",
".",
"score",
"(",
")",
"p",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'votes'",
"]",
")"
] |
When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property
|
[
"When",
"a",
"Vote",
"is",
"added",
"re",
"-",
"saves",
"the",
"topic",
"or",
"post",
"to",
"update",
"vote",
"count",
".",
"Since",
"Votes",
"can",
"be",
"assigned",
"to",
"any",
"content",
"type",
"first",
"makes",
"sure",
"we",
"are",
"dealing",
"with",
"a",
"forum",
"post",
"or",
"topic",
".",
"Deprecated",
"1",
"-",
"6",
"-",
"14",
"by",
"storing",
"score",
"as",
"cached",
"property"
] |
3c3f9557089821283f315a07f3e5a57a2725ab3b
|
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/signals.py#L7-L25
|
246,219 |
cirruscluster/cirruscluster
|
cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py
|
Connection.close
|
def close(self):
''' terminate the connection '''
cache_key = self._cache_key()
SSH_CONNECTION_CACHE.pop(cache_key, None)
SFTP_CONNECTION_CACHE.pop(cache_key, None)
if self.sftp is not None:
self.sftp.close()
self.ssh.close()
|
python
|
def close(self):
''' terminate the connection '''
cache_key = self._cache_key()
SSH_CONNECTION_CACHE.pop(cache_key, None)
SFTP_CONNECTION_CACHE.pop(cache_key, None)
if self.sftp is not None:
self.sftp.close()
self.ssh.close()
|
[
"def",
"close",
"(",
"self",
")",
":",
"cache_key",
"=",
"self",
".",
"_cache_key",
"(",
")",
"SSH_CONNECTION_CACHE",
".",
"pop",
"(",
"cache_key",
",",
"None",
")",
"SFTP_CONNECTION_CACHE",
".",
"pop",
"(",
"cache_key",
",",
"None",
")",
"if",
"self",
".",
"sftp",
"is",
"not",
"None",
":",
"self",
".",
"sftp",
".",
"close",
"(",
")",
"self",
".",
"ssh",
".",
"close",
"(",
")"
] |
terminate the connection
|
[
"terminate",
"the",
"connection"
] |
977409929dd81322d886425cdced10608117d5d7
|
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L190-L197
|
246,220 |
thomas-maurice/clifactory
|
clifactory/clifactory.py
|
CommandLineInterface.parse
|
def parse(self, line=None):
"""parses the line provided, if None then uses sys.argv"""
args = self.parser.parse_args(args=line)
return args.func(args)
|
python
|
def parse(self, line=None):
"""parses the line provided, if None then uses sys.argv"""
args = self.parser.parse_args(args=line)
return args.func(args)
|
[
"def",
"parse",
"(",
"self",
",",
"line",
"=",
"None",
")",
":",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"line",
")",
"return",
"args",
".",
"func",
"(",
"args",
")"
] |
parses the line provided, if None then uses sys.argv
|
[
"parses",
"the",
"line",
"provided",
"if",
"None",
"then",
"uses",
"sys",
".",
"argv"
] |
b0649e3fe8901a3de7a3e3ecf4bf23499f6a87b3
|
https://github.com/thomas-maurice/clifactory/blob/b0649e3fe8901a3de7a3e3ecf4bf23499f6a87b3/clifactory/clifactory.py#L65-L68
|
246,221 |
openbermuda/ripl
|
ripl/slidelayout.py
|
SlideLayout.vertical_layout
|
def vertical_layout(self, draw, slide):
""" Augment slide with vertical layout info """
padding = self.padding
heading = slide['heading']
width, height = draw.textsize(heading['text'])
top = padding
left = padding
# Calculate size and location of heading
heading.update(dict(
width = width,
height = height,
top = self.padding,
left = self.padding))
top += height + padding
# count how many rows just text and how many have image
rows = slide['rows']
text_rows = 0
image_rows = 0
# calculate size of all text objects
total_height = top
for row in rows:
row_height = 0
images = 0
for item in row['items']:
if item.get('image'):
images += 1
text = item.get('text')
if text is None: continue
width, height = draw.textsize(text)
item.update(dict(
width = width,
height = height))
row_height = max(row_height, height)
if images:
image_rows += 1
row['images'] = images
else:
row['height'] = row_height
text_rows += 1
total_height += row_height + padding
# Calculate average height for image rows
if image_rows:
available = HEIGHT - total_height
image_height = available // image_rows
image_text_offset = image_height // 2
# now spin through rows again setting top
# (and height for images)
for row in rows:
text_top = top
images = row.get('images', 0)
if images:
text_top += image_text_offset
for item in row['items']:
if item.get('text') is not None:
item['top'] = text_top
else:
# image
item['top'] = top
item['height'] = image_height
row['height'] = image_height
top += row.get('height', 0) + padding
return
|
python
|
def vertical_layout(self, draw, slide):
""" Augment slide with vertical layout info """
padding = self.padding
heading = slide['heading']
width, height = draw.textsize(heading['text'])
top = padding
left = padding
# Calculate size and location of heading
heading.update(dict(
width = width,
height = height,
top = self.padding,
left = self.padding))
top += height + padding
# count how many rows just text and how many have image
rows = slide['rows']
text_rows = 0
image_rows = 0
# calculate size of all text objects
total_height = top
for row in rows:
row_height = 0
images = 0
for item in row['items']:
if item.get('image'):
images += 1
text = item.get('text')
if text is None: continue
width, height = draw.textsize(text)
item.update(dict(
width = width,
height = height))
row_height = max(row_height, height)
if images:
image_rows += 1
row['images'] = images
else:
row['height'] = row_height
text_rows += 1
total_height += row_height + padding
# Calculate average height for image rows
if image_rows:
available = HEIGHT - total_height
image_height = available // image_rows
image_text_offset = image_height // 2
# now spin through rows again setting top
# (and height for images)
for row in rows:
text_top = top
images = row.get('images', 0)
if images:
text_top += image_text_offset
for item in row['items']:
if item.get('text') is not None:
item['top'] = text_top
else:
# image
item['top'] = top
item['height'] = image_height
row['height'] = image_height
top += row.get('height', 0) + padding
return
|
[
"def",
"vertical_layout",
"(",
"self",
",",
"draw",
",",
"slide",
")",
":",
"padding",
"=",
"self",
".",
"padding",
"heading",
"=",
"slide",
"[",
"'heading'",
"]",
"width",
",",
"height",
"=",
"draw",
".",
"textsize",
"(",
"heading",
"[",
"'text'",
"]",
")",
"top",
"=",
"padding",
"left",
"=",
"padding",
"# Calculate size and location of heading",
"heading",
".",
"update",
"(",
"dict",
"(",
"width",
"=",
"width",
",",
"height",
"=",
"height",
",",
"top",
"=",
"self",
".",
"padding",
",",
"left",
"=",
"self",
".",
"padding",
")",
")",
"top",
"+=",
"height",
"+",
"padding",
"# count how many rows just text and how many have image",
"rows",
"=",
"slide",
"[",
"'rows'",
"]",
"text_rows",
"=",
"0",
"image_rows",
"=",
"0",
"# calculate size of all text objects",
"total_height",
"=",
"top",
"for",
"row",
"in",
"rows",
":",
"row_height",
"=",
"0",
"images",
"=",
"0",
"for",
"item",
"in",
"row",
"[",
"'items'",
"]",
":",
"if",
"item",
".",
"get",
"(",
"'image'",
")",
":",
"images",
"+=",
"1",
"text",
"=",
"item",
".",
"get",
"(",
"'text'",
")",
"if",
"text",
"is",
"None",
":",
"continue",
"width",
",",
"height",
"=",
"draw",
".",
"textsize",
"(",
"text",
")",
"item",
".",
"update",
"(",
"dict",
"(",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
")",
"row_height",
"=",
"max",
"(",
"row_height",
",",
"height",
")",
"if",
"images",
":",
"image_rows",
"+=",
"1",
"row",
"[",
"'images'",
"]",
"=",
"images",
"else",
":",
"row",
"[",
"'height'",
"]",
"=",
"row_height",
"text_rows",
"+=",
"1",
"total_height",
"+=",
"row_height",
"+",
"padding",
"# Calculate average height for image rows",
"if",
"image_rows",
":",
"available",
"=",
"HEIGHT",
"-",
"total_height",
"image_height",
"=",
"available",
"//",
"image_rows",
"image_text_offset",
"=",
"image_height",
"//",
"2",
"# now spin through rows again setting top",
"# (and height for images)",
"for",
"row",
"in",
"rows",
":",
"text_top",
"=",
"top",
"images",
"=",
"row",
".",
"get",
"(",
"'images'",
",",
"0",
")",
"if",
"images",
":",
"text_top",
"+=",
"image_text_offset",
"for",
"item",
"in",
"row",
"[",
"'items'",
"]",
":",
"if",
"item",
".",
"get",
"(",
"'text'",
")",
"is",
"not",
"None",
":",
"item",
"[",
"'top'",
"]",
"=",
"text_top",
"else",
":",
"# image",
"item",
"[",
"'top'",
"]",
"=",
"top",
"item",
"[",
"'height'",
"]",
"=",
"image_height",
"row",
"[",
"'height'",
"]",
"=",
"image_height",
"top",
"+=",
"row",
".",
"get",
"(",
"'height'",
",",
"0",
")",
"+",
"padding",
"return"
] |
Augment slide with vertical layout info
|
[
"Augment",
"slide",
"with",
"vertical",
"layout",
"info"
] |
4886b1a697e4b81c2202db9cb977609e034f8e70
|
https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/slidelayout.py#L59-L145
|
246,222 |
openbermuda/ripl
|
ripl/slidelayout.py
|
SlideLayout.horizontal_layout
|
def horizontal_layout(self, draw, slide):
""" Augment slide with horizontal layout info """
padding = self.padding
heading = slide['heading']
top = padding
left = padding
top += heading['height'] + padding
rows = slide['rows']
for row in rows:
images = row.get('images', 0)
items = row['items']
used_width = sum(x.get('width', 0) for x in items)
available_width = WIDTH - (
used_width + ((1 + len(items)) * padding))
if images:
image_width = available_width // images
# OK, now set left for all items and image_width for images
left = padding
for item in row['items']:
if item.get('image'):
item['width'] = image_width
item['left'] = left
left += item['width'] + padding
return
|
python
|
def horizontal_layout(self, draw, slide):
""" Augment slide with horizontal layout info """
padding = self.padding
heading = slide['heading']
top = padding
left = padding
top += heading['height'] + padding
rows = slide['rows']
for row in rows:
images = row.get('images', 0)
items = row['items']
used_width = sum(x.get('width', 0) for x in items)
available_width = WIDTH - (
used_width + ((1 + len(items)) * padding))
if images:
image_width = available_width // images
# OK, now set left for all items and image_width for images
left = padding
for item in row['items']:
if item.get('image'):
item['width'] = image_width
item['left'] = left
left += item['width'] + padding
return
|
[
"def",
"horizontal_layout",
"(",
"self",
",",
"draw",
",",
"slide",
")",
":",
"padding",
"=",
"self",
".",
"padding",
"heading",
"=",
"slide",
"[",
"'heading'",
"]",
"top",
"=",
"padding",
"left",
"=",
"padding",
"top",
"+=",
"heading",
"[",
"'height'",
"]",
"+",
"padding",
"rows",
"=",
"slide",
"[",
"'rows'",
"]",
"for",
"row",
"in",
"rows",
":",
"images",
"=",
"row",
".",
"get",
"(",
"'images'",
",",
"0",
")",
"items",
"=",
"row",
"[",
"'items'",
"]",
"used_width",
"=",
"sum",
"(",
"x",
".",
"get",
"(",
"'width'",
",",
"0",
")",
"for",
"x",
"in",
"items",
")",
"available_width",
"=",
"WIDTH",
"-",
"(",
"used_width",
"+",
"(",
"(",
"1",
"+",
"len",
"(",
"items",
")",
")",
"*",
"padding",
")",
")",
"if",
"images",
":",
"image_width",
"=",
"available_width",
"//",
"images",
"# OK, now set left for all items and image_width for images",
"left",
"=",
"padding",
"for",
"item",
"in",
"row",
"[",
"'items'",
"]",
":",
"if",
"item",
".",
"get",
"(",
"'image'",
")",
":",
"item",
"[",
"'width'",
"]",
"=",
"image_width",
"item",
"[",
"'left'",
"]",
"=",
"left",
"left",
"+=",
"item",
"[",
"'width'",
"]",
"+",
"padding",
"return"
] |
Augment slide with horizontal layout info
|
[
"Augment",
"slide",
"with",
"horizontal",
"layout",
"info"
] |
4886b1a697e4b81c2202db9cb977609e034f8e70
|
https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/slidelayout.py#L147-L184
|
246,223 |
tschaume/ccsgp_get_started
|
ccsgp_get_started/examples/gp_xfac.py
|
gp_xfac
|
def gp_xfac():
"""example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&materialId=slides&confId=181055
.. _NSD: http://rnc.lbl.gov/~xdong/RNC/DirectorReview2012/posters/Huck.pdf
.. image:: pics/xfac.png
:width: 450 px
:ivar key: translates filename into legend/key label
:ivar shift: slightly shift selected data points
"""
# prepare data
inDir, outDir = getWorkDirs()
data = OrderedDict()
# TODO: "really" reproduce plot using spectral data
for file in os.listdir(inDir):
info = os.path.splitext(file)[0].split('_')
key = ' '.join(info[:2] + [':',
' - '.join([
str(float(s)/1e3) for s in info[-1][:7].split('-')
]) + ' GeV'
])
file_url = os.path.join(inDir, file)
data[key] = np.loadtxt(open(file_url, 'rb')).reshape((-1,5))
data[key][:, 0] *= shift.get(key, 1)
logging.debug(data) # shown if --log flag given on command line
# generate plot
nSets = len(data)
make_plot(
data = data.values(),
properties = [ getOpts(i) for i in xrange(nSets) ],
titles = data.keys(), # use data keys as legend titles
name = os.path.join(outDir, 'xfac'),
key = [ 'top center', 'maxcols 2', 'width -7', 'font ",20"' ],
ylabel = 'LMR Enhancement Factor',
xlabel = '{/Symbol \326}s_{NN} (GeV)',
yr = [0.5, 6.5], size = '8.5in,8in',
rmargin = 0.99, tmargin = 0.98, bmargin = 0.14,
xlog = True, gpcalls = [
'format x "%g"',
'xtics (20,"" 30, 40,"" 50, 60,"" 70,"" 80,"" 90, 100, 200)',
'boxwidth 0.015 absolute'
],
labels = { 'STAR Preliminary': [0.5, 0.5, False] },
lines = { 'x=1': 'lc 0 lw 4 lt 2' }
)
return 'done'
|
python
|
def gp_xfac():
"""example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&materialId=slides&confId=181055
.. _NSD: http://rnc.lbl.gov/~xdong/RNC/DirectorReview2012/posters/Huck.pdf
.. image:: pics/xfac.png
:width: 450 px
:ivar key: translates filename into legend/key label
:ivar shift: slightly shift selected data points
"""
# prepare data
inDir, outDir = getWorkDirs()
data = OrderedDict()
# TODO: "really" reproduce plot using spectral data
for file in os.listdir(inDir):
info = os.path.splitext(file)[0].split('_')
key = ' '.join(info[:2] + [':',
' - '.join([
str(float(s)/1e3) for s in info[-1][:7].split('-')
]) + ' GeV'
])
file_url = os.path.join(inDir, file)
data[key] = np.loadtxt(open(file_url, 'rb')).reshape((-1,5))
data[key][:, 0] *= shift.get(key, 1)
logging.debug(data) # shown if --log flag given on command line
# generate plot
nSets = len(data)
make_plot(
data = data.values(),
properties = [ getOpts(i) for i in xrange(nSets) ],
titles = data.keys(), # use data keys as legend titles
name = os.path.join(outDir, 'xfac'),
key = [ 'top center', 'maxcols 2', 'width -7', 'font ",20"' ],
ylabel = 'LMR Enhancement Factor',
xlabel = '{/Symbol \326}s_{NN} (GeV)',
yr = [0.5, 6.5], size = '8.5in,8in',
rmargin = 0.99, tmargin = 0.98, bmargin = 0.14,
xlog = True, gpcalls = [
'format x "%g"',
'xtics (20,"" 30, 40,"" 50, 60,"" 70,"" 80,"" 90, 100, 200)',
'boxwidth 0.015 absolute'
],
labels = { 'STAR Preliminary': [0.5, 0.5, False] },
lines = { 'x=1': 'lc 0 lw 4 lt 2' }
)
return 'done'
|
[
"def",
"gp_xfac",
"(",
")",
":",
"# prepare data",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"data",
"=",
"OrderedDict",
"(",
")",
"# TODO: \"really\" reproduce plot using spectral data",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"inDir",
")",
":",
"info",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'_'",
")",
"key",
"=",
"' '",
".",
"join",
"(",
"info",
"[",
":",
"2",
"]",
"+",
"[",
"':'",
",",
"' - '",
".",
"join",
"(",
"[",
"str",
"(",
"float",
"(",
"s",
")",
"/",
"1e3",
")",
"for",
"s",
"in",
"info",
"[",
"-",
"1",
"]",
"[",
":",
"7",
"]",
".",
"split",
"(",
"'-'",
")",
"]",
")",
"+",
"' GeV'",
"]",
")",
"file_url",
"=",
"os",
".",
"path",
".",
"join",
"(",
"inDir",
",",
"file",
")",
"data",
"[",
"key",
"]",
"=",
"np",
".",
"loadtxt",
"(",
"open",
"(",
"file_url",
",",
"'rb'",
")",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"5",
")",
")",
"data",
"[",
"key",
"]",
"[",
":",
",",
"0",
"]",
"*=",
"shift",
".",
"get",
"(",
"key",
",",
"1",
")",
"logging",
".",
"debug",
"(",
"data",
")",
"# shown if --log flag given on command line",
"# generate plot",
"nSets",
"=",
"len",
"(",
"data",
")",
"make_plot",
"(",
"data",
"=",
"data",
".",
"values",
"(",
")",
",",
"properties",
"=",
"[",
"getOpts",
"(",
"i",
")",
"for",
"i",
"in",
"xrange",
"(",
"nSets",
")",
"]",
",",
"titles",
"=",
"data",
".",
"keys",
"(",
")",
",",
"# use data keys as legend titles",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outDir",
",",
"'xfac'",
")",
",",
"key",
"=",
"[",
"'top center'",
",",
"'maxcols 2'",
",",
"'width -7'",
",",
"'font \",20\"'",
"]",
",",
"ylabel",
"=",
"'LMR Enhancement Factor'",
",",
"xlabel",
"=",
"'{/Symbol \\326}s_{NN} (GeV)'",
",",
"yr",
"=",
"[",
"0.5",
",",
"6.5",
"]",
",",
"size",
"=",
"'8.5in,8in'",
",",
"rmargin",
"=",
"0.99",
",",
"tmargin",
"=",
"0.98",
",",
"bmargin",
"=",
"0.14",
",",
"xlog",
"=",
"True",
",",
"gpcalls",
"=",
"[",
"'format x \"%g\"'",
",",
"'xtics (20,\"\" 30, 40,\"\" 50, 60,\"\" 70,\"\" 80,\"\" 90, 100, 200)'",
",",
"'boxwidth 0.015 absolute'",
"]",
",",
"labels",
"=",
"{",
"'STAR Preliminary'",
":",
"[",
"0.5",
",",
"0.5",
",",
"False",
"]",
"}",
",",
"lines",
"=",
"{",
"'x=1'",
":",
"'lc 0 lw 4 lt 2'",
"}",
")",
"return",
"'done'"
] |
example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&materialId=slides&confId=181055
.. _NSD: http://rnc.lbl.gov/~xdong/RNC/DirectorReview2012/posters/Huck.pdf
.. image:: pics/xfac.png
:width: 450 px
:ivar key: translates filename into legend/key label
:ivar shift: slightly shift selected data points
|
[
"example",
"using",
"QM12",
"enhancement",
"factors"
] |
e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2
|
https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_xfac.py#L12-L63
|
246,224 |
ramrod-project/database-brain
|
schema/brain/checks.py
|
verify
|
def verify(value, msg):
"""
C-style validator
Keyword arguments:
value -- dictionary to validate (required)
msg -- the protobuf schema to validate against (required)
Returns:
True: If valid input
False: If invalid input
"""
return bool(value) and \
converts_to_proto(value, msg) and \
successfuly_encodes(msg) and \
special_typechecking(value, msg)
|
python
|
def verify(value, msg):
"""
C-style validator
Keyword arguments:
value -- dictionary to validate (required)
msg -- the protobuf schema to validate against (required)
Returns:
True: If valid input
False: If invalid input
"""
return bool(value) and \
converts_to_proto(value, msg) and \
successfuly_encodes(msg) and \
special_typechecking(value, msg)
|
[
"def",
"verify",
"(",
"value",
",",
"msg",
")",
":",
"return",
"bool",
"(",
"value",
")",
"and",
"converts_to_proto",
"(",
"value",
",",
"msg",
")",
"and",
"successfuly_encodes",
"(",
"msg",
")",
"and",
"special_typechecking",
"(",
"value",
",",
"msg",
")"
] |
C-style validator
Keyword arguments:
value -- dictionary to validate (required)
msg -- the protobuf schema to validate against (required)
Returns:
True: If valid input
False: If invalid input
|
[
"C",
"-",
"style",
"validator"
] |
b024cb44f34cabb9d80af38271ddb65c25767083
|
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L13-L28
|
246,225 |
ramrod-project/database-brain
|
schema/brain/checks.py
|
converts_to_proto
|
def converts_to_proto(value, msg, raise_err=False):
"""
Boolean response if a dictionary can convert into the proto's schema
:param value: <dict>
:param msg: <proto object>
:param raise_err: <bool> (default false) raise for troubleshooting
:return: <bool> whether the dict can covert
"""
result = True
try:
dict_to_protobuf.dict_to_protobuf(value, msg)
except TypeError as type_error:
if raise_err:
raise type_error
result = False
return result
|
python
|
def converts_to_proto(value, msg, raise_err=False):
"""
Boolean response if a dictionary can convert into the proto's schema
:param value: <dict>
:param msg: <proto object>
:param raise_err: <bool> (default false) raise for troubleshooting
:return: <bool> whether the dict can covert
"""
result = True
try:
dict_to_protobuf.dict_to_protobuf(value, msg)
except TypeError as type_error:
if raise_err:
raise type_error
result = False
return result
|
[
"def",
"converts_to_proto",
"(",
"value",
",",
"msg",
",",
"raise_err",
"=",
"False",
")",
":",
"result",
"=",
"True",
"try",
":",
"dict_to_protobuf",
".",
"dict_to_protobuf",
"(",
"value",
",",
"msg",
")",
"except",
"TypeError",
"as",
"type_error",
":",
"if",
"raise_err",
":",
"raise",
"type_error",
"result",
"=",
"False",
"return",
"result"
] |
Boolean response if a dictionary can convert into the proto's schema
:param value: <dict>
:param msg: <proto object>
:param raise_err: <bool> (default false) raise for troubleshooting
:return: <bool> whether the dict can covert
|
[
"Boolean",
"response",
"if",
"a",
"dictionary",
"can",
"convert",
"into",
"the",
"proto",
"s",
"schema"
] |
b024cb44f34cabb9d80af38271ddb65c25767083
|
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L67-L83
|
246,226 |
ramrod-project/database-brain
|
schema/brain/checks.py
|
successfuly_encodes
|
def successfuly_encodes(msg, raise_err=False):
"""
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
"""
result = True
try:
msg.SerializeToString()
except EncodeError as encode_error:
if raise_err:
raise encode_error
result = False
return result
|
python
|
def successfuly_encodes(msg, raise_err=False):
"""
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
"""
result = True
try:
msg.SerializeToString()
except EncodeError as encode_error:
if raise_err:
raise encode_error
result = False
return result
|
[
"def",
"successfuly_encodes",
"(",
"msg",
",",
"raise_err",
"=",
"False",
")",
":",
"result",
"=",
"True",
"try",
":",
"msg",
".",
"SerializeToString",
"(",
")",
"except",
"EncodeError",
"as",
"encode_error",
":",
"if",
"raise_err",
":",
"raise",
"encode_error",
"result",
"=",
"False",
"return",
"result"
] |
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
|
[
"boolean",
"response",
"if",
"a",
"message",
"contains",
"correct",
"information",
"to",
"serialize"
] |
b024cb44f34cabb9d80af38271ddb65c25767083
|
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L86-L101
|
246,227 |
ramrod-project/database-brain
|
schema/brain/checks.py
|
strip
|
def strip(value, msg):
"""
Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict> with keys defined by msg, omits any other key
"""
dict_to_protobuf.dict_to_protobuf(value, msg)
try:
msg.SerializeToString() #raise error for insufficient input
except EncodeError as encode_error:
raise ValueError(str(encode_error))
output = dict_to_protobuf.protobuf_to_dict(msg)
return output
|
python
|
def strip(value, msg):
"""
Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict> with keys defined by msg, omits any other key
"""
dict_to_protobuf.dict_to_protobuf(value, msg)
try:
msg.SerializeToString() #raise error for insufficient input
except EncodeError as encode_error:
raise ValueError(str(encode_error))
output = dict_to_protobuf.protobuf_to_dict(msg)
return output
|
[
"def",
"strip",
"(",
"value",
",",
"msg",
")",
":",
"dict_to_protobuf",
".",
"dict_to_protobuf",
"(",
"value",
",",
"msg",
")",
"try",
":",
"msg",
".",
"SerializeToString",
"(",
")",
"#raise error for insufficient input",
"except",
"EncodeError",
"as",
"encode_error",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"encode_error",
")",
")",
"output",
"=",
"dict_to_protobuf",
".",
"protobuf_to_dict",
"(",
"msg",
")",
"return",
"output"
] |
Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict> with keys defined by msg, omits any other key
|
[
"Strips",
"all",
"non",
"-",
"essential",
"keys",
"from",
"the",
"value",
"dictionary",
"given",
"the",
"message",
"format",
"protobuf"
] |
b024cb44f34cabb9d80af38271ddb65c25767083
|
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L104-L121
|
246,228 |
ulf1/oxyba
|
oxyba/clean_german_number.py
|
clean_german_number
|
def clean_german_number(x):
"""Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string or array of strings that can be converted
to a numeric data type (e.g. Decimal, float, int).
Example
-------
The function aims to convert a string as follows
'1.234' => '1234'
'1234' => '1234'
'1.234,56' => '1234.56'
'1.234.560' => '1234560'
'+123' => '123'
'-123' => '-123'
Code Example
------------
print(clean_german_number('1.234,56'))
'1234.56'
Behavior
--------
- The function will return None if the element is not a string
- The function assumes that provided string are German numbers.
- There will NO check if it is a regular number.
- No conversion to a numeric data type (have to be done afterwards)
Notes
-----
The command `x.dropna().apply(proc_elem)` is not working for
pandas dataframes. Maybe the `proc_elem` sub function is too big
or complex for pandas' apply method.
"""
import numpy as np
import pandas as pd
import re
def proc_elem(e):
# abort if it is not a string
if not isinstance(e, str):
return None
# strip all char except digits, ".", "," and "-"
s = re.sub('[^0-9\.\,\-]+', '', e)
# abort if nothing is left
if len(s) is 0:
return None
# extra check regarding "-" modifier
m = ""
if s[0] is "-":
if len(s) > 1:
m = "-"
s = s[1:]
else:
return None
# remove the "-" from the string
s = re.sub('[^0-9\.\,]+', '', s)
# abort if nothing is left
if len(s) is 0:
return None
# abort if the number of "," (decimal sep) is bigger than 1
if s.count(',') > 1:
return None
# about if the decimal sep "," occurs before a 000' sep "."
if s.count('.') > 0 and s.count(',') > 0:
rev = s[::-1]
if rev.find(",") > rev.find("."):
return None
# remove 000' seperators "."
s = s.replace('.', '')
# convert comma to dot
s = s.replace(',', '.')
# if just a dot is left "."
if s == ".":
return None
# reattach the "-" modifier
return m + s
def proc_list(x):
return [proc_elem(e) for e in x]
def proc_ndarray(x):
tmp = proc_list(list(x.reshape((x.size,))))
return np.array(tmp).reshape(x.shape)
# transform string, list/tuple, numpy array, pandas dataframe
if isinstance(x, str):
return proc_elem(x)
elif isinstance(x, (list, tuple)):
return proc_list(x)
elif isinstance(x, np.ndarray):
return proc_ndarray(x)
elif isinstance(x, pd.DataFrame):
return pd.DataFrame(proc_ndarray(x.values),
columns=x.columns, index=x.index)
else:
return None
|
python
|
def clean_german_number(x):
"""Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string or array of strings that can be converted
to a numeric data type (e.g. Decimal, float, int).
Example
-------
The function aims to convert a string as follows
'1.234' => '1234'
'1234' => '1234'
'1.234,56' => '1234.56'
'1.234.560' => '1234560'
'+123' => '123'
'-123' => '-123'
Code Example
------------
print(clean_german_number('1.234,56'))
'1234.56'
Behavior
--------
- The function will return None if the element is not a string
- The function assumes that provided string are German numbers.
- There will NO check if it is a regular number.
- No conversion to a numeric data type (have to be done afterwards)
Notes
-----
The command `x.dropna().apply(proc_elem)` is not working for
pandas dataframes. Maybe the `proc_elem` sub function is too big
or complex for pandas' apply method.
"""
import numpy as np
import pandas as pd
import re
def proc_elem(e):
# abort if it is not a string
if not isinstance(e, str):
return None
# strip all char except digits, ".", "," and "-"
s = re.sub('[^0-9\.\,\-]+', '', e)
# abort if nothing is left
if len(s) is 0:
return None
# extra check regarding "-" modifier
m = ""
if s[0] is "-":
if len(s) > 1:
m = "-"
s = s[1:]
else:
return None
# remove the "-" from the string
s = re.sub('[^0-9\.\,]+', '', s)
# abort if nothing is left
if len(s) is 0:
return None
# abort if the number of "," (decimal sep) is bigger than 1
if s.count(',') > 1:
return None
# about if the decimal sep "," occurs before a 000' sep "."
if s.count('.') > 0 and s.count(',') > 0:
rev = s[::-1]
if rev.find(",") > rev.find("."):
return None
# remove 000' seperators "."
s = s.replace('.', '')
# convert comma to dot
s = s.replace(',', '.')
# if just a dot is left "."
if s == ".":
return None
# reattach the "-" modifier
return m + s
def proc_list(x):
return [proc_elem(e) for e in x]
def proc_ndarray(x):
tmp = proc_list(list(x.reshape((x.size,))))
return np.array(tmp).reshape(x.shape)
# transform string, list/tuple, numpy array, pandas dataframe
if isinstance(x, str):
return proc_elem(x)
elif isinstance(x, (list, tuple)):
return proc_list(x)
elif isinstance(x, np.ndarray):
return proc_ndarray(x)
elif isinstance(x, pd.DataFrame):
return pd.DataFrame(proc_ndarray(x.values),
columns=x.columns, index=x.index)
else:
return None
|
[
"def",
"clean_german_number",
"(",
"x",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"import",
"re",
"def",
"proc_elem",
"(",
"e",
")",
":",
"# abort if it is not a string",
"if",
"not",
"isinstance",
"(",
"e",
",",
"str",
")",
":",
"return",
"None",
"# strip all char except digits, \".\", \",\" and \"-\"",
"s",
"=",
"re",
".",
"sub",
"(",
"'[^0-9\\.\\,\\-]+'",
",",
"''",
",",
"e",
")",
"# abort if nothing is left",
"if",
"len",
"(",
"s",
")",
"is",
"0",
":",
"return",
"None",
"# extra check regarding \"-\" modifier",
"m",
"=",
"\"\"",
"if",
"s",
"[",
"0",
"]",
"is",
"\"-\"",
":",
"if",
"len",
"(",
"s",
")",
">",
"1",
":",
"m",
"=",
"\"-\"",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"else",
":",
"return",
"None",
"# remove the \"-\" from the string",
"s",
"=",
"re",
".",
"sub",
"(",
"'[^0-9\\.\\,]+'",
",",
"''",
",",
"s",
")",
"# abort if nothing is left",
"if",
"len",
"(",
"s",
")",
"is",
"0",
":",
"return",
"None",
"# abort if the number of \",\" (decimal sep) is bigger than 1",
"if",
"s",
".",
"count",
"(",
"','",
")",
">",
"1",
":",
"return",
"None",
"# about if the decimal sep \",\" occurs before a 000' sep \".\"",
"if",
"s",
".",
"count",
"(",
"'.'",
")",
">",
"0",
"and",
"s",
".",
"count",
"(",
"','",
")",
">",
"0",
":",
"rev",
"=",
"s",
"[",
":",
":",
"-",
"1",
"]",
"if",
"rev",
".",
"find",
"(",
"\",\"",
")",
">",
"rev",
".",
"find",
"(",
"\".\"",
")",
":",
"return",
"None",
"# remove 000' seperators \".\"",
"s",
"=",
"s",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"# convert comma to dot",
"s",
"=",
"s",
".",
"replace",
"(",
"','",
",",
"'.'",
")",
"# if just a dot is left \".\"",
"if",
"s",
"==",
"\".\"",
":",
"return",
"None",
"# reattach the \"-\" modifier",
"return",
"m",
"+",
"s",
"def",
"proc_list",
"(",
"x",
")",
":",
"return",
"[",
"proc_elem",
"(",
"e",
")",
"for",
"e",
"in",
"x",
"]",
"def",
"proc_ndarray",
"(",
"x",
")",
":",
"tmp",
"=",
"proc_list",
"(",
"list",
"(",
"x",
".",
"reshape",
"(",
"(",
"x",
".",
"size",
",",
")",
")",
")",
")",
"return",
"np",
".",
"array",
"(",
"tmp",
")",
".",
"reshape",
"(",
"x",
".",
"shape",
")",
"# transform string, list/tuple, numpy array, pandas dataframe",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"proc_elem",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"proc_list",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"proc_ndarray",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"pd",
".",
"DataFrame",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"proc_ndarray",
"(",
"x",
".",
"values",
")",
",",
"columns",
"=",
"x",
".",
"columns",
",",
"index",
"=",
"x",
".",
"index",
")",
"else",
":",
"return",
"None"
] |
Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string or array of strings that can be converted
to a numeric data type (e.g. Decimal, float, int).
Example
-------
The function aims to convert a string as follows
'1.234' => '1234'
'1234' => '1234'
'1.234,56' => '1234.56'
'1.234.560' => '1234560'
'+123' => '123'
'-123' => '-123'
Code Example
------------
print(clean_german_number('1.234,56'))
'1234.56'
Behavior
--------
- The function will return None if the element is not a string
- The function assumes that provided string are German numbers.
- There will NO check if it is a regular number.
- No conversion to a numeric data type (have to be done afterwards)
Notes
-----
The command `x.dropna().apply(proc_elem)` is not working for
pandas dataframes. Maybe the `proc_elem` sub function is too big
or complex for pandas' apply method.
|
[
"Convert",
"a",
"string",
"with",
"a",
"German",
"number",
"into",
"a",
"Decimal"
] |
b3043116050de275124365cb11e7df91fb40169d
|
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_german_number.py#L2-L121
|
246,229 |
dustinmm80/healthy
|
pylint_runner.py
|
score
|
def score(package_path):
"""
Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score
"""
python_files = find_files(package_path, '*.py')
total_counter = Counter()
for python_file in python_files:
output = run_pylint(python_file)
counter = parse_pylint_output(output)
total_counter += counter
score_value = 0
for count, stat in enumerate(total_counter):
score_value += SCORING_VALUES[stat] * count
return score_value / 5
|
python
|
def score(package_path):
"""
Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score
"""
python_files = find_files(package_path, '*.py')
total_counter = Counter()
for python_file in python_files:
output = run_pylint(python_file)
counter = parse_pylint_output(output)
total_counter += counter
score_value = 0
for count, stat in enumerate(total_counter):
score_value += SCORING_VALUES[stat] * count
return score_value / 5
|
[
"def",
"score",
"(",
"package_path",
")",
":",
"python_files",
"=",
"find_files",
"(",
"package_path",
",",
"'*.py'",
")",
"total_counter",
"=",
"Counter",
"(",
")",
"for",
"python_file",
"in",
"python_files",
":",
"output",
"=",
"run_pylint",
"(",
"python_file",
")",
"counter",
"=",
"parse_pylint_output",
"(",
"output",
")",
"total_counter",
"+=",
"counter",
"score_value",
"=",
"0",
"for",
"count",
",",
"stat",
"in",
"enumerate",
"(",
"total_counter",
")",
":",
"score_value",
"+=",
"SCORING_VALUES",
"[",
"stat",
"]",
"*",
"count",
"return",
"score_value",
"/",
"5"
] |
Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score
|
[
"Runs",
"pylint",
"on",
"a",
"package",
"and",
"returns",
"a",
"score",
"Lower",
"score",
"is",
"better"
] |
b59016c3f578ca45b6ce857a2d5c4584b8542288
|
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/pylint_runner.py#L22-L44
|
246,230 |
patchboard/patchboard-py
|
patchboard/base.py
|
discover
|
def discover(url, options={}):
"""
Retrieve the API definition from the given URL and construct
a Patchboard to interface with it.
"""
try:
resp = requests.get(url, headers=Patchboard.default_headers)
except Exception as e:
raise PatchboardError("Problem discovering API: {0}".format(e))
# Parse as JSON (Requests uses json.loads())
try:
api_spec = resp.json()
except ValueError as e:
raise PatchboardError("Unparseable API description: {0}".format(e))
# Return core handle object
return Patchboard(api_spec, options)
|
python
|
def discover(url, options={}):
"""
Retrieve the API definition from the given URL and construct
a Patchboard to interface with it.
"""
try:
resp = requests.get(url, headers=Patchboard.default_headers)
except Exception as e:
raise PatchboardError("Problem discovering API: {0}".format(e))
# Parse as JSON (Requests uses json.loads())
try:
api_spec = resp.json()
except ValueError as e:
raise PatchboardError("Unparseable API description: {0}".format(e))
# Return core handle object
return Patchboard(api_spec, options)
|
[
"def",
"discover",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
":",
"try",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"Patchboard",
".",
"default_headers",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PatchboardError",
"(",
"\"Problem discovering API: {0}\"",
".",
"format",
"(",
"e",
")",
")",
"# Parse as JSON (Requests uses json.loads())",
"try",
":",
"api_spec",
"=",
"resp",
".",
"json",
"(",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"PatchboardError",
"(",
"\"Unparseable API description: {0}\"",
".",
"format",
"(",
"e",
")",
")",
"# Return core handle object",
"return",
"Patchboard",
"(",
"api_spec",
",",
"options",
")"
] |
Retrieve the API definition from the given URL and construct
a Patchboard to interface with it.
|
[
"Retrieve",
"the",
"API",
"definition",
"from",
"the",
"given",
"URL",
"and",
"construct",
"a",
"Patchboard",
"to",
"interface",
"with",
"it",
"."
] |
3d9f66f3f26d71e769cd3a578b760441a237ce4d
|
https://github.com/patchboard/patchboard-py/blob/3d9f66f3f26d71e769cd3a578b760441a237ce4d/patchboard/base.py#L27-L44
|
246,231 |
patchboard/patchboard-py
|
patchboard/base.py
|
Patchboard.spawn
|
def spawn(self, context=None):
"""
context may be a callable or a dict.
"""
if context is None:
context = self.default_context
if isinstance(context, collections.Callable):
context = context()
if not isinstance(context, collections.Mapping):
raise PatchboardError('Cannot determine a valid context')
return Client(self, context, self.api, self.endpoint_classes)
|
python
|
def spawn(self, context=None):
"""
context may be a callable or a dict.
"""
if context is None:
context = self.default_context
if isinstance(context, collections.Callable):
context = context()
if not isinstance(context, collections.Mapping):
raise PatchboardError('Cannot determine a valid context')
return Client(self, context, self.api, self.endpoint_classes)
|
[
"def",
"spawn",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
".",
"default_context",
"if",
"isinstance",
"(",
"context",
",",
"collections",
".",
"Callable",
")",
":",
"context",
"=",
"context",
"(",
")",
"if",
"not",
"isinstance",
"(",
"context",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"PatchboardError",
"(",
"'Cannot determine a valid context'",
")",
"return",
"Client",
"(",
"self",
",",
"context",
",",
"self",
".",
"api",
",",
"self",
".",
"endpoint_classes",
")"
] |
context may be a callable or a dict.
|
[
"context",
"may",
"be",
"a",
"callable",
"or",
"a",
"dict",
"."
] |
3d9f66f3f26d71e769cd3a578b760441a237ce4d
|
https://github.com/patchboard/patchboard-py/blob/3d9f66f3f26d71e769cd3a578b760441a237ce4d/patchboard/base.py#L114-L127
|
246,232 |
jmatt/threepio
|
threepio/version.py
|
get_version
|
def get_version(form='short'):
"""
Returns the version string.
Takes single argument ``form``, which should be one of the following
strings:
* ``short`` Returns major + minor branch version string with the format of
B.b.t.
* ``normal`` Returns human readable version string with the format of
B.b.t _type type_num.
* ``verbose`` Returns a verbose version string with the format of
B.b.t _type type_num@git_sha
* ``all`` Returns a dict of all versions.
"""
versions = {}
branch = "%s.%s" % (VERSION[0], VERSION[1])
tertiary = VERSION[2]
type_ = VERSION[3]
type_num = VERSION[4]
versions["branch"] = branch
v = versions["branch"]
if tertiary:
versions["tertiary"] = "." + str(tertiary)
v += versions["tertiary"]
versions['short'] = v
if form is "short":
return v
v += " " + type_ + " " + str(type_num)
versions["normal"] = v
if form is "normal":
return v
v += " @" + git_sha()
versions["verbose"] = v
if form is "verbose":
return v
if form is "all":
return versions
|
python
|
def get_version(form='short'):
"""
Returns the version string.
Takes single argument ``form``, which should be one of the following
strings:
* ``short`` Returns major + minor branch version string with the format of
B.b.t.
* ``normal`` Returns human readable version string with the format of
B.b.t _type type_num.
* ``verbose`` Returns a verbose version string with the format of
B.b.t _type type_num@git_sha
* ``all`` Returns a dict of all versions.
"""
versions = {}
branch = "%s.%s" % (VERSION[0], VERSION[1])
tertiary = VERSION[2]
type_ = VERSION[3]
type_num = VERSION[4]
versions["branch"] = branch
v = versions["branch"]
if tertiary:
versions["tertiary"] = "." + str(tertiary)
v += versions["tertiary"]
versions['short'] = v
if form is "short":
return v
v += " " + type_ + " " + str(type_num)
versions["normal"] = v
if form is "normal":
return v
v += " @" + git_sha()
versions["verbose"] = v
if form is "verbose":
return v
if form is "all":
return versions
|
[
"def",
"get_version",
"(",
"form",
"=",
"'short'",
")",
":",
"versions",
"=",
"{",
"}",
"branch",
"=",
"\"%s.%s\"",
"%",
"(",
"VERSION",
"[",
"0",
"]",
",",
"VERSION",
"[",
"1",
"]",
")",
"tertiary",
"=",
"VERSION",
"[",
"2",
"]",
"type_",
"=",
"VERSION",
"[",
"3",
"]",
"type_num",
"=",
"VERSION",
"[",
"4",
"]",
"versions",
"[",
"\"branch\"",
"]",
"=",
"branch",
"v",
"=",
"versions",
"[",
"\"branch\"",
"]",
"if",
"tertiary",
":",
"versions",
"[",
"\"tertiary\"",
"]",
"=",
"\".\"",
"+",
"str",
"(",
"tertiary",
")",
"v",
"+=",
"versions",
"[",
"\"tertiary\"",
"]",
"versions",
"[",
"'short'",
"]",
"=",
"v",
"if",
"form",
"is",
"\"short\"",
":",
"return",
"v",
"v",
"+=",
"\" \"",
"+",
"type_",
"+",
"\" \"",
"+",
"str",
"(",
"type_num",
")",
"versions",
"[",
"\"normal\"",
"]",
"=",
"v",
"if",
"form",
"is",
"\"normal\"",
":",
"return",
"v",
"v",
"+=",
"\" @\"",
"+",
"git_sha",
"(",
")",
"versions",
"[",
"\"verbose\"",
"]",
"=",
"v",
"if",
"form",
"is",
"\"verbose\"",
":",
"return",
"v",
"if",
"form",
"is",
"\"all\"",
":",
"return",
"versions"
] |
Returns the version string.
Takes single argument ``form``, which should be one of the following
strings:
* ``short`` Returns major + minor branch version string with the format of
B.b.t.
* ``normal`` Returns human readable version string with the format of
B.b.t _type type_num.
* ``verbose`` Returns a verbose version string with the format of
B.b.t _type type_num@git_sha
* ``all`` Returns a dict of all versions.
|
[
"Returns",
"the",
"version",
"string",
"."
] |
91e2835c85c1618fcc4a1357dbb398353e662d1a
|
https://github.com/jmatt/threepio/blob/91e2835c85c1618fcc4a1357dbb398353e662d1a/threepio/version.py#L22-L60
|
246,233 |
jjjake/giganews
|
giganews/giganews.py
|
NewsGroup._download_article
|
def _download_article(self, article_number, max_retries=10):
"""Download a given article.
:type article_number: str
:param article_number: the article number to download.
:type group: str
:param group: the group that contains the article to be downloaded.
:returns: nntplib article response object if successful, else False.
"""
log.debug('downloading article {0} from {1}'.format(article_number, self.name))
_connection = self.session.connections.get()
try:
i = 0
while True:
if i >= max_retries:
return False
try:
_connection.group(self.name)
resp = _connection.article(article_number)
log.debug('downloaded article {0} from {1}'.format(article_number,
self.name))
return resp
# Connection closed, transient error, retry forever.
except EOFError:
log.warning('EOFError, refreshing connection retrying -- '
'article={0}, group={1}'.format(article_number, self.name))
self.session.refresh_connection(_connection)
time.sleep(2)
_connection = self.session.connections.get()
# NNTP Error.
except nntplib.NNTPError as exc:
log.warning('NNTPError: {0} -- article={1}, '
'group={2}'.format(exc, article_number, self.name))
if any(s in exc.response for s in ['430', '423']):
# Don't retry, article probably doesn't exist.
i = max_retries
else:
i += 1
except:
self.session.refresh_connection(_connection)
time.sleep(2)
_connection = self.session.connections.get()
# Always return connection back to the pool!
finally:
self.session.connections.put(_connection)
|
python
|
def _download_article(self, article_number, max_retries=10):
"""Download a given article.
:type article_number: str
:param article_number: the article number to download.
:type group: str
:param group: the group that contains the article to be downloaded.
:returns: nntplib article response object if successful, else False.
"""
log.debug('downloading article {0} from {1}'.format(article_number, self.name))
_connection = self.session.connections.get()
try:
i = 0
while True:
if i >= max_retries:
return False
try:
_connection.group(self.name)
resp = _connection.article(article_number)
log.debug('downloaded article {0} from {1}'.format(article_number,
self.name))
return resp
# Connection closed, transient error, retry forever.
except EOFError:
log.warning('EOFError, refreshing connection retrying -- '
'article={0}, group={1}'.format(article_number, self.name))
self.session.refresh_connection(_connection)
time.sleep(2)
_connection = self.session.connections.get()
# NNTP Error.
except nntplib.NNTPError as exc:
log.warning('NNTPError: {0} -- article={1}, '
'group={2}'.format(exc, article_number, self.name))
if any(s in exc.response for s in ['430', '423']):
# Don't retry, article probably doesn't exist.
i = max_retries
else:
i += 1
except:
self.session.refresh_connection(_connection)
time.sleep(2)
_connection = self.session.connections.get()
# Always return connection back to the pool!
finally:
self.session.connections.put(_connection)
|
[
"def",
"_download_article",
"(",
"self",
",",
"article_number",
",",
"max_retries",
"=",
"10",
")",
":",
"log",
".",
"debug",
"(",
"'downloading article {0} from {1}'",
".",
"format",
"(",
"article_number",
",",
"self",
".",
"name",
")",
")",
"_connection",
"=",
"self",
".",
"session",
".",
"connections",
".",
"get",
"(",
")",
"try",
":",
"i",
"=",
"0",
"while",
"True",
":",
"if",
"i",
">=",
"max_retries",
":",
"return",
"False",
"try",
":",
"_connection",
".",
"group",
"(",
"self",
".",
"name",
")",
"resp",
"=",
"_connection",
".",
"article",
"(",
"article_number",
")",
"log",
".",
"debug",
"(",
"'downloaded article {0} from {1}'",
".",
"format",
"(",
"article_number",
",",
"self",
".",
"name",
")",
")",
"return",
"resp",
"# Connection closed, transient error, retry forever.",
"except",
"EOFError",
":",
"log",
".",
"warning",
"(",
"'EOFError, refreshing connection retrying -- '",
"'article={0}, group={1}'",
".",
"format",
"(",
"article_number",
",",
"self",
".",
"name",
")",
")",
"self",
".",
"session",
".",
"refresh_connection",
"(",
"_connection",
")",
"time",
".",
"sleep",
"(",
"2",
")",
"_connection",
"=",
"self",
".",
"session",
".",
"connections",
".",
"get",
"(",
")",
"# NNTP Error.",
"except",
"nntplib",
".",
"NNTPError",
"as",
"exc",
":",
"log",
".",
"warning",
"(",
"'NNTPError: {0} -- article={1}, '",
"'group={2}'",
".",
"format",
"(",
"exc",
",",
"article_number",
",",
"self",
".",
"name",
")",
")",
"if",
"any",
"(",
"s",
"in",
"exc",
".",
"response",
"for",
"s",
"in",
"[",
"'430'",
",",
"'423'",
"]",
")",
":",
"# Don't retry, article probably doesn't exist.",
"i",
"=",
"max_retries",
"else",
":",
"i",
"+=",
"1",
"except",
":",
"self",
".",
"session",
".",
"refresh_connection",
"(",
"_connection",
")",
"time",
".",
"sleep",
"(",
"2",
")",
"_connection",
"=",
"self",
".",
"session",
".",
"connections",
".",
"get",
"(",
")",
"# Always return connection back to the pool!",
"finally",
":",
"self",
".",
"session",
".",
"connections",
".",
"put",
"(",
"_connection",
")"
] |
Download a given article.
:type article_number: str
:param article_number: the article number to download.
:type group: str
:param group: the group that contains the article to be downloaded.
:returns: nntplib article response object if successful, else False.
|
[
"Download",
"a",
"given",
"article",
"."
] |
8cfb26de6c10c482a8da348d438f0ce19e477573
|
https://github.com/jjjake/giganews/blob/8cfb26de6c10c482a8da348d438f0ce19e477573/giganews/giganews.py#L280-L331
|
246,234 |
jjjake/giganews
|
giganews/giganews.py
|
NewsGroup.index_article
|
def index_article(self, msg_str, article_number, start, length):
"""Add article to index file.
:type msg_str: str
:param msg_str: the message string to index.
:type article_number: str
:param article_number: the article number to index.
:type start: int
:param start: the byte-offset where a given message starts in the
corresponding mbox file.
:type length: int
:param length: the byte-length of the message.
:rtype: bool
:returns: True
"""
f = cStringIO.StringIO(msg_str)
message = rfc822.Message(f)
f.close()
# Replace header dict None values with '', and any tabs or
# newlines with ' '.
h = dict()
for key in message.dict:
if not message.dict[key]:
h[key] = ''
h[key] = message.dict[key]
h[key] = utf8_encode_str(message.dict[key])
if '\n' in h[key]:
h[key] = h[key].replace('\n', ' ')
if '\t' in h[key]:
h[key] = h[key].replace('\t', ' ')
date = h.get('NNTP-Posting-Date')
if not date:
date = h.get('date', '')
date = get_utc_iso_date(date)
idx_line = (date, h.get('message-id'), h.get('from'), h.get('newsgroups'),
h.get('subject'), h.get('references', ''), start, length)
idx_fname = '{name}.{date}.mbox.csv'.format(**self.__dict__)
s = cStringIO.StringIO()
writer = csv.writer(s, dialect='excel-tab')
writer.writerow(idx_line)
with self._idx_lock:
with open(idx_fname, 'a') as fp:
fp.write(s.getvalue())
s.close()
return True
|
python
|
def index_article(self, msg_str, article_number, start, length):
"""Add article to index file.
:type msg_str: str
:param msg_str: the message string to index.
:type article_number: str
:param article_number: the article number to index.
:type start: int
:param start: the byte-offset where a given message starts in the
corresponding mbox file.
:type length: int
:param length: the byte-length of the message.
:rtype: bool
:returns: True
"""
f = cStringIO.StringIO(msg_str)
message = rfc822.Message(f)
f.close()
# Replace header dict None values with '', and any tabs or
# newlines with ' '.
h = dict()
for key in message.dict:
if not message.dict[key]:
h[key] = ''
h[key] = message.dict[key]
h[key] = utf8_encode_str(message.dict[key])
if '\n' in h[key]:
h[key] = h[key].replace('\n', ' ')
if '\t' in h[key]:
h[key] = h[key].replace('\t', ' ')
date = h.get('NNTP-Posting-Date')
if not date:
date = h.get('date', '')
date = get_utc_iso_date(date)
idx_line = (date, h.get('message-id'), h.get('from'), h.get('newsgroups'),
h.get('subject'), h.get('references', ''), start, length)
idx_fname = '{name}.{date}.mbox.csv'.format(**self.__dict__)
s = cStringIO.StringIO()
writer = csv.writer(s, dialect='excel-tab')
writer.writerow(idx_line)
with self._idx_lock:
with open(idx_fname, 'a') as fp:
fp.write(s.getvalue())
s.close()
return True
|
[
"def",
"index_article",
"(",
"self",
",",
"msg_str",
",",
"article_number",
",",
"start",
",",
"length",
")",
":",
"f",
"=",
"cStringIO",
".",
"StringIO",
"(",
"msg_str",
")",
"message",
"=",
"rfc822",
".",
"Message",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"# Replace header dict None values with '', and any tabs or",
"# newlines with ' '.",
"h",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"message",
".",
"dict",
":",
"if",
"not",
"message",
".",
"dict",
"[",
"key",
"]",
":",
"h",
"[",
"key",
"]",
"=",
"''",
"h",
"[",
"key",
"]",
"=",
"message",
".",
"dict",
"[",
"key",
"]",
"h",
"[",
"key",
"]",
"=",
"utf8_encode_str",
"(",
"message",
".",
"dict",
"[",
"key",
"]",
")",
"if",
"'\\n'",
"in",
"h",
"[",
"key",
"]",
":",
"h",
"[",
"key",
"]",
"=",
"h",
"[",
"key",
"]",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
"if",
"'\\t'",
"in",
"h",
"[",
"key",
"]",
":",
"h",
"[",
"key",
"]",
"=",
"h",
"[",
"key",
"]",
".",
"replace",
"(",
"'\\t'",
",",
"' '",
")",
"date",
"=",
"h",
".",
"get",
"(",
"'NNTP-Posting-Date'",
")",
"if",
"not",
"date",
":",
"date",
"=",
"h",
".",
"get",
"(",
"'date'",
",",
"''",
")",
"date",
"=",
"get_utc_iso_date",
"(",
"date",
")",
"idx_line",
"=",
"(",
"date",
",",
"h",
".",
"get",
"(",
"'message-id'",
")",
",",
"h",
".",
"get",
"(",
"'from'",
")",
",",
"h",
".",
"get",
"(",
"'newsgroups'",
")",
",",
"h",
".",
"get",
"(",
"'subject'",
")",
",",
"h",
".",
"get",
"(",
"'references'",
",",
"''",
")",
",",
"start",
",",
"length",
")",
"idx_fname",
"=",
"'{name}.{date}.mbox.csv'",
".",
"format",
"(",
"*",
"*",
"self",
".",
"__dict__",
")",
"s",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"s",
",",
"dialect",
"=",
"'excel-tab'",
")",
"writer",
".",
"writerow",
"(",
"idx_line",
")",
"with",
"self",
".",
"_idx_lock",
":",
"with",
"open",
"(",
"idx_fname",
",",
"'a'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"s",
".",
"getvalue",
"(",
")",
")",
"s",
".",
"close",
"(",
")",
"return",
"True"
] |
Add article to index file.
:type msg_str: str
:param msg_str: the message string to index.
:type article_number: str
:param article_number: the article number to index.
:type start: int
:param start: the byte-offset where a given message starts in the
corresponding mbox file.
:type length: int
:param length: the byte-length of the message.
:rtype: bool
:returns: True
|
[
"Add",
"article",
"to",
"index",
"file",
"."
] |
8cfb26de6c10c482a8da348d438f0ce19e477573
|
https://github.com/jjjake/giganews/blob/8cfb26de6c10c482a8da348d438f0ce19e477573/giganews/giganews.py#L375-L429
|
246,235 |
jjjake/giganews
|
giganews/giganews.py
|
NewsGroup.compress_and_sort_index
|
def compress_and_sort_index(self):
"""Sort index, add header, and compress.
:rtype: bool
:returns: True
"""
idx_fname = '{name}.{date}.mbox.csv'.format(**self.__dict__)
try:
reader = csv.reader(open(idx_fname), dialect='excel-tab')
except IOError:
return False
index = [x for x in reader if x]
sorted_index = sorted(index, key=itemgetter(0))
gzip_idx_fname = idx_fname + '.gz'
# Include UTF-8 BOM in header.
header = [
'\xef\xbb\xbf#date', 'msg_id', 'from', 'newsgroups', 'subject', 'references',
'start', 'length',
]
s = cStringIO.StringIO()
writer = csv.writer(s, dialect='excel-tab')
writer.writerow(header)
for line in sorted_index:
writer.writerow(line)
compressed_index = inline_compress_chunk(s.getvalue())
s.close()
with open(gzip_idx_fname, 'ab') as fp:
fp.write(compressed_index)
os.remove(idx_fname)
return True
|
python
|
def compress_and_sort_index(self):
"""Sort index, add header, and compress.
:rtype: bool
:returns: True
"""
idx_fname = '{name}.{date}.mbox.csv'.format(**self.__dict__)
try:
reader = csv.reader(open(idx_fname), dialect='excel-tab')
except IOError:
return False
index = [x for x in reader if x]
sorted_index = sorted(index, key=itemgetter(0))
gzip_idx_fname = idx_fname + '.gz'
# Include UTF-8 BOM in header.
header = [
'\xef\xbb\xbf#date', 'msg_id', 'from', 'newsgroups', 'subject', 'references',
'start', 'length',
]
s = cStringIO.StringIO()
writer = csv.writer(s, dialect='excel-tab')
writer.writerow(header)
for line in sorted_index:
writer.writerow(line)
compressed_index = inline_compress_chunk(s.getvalue())
s.close()
with open(gzip_idx_fname, 'ab') as fp:
fp.write(compressed_index)
os.remove(idx_fname)
return True
|
[
"def",
"compress_and_sort_index",
"(",
"self",
")",
":",
"idx_fname",
"=",
"'{name}.{date}.mbox.csv'",
".",
"format",
"(",
"*",
"*",
"self",
".",
"__dict__",
")",
"try",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"open",
"(",
"idx_fname",
")",
",",
"dialect",
"=",
"'excel-tab'",
")",
"except",
"IOError",
":",
"return",
"False",
"index",
"=",
"[",
"x",
"for",
"x",
"in",
"reader",
"if",
"x",
"]",
"sorted_index",
"=",
"sorted",
"(",
"index",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
"gzip_idx_fname",
"=",
"idx_fname",
"+",
"'.gz'",
"# Include UTF-8 BOM in header.",
"header",
"=",
"[",
"'\\xef\\xbb\\xbf#date'",
",",
"'msg_id'",
",",
"'from'",
",",
"'newsgroups'",
",",
"'subject'",
",",
"'references'",
",",
"'start'",
",",
"'length'",
",",
"]",
"s",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"s",
",",
"dialect",
"=",
"'excel-tab'",
")",
"writer",
".",
"writerow",
"(",
"header",
")",
"for",
"line",
"in",
"sorted_index",
":",
"writer",
".",
"writerow",
"(",
"line",
")",
"compressed_index",
"=",
"inline_compress_chunk",
"(",
"s",
".",
"getvalue",
"(",
")",
")",
"s",
".",
"close",
"(",
")",
"with",
"open",
"(",
"gzip_idx_fname",
",",
"'ab'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"compressed_index",
")",
"os",
".",
"remove",
"(",
"idx_fname",
")",
"return",
"True"
] |
Sort index, add header, and compress.
:rtype: bool
:returns: True
|
[
"Sort",
"index",
"add",
"header",
"and",
"compress",
"."
] |
8cfb26de6c10c482a8da348d438f0ce19e477573
|
https://github.com/jjjake/giganews/blob/8cfb26de6c10c482a8da348d438f0ce19e477573/giganews/giganews.py#L434-L467
|
246,236 |
seryl/Python-Couchdbhelper
|
couchdbhelper/__init__.py
|
CouchHelper.save
|
def save(self, data):
"""Save a document or list of documents"""
if not self.is_connected:
raise Exception("No database selected")
if not data:
return False
if isinstance(data, dict):
doc = couchdb.Document()
doc.update(data)
self.db.create(doc)
elif isinstance(data, couchdb.Document):
self.db.update(data)
elif isinstance(data, list):
self.db.update(data)
return True
|
python
|
def save(self, data):
"""Save a document or list of documents"""
if not self.is_connected:
raise Exception("No database selected")
if not data:
return False
if isinstance(data, dict):
doc = couchdb.Document()
doc.update(data)
self.db.create(doc)
elif isinstance(data, couchdb.Document):
self.db.update(data)
elif isinstance(data, list):
self.db.update(data)
return True
|
[
"def",
"save",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
":",
"raise",
"Exception",
"(",
"\"No database selected\"",
")",
"if",
"not",
"data",
":",
"return",
"False",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"doc",
"=",
"couchdb",
".",
"Document",
"(",
")",
"doc",
".",
"update",
"(",
"data",
")",
"self",
".",
"db",
".",
"create",
"(",
"doc",
")",
"elif",
"isinstance",
"(",
"data",
",",
"couchdb",
".",
"Document",
")",
":",
"self",
".",
"db",
".",
"update",
"(",
"data",
")",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"self",
".",
"db",
".",
"update",
"(",
"data",
")",
"return",
"True"
] |
Save a document or list of documents
|
[
"Save",
"a",
"document",
"or",
"list",
"of",
"documents"
] |
6783b777dd793da91ba6a2102f932492556ecbcd
|
https://github.com/seryl/Python-Couchdbhelper/blob/6783b777dd793da91ba6a2102f932492556ecbcd/couchdbhelper/__init__.py#L42-L56
|
246,237 |
jrabbit/austere
|
austere.py
|
win_register
|
def win_register():
"need to be admin"
try:
with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "austere.HTTP") as k:
# winreg.SetValue(k, None, winreg.REG_SZ, "{} austere".format(sys.argv[0]))
logger.debug("\shell")
with winreg.CreateKey(k, "shell") as shellkey:
logger.debug("\open")
with winreg.CreateKey(shellkey, "open") as openkey:
logger.debug("\command")
with winreg.CreateKey(openkey, "command") as cmdkey:
winreg.SetValue(cmdkey, None, winreg.REG_SZ, '"{} austere" "%1"'.format(sys.argv[0]))
# with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "austere.HTTPS") as kssl:
# winreg.SetValue(kssl, None, winreg.REG_SZ, "{} austere".format(sys.argv[0]))
except OSError as e:
logger.error(e)
|
python
|
def win_register():
"need to be admin"
try:
with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "austere.HTTP") as k:
# winreg.SetValue(k, None, winreg.REG_SZ, "{} austere".format(sys.argv[0]))
logger.debug("\shell")
with winreg.CreateKey(k, "shell") as shellkey:
logger.debug("\open")
with winreg.CreateKey(shellkey, "open") as openkey:
logger.debug("\command")
with winreg.CreateKey(openkey, "command") as cmdkey:
winreg.SetValue(cmdkey, None, winreg.REG_SZ, '"{} austere" "%1"'.format(sys.argv[0]))
# with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "austere.HTTPS") as kssl:
# winreg.SetValue(kssl, None, winreg.REG_SZ, "{} austere".format(sys.argv[0]))
except OSError as e:
logger.error(e)
|
[
"def",
"win_register",
"(",
")",
":",
"try",
":",
"with",
"winreg",
".",
"CreateKey",
"(",
"winreg",
".",
"HKEY_CLASSES_ROOT",
",",
"\"austere.HTTP\"",
")",
"as",
"k",
":",
"# winreg.SetValue(k, None, winreg.REG_SZ, \"{} austere\".format(sys.argv[0]))",
"logger",
".",
"debug",
"(",
"\"\\shell\"",
")",
"with",
"winreg",
".",
"CreateKey",
"(",
"k",
",",
"\"shell\"",
")",
"as",
"shellkey",
":",
"logger",
".",
"debug",
"(",
"\"",
"o",
"pen",
"\"",
")",
"with",
"winreg",
".",
"CreateKey",
"(",
"shellkey",
",",
"\"open\"",
")",
"as",
"openkey",
":",
"logger",
".",
"debug",
"(",
"\"\\command\"",
")",
"with",
"winreg",
".",
"CreateKey",
"(",
"openkey",
",",
"\"command\"",
")",
"as",
"cmdkey",
":",
"winreg",
".",
"SetValue",
"(",
"cmdkey",
",",
"None",
",",
"winreg",
".",
"REG_SZ",
",",
"'\"{} austere\" \"%1\"'",
".",
"format",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"# with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, \"austere.HTTPS\") as kssl:",
"# winreg.SetValue(kssl, None, winreg.REG_SZ, \"{} austere\".format(sys.argv[0]))",
"except",
"OSError",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"e",
")"
] |
need to be admin
|
[
"need",
"to",
"be",
"admin"
] |
3f062c70ae37ce9e63dd639f524cbb88247fc92c
|
https://github.com/jrabbit/austere/blob/3f062c70ae37ce9e63dd639f524cbb88247fc92c/austere.py#L102-L117
|
246,238 |
GaretJax/irco
|
irco/conf.py
|
load_config
|
def load_config(path=None, defaults=None):
"""
Loads and parses an INI style configuration file using Python's built-in
ConfigParser module.
If path is specified, load it.
If ``defaults`` (a list of strings) is given, try to load each entry as a
file, without throwing any error if the operation fails.
If ``defaults`` is not given, the following locations listed in the
DEFAULT_FILES constant are tried.
To completely disable defaults loading, pass in an empty list or ``False``.
Returns the SafeConfigParser instance used to load and parse the files.
"""
if defaults is None:
defaults = DEFAULT_FILES
config = configparser.SafeConfigParser(allow_no_value=True)
if defaults:
config.read(defaults)
if path:
with open(path) as fh:
config.readfp(fh)
return config
|
python
|
def load_config(path=None, defaults=None):
"""
Loads and parses an INI style configuration file using Python's built-in
ConfigParser module.
If path is specified, load it.
If ``defaults`` (a list of strings) is given, try to load each entry as a
file, without throwing any error if the operation fails.
If ``defaults`` is not given, the following locations listed in the
DEFAULT_FILES constant are tried.
To completely disable defaults loading, pass in an empty list or ``False``.
Returns the SafeConfigParser instance used to load and parse the files.
"""
if defaults is None:
defaults = DEFAULT_FILES
config = configparser.SafeConfigParser(allow_no_value=True)
if defaults:
config.read(defaults)
if path:
with open(path) as fh:
config.readfp(fh)
return config
|
[
"def",
"load_config",
"(",
"path",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"DEFAULT_FILES",
"config",
"=",
"configparser",
".",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"if",
"defaults",
":",
"config",
".",
"read",
"(",
"defaults",
")",
"if",
"path",
":",
"with",
"open",
"(",
"path",
")",
"as",
"fh",
":",
"config",
".",
"readfp",
"(",
"fh",
")",
"return",
"config"
] |
Loads and parses an INI style configuration file using Python's built-in
ConfigParser module.
If path is specified, load it.
If ``defaults`` (a list of strings) is given, try to load each entry as a
file, without throwing any error if the operation fails.
If ``defaults`` is not given, the following locations listed in the
DEFAULT_FILES constant are tried.
To completely disable defaults loading, pass in an empty list or ``False``.
Returns the SafeConfigParser instance used to load and parse the files.
|
[
"Loads",
"and",
"parses",
"an",
"INI",
"style",
"configuration",
"file",
"using",
"Python",
"s",
"built",
"-",
"in",
"ConfigParser",
"module",
"."
] |
e5df3cf1a608dc813011a1ee7e920637e5bd155c
|
https://github.com/GaretJax/irco/blob/e5df3cf1a608dc813011a1ee7e920637e5bd155c/irco/conf.py#L23-L53
|
246,239 |
sys-git/certifiable
|
certifiable/cli_impl/utils.py
|
load_value_from_schema
|
def load_value_from_schema(v):
"""
Load a value from a schema defined string.
"""
x = urllib.parse.urlparse(v)
if x.scheme.lower() == 'decimal':
v = Decimal(x.netloc)
elif x.scheme.lower() in ['int', 'integer']:
v = int(x.netloc)
elif x.scheme.lower() == 'float':
v = float(x.netloc)
elif x.scheme.lower() in ['s', 'str', 'string']:
v = str(x.netloc)
elif x.scheme.lower() in ['u', 'unicode']:
v = six.u(x.netloc)
elif x.scheme.lower() == 'email':
v = six.u(x.netloc)
elif x.scheme.lower() == 'bool':
v = bool(x.netloc)
elif x.scheme.lower() in ['b', 'bytes']:
v = six.b(x.netloc)
elif x.scheme.lower() in ['ts.iso8601', 'timestamp.iso8601']:
v = MayaDT.from_iso8601(x.netloc).datetime()
elif x.scheme.lower() in ['ts.rfc2822', 'timestamp.rfc2822']:
v = MayaDT.from_rfc2822(x.netloc).datetime()
elif x.scheme.lower() in ['ts.rfc3339', 'timestamp.rfx3339']:
v = MayaDT.from_rfc3339(x.netloc).datetime()
elif x.scheme.lower() in ['ts', 'timestamp']:
v = maya.parse(x.netloc).datetime()
elif x.scheme.lower() == 'date':
v = datetime.date.fromtimestamp(float(x.netloc))
elif x.scheme.lower() == 'time':
v = time.gmtime(float(x.netloc))
else:
v = None
return v
|
python
|
def load_value_from_schema(v):
"""
Load a value from a schema defined string.
"""
x = urllib.parse.urlparse(v)
if x.scheme.lower() == 'decimal':
v = Decimal(x.netloc)
elif x.scheme.lower() in ['int', 'integer']:
v = int(x.netloc)
elif x.scheme.lower() == 'float':
v = float(x.netloc)
elif x.scheme.lower() in ['s', 'str', 'string']:
v = str(x.netloc)
elif x.scheme.lower() in ['u', 'unicode']:
v = six.u(x.netloc)
elif x.scheme.lower() == 'email':
v = six.u(x.netloc)
elif x.scheme.lower() == 'bool':
v = bool(x.netloc)
elif x.scheme.lower() in ['b', 'bytes']:
v = six.b(x.netloc)
elif x.scheme.lower() in ['ts.iso8601', 'timestamp.iso8601']:
v = MayaDT.from_iso8601(x.netloc).datetime()
elif x.scheme.lower() in ['ts.rfc2822', 'timestamp.rfc2822']:
v = MayaDT.from_rfc2822(x.netloc).datetime()
elif x.scheme.lower() in ['ts.rfc3339', 'timestamp.rfx3339']:
v = MayaDT.from_rfc3339(x.netloc).datetime()
elif x.scheme.lower() in ['ts', 'timestamp']:
v = maya.parse(x.netloc).datetime()
elif x.scheme.lower() == 'date':
v = datetime.date.fromtimestamp(float(x.netloc))
elif x.scheme.lower() == 'time':
v = time.gmtime(float(x.netloc))
else:
v = None
return v
|
[
"def",
"load_value_from_schema",
"(",
"v",
")",
":",
"x",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"v",
")",
"if",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'decimal'",
":",
"v",
"=",
"Decimal",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'int'",
",",
"'integer'",
"]",
":",
"v",
"=",
"int",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'float'",
":",
"v",
"=",
"float",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'s'",
",",
"'str'",
",",
"'string'",
"]",
":",
"v",
"=",
"str",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'u'",
",",
"'unicode'",
"]",
":",
"v",
"=",
"six",
".",
"u",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'email'",
":",
"v",
"=",
"six",
".",
"u",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'bool'",
":",
"v",
"=",
"bool",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'b'",
",",
"'bytes'",
"]",
":",
"v",
"=",
"six",
".",
"b",
"(",
"x",
".",
"netloc",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'ts.iso8601'",
",",
"'timestamp.iso8601'",
"]",
":",
"v",
"=",
"MayaDT",
".",
"from_iso8601",
"(",
"x",
".",
"netloc",
")",
".",
"datetime",
"(",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'ts.rfc2822'",
",",
"'timestamp.rfc2822'",
"]",
":",
"v",
"=",
"MayaDT",
".",
"from_rfc2822",
"(",
"x",
".",
"netloc",
")",
".",
"datetime",
"(",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'ts.rfc3339'",
",",
"'timestamp.rfx3339'",
"]",
":",
"v",
"=",
"MayaDT",
".",
"from_rfc3339",
"(",
"x",
".",
"netloc",
")",
".",
"datetime",
"(",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"in",
"[",
"'ts'",
",",
"'timestamp'",
"]",
":",
"v",
"=",
"maya",
".",
"parse",
"(",
"x",
".",
"netloc",
")",
".",
"datetime",
"(",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'date'",
":",
"v",
"=",
"datetime",
".",
"date",
".",
"fromtimestamp",
"(",
"float",
"(",
"x",
".",
"netloc",
")",
")",
"elif",
"x",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"'time'",
":",
"v",
"=",
"time",
".",
"gmtime",
"(",
"float",
"(",
"x",
".",
"netloc",
")",
")",
"else",
":",
"v",
"=",
"None",
"return",
"v"
] |
Load a value from a schema defined string.
|
[
"Load",
"a",
"value",
"from",
"a",
"schema",
"defined",
"string",
"."
] |
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
|
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/cli_impl/utils.py#L73-L110
|
246,240 |
sys-git/certifiable
|
certifiable/cli_impl/utils.py
|
parse_value
|
def parse_value(v, parser, config, description):
"""
Convert a string received on the command-line into
a value or None.
:param str v:
The value to parse.
:param parser:
The fallback callable to load the value if loading
from scheme fails.
:param dict config:
The config to use.
:param str description:
Description (for debugging)
:return:
The parsed value
:rtype:
object
"""
val = None
if v == '':
return
if v is not None:
try:
val = load_value_from_schema(v)
except Exception as e:
six.raise_from(
CertifierTypeError(
message='{kind}'.format(
description=description,
kind=type(v).__name__,
),
required=config['required'],
value=v,
),
e)
else:
if val is None:
try:
return parser(v)
except CertifierTypeError:
raise
except CertifierValueError:
raise
except TypeError as e:
six.raise_from(
CertifierTypeError(
message='{kind}'.format(
description=description,
kind=type(v).__name__,
),
required=config['required'],
value=v,
),
e)
except ValueError as e:
six.raise_from(
CertifierValueError(
message='{value}'.format(
description=description,
value=v,
),
required=config['required'],
value=v,
),
e)
return val
|
python
|
def parse_value(v, parser, config, description):
"""
Convert a string received on the command-line into
a value or None.
:param str v:
The value to parse.
:param parser:
The fallback callable to load the value if loading
from scheme fails.
:param dict config:
The config to use.
:param str description:
Description (for debugging)
:return:
The parsed value
:rtype:
object
"""
val = None
if v == '':
return
if v is not None:
try:
val = load_value_from_schema(v)
except Exception as e:
six.raise_from(
CertifierTypeError(
message='{kind}'.format(
description=description,
kind=type(v).__name__,
),
required=config['required'],
value=v,
),
e)
else:
if val is None:
try:
return parser(v)
except CertifierTypeError:
raise
except CertifierValueError:
raise
except TypeError as e:
six.raise_from(
CertifierTypeError(
message='{kind}'.format(
description=description,
kind=type(v).__name__,
),
required=config['required'],
value=v,
),
e)
except ValueError as e:
six.raise_from(
CertifierValueError(
message='{value}'.format(
description=description,
value=v,
),
required=config['required'],
value=v,
),
e)
return val
|
[
"def",
"parse_value",
"(",
"v",
",",
"parser",
",",
"config",
",",
"description",
")",
":",
"val",
"=",
"None",
"if",
"v",
"==",
"''",
":",
"return",
"if",
"v",
"is",
"not",
"None",
":",
"try",
":",
"val",
"=",
"load_value_from_schema",
"(",
"v",
")",
"except",
"Exception",
"as",
"e",
":",
"six",
".",
"raise_from",
"(",
"CertifierTypeError",
"(",
"message",
"=",
"'{kind}'",
".",
"format",
"(",
"description",
"=",
"description",
",",
"kind",
"=",
"type",
"(",
"v",
")",
".",
"__name__",
",",
")",
",",
"required",
"=",
"config",
"[",
"'required'",
"]",
",",
"value",
"=",
"v",
",",
")",
",",
"e",
")",
"else",
":",
"if",
"val",
"is",
"None",
":",
"try",
":",
"return",
"parser",
"(",
"v",
")",
"except",
"CertifierTypeError",
":",
"raise",
"except",
"CertifierValueError",
":",
"raise",
"except",
"TypeError",
"as",
"e",
":",
"six",
".",
"raise_from",
"(",
"CertifierTypeError",
"(",
"message",
"=",
"'{kind}'",
".",
"format",
"(",
"description",
"=",
"description",
",",
"kind",
"=",
"type",
"(",
"v",
")",
".",
"__name__",
",",
")",
",",
"required",
"=",
"config",
"[",
"'required'",
"]",
",",
"value",
"=",
"v",
",",
")",
",",
"e",
")",
"except",
"ValueError",
"as",
"e",
":",
"six",
".",
"raise_from",
"(",
"CertifierValueError",
"(",
"message",
"=",
"'{value}'",
".",
"format",
"(",
"description",
"=",
"description",
",",
"value",
"=",
"v",
",",
")",
",",
"required",
"=",
"config",
"[",
"'required'",
"]",
",",
"value",
"=",
"v",
",",
")",
",",
"e",
")",
"return",
"val"
] |
Convert a string received on the command-line into
a value or None.
:param str v:
The value to parse.
:param parser:
The fallback callable to load the value if loading
from scheme fails.
:param dict config:
The config to use.
:param str description:
Description (for debugging)
:return:
The parsed value
:rtype:
object
|
[
"Convert",
"a",
"string",
"received",
"on",
"the",
"command",
"-",
"line",
"into",
"a",
"value",
"or",
"None",
"."
] |
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
|
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/cli_impl/utils.py#L113-L182
|
246,241 |
coumbole/mailscanner
|
mailscanner/parser.py
|
get_simple_date
|
def get_simple_date(datestring):
"""Transforms a datestring into shorter date 7.9.2017 > 07.09
Expects the datestring to be format 07.09.2017. If this is not the
case, returns string "Failed".
Keyword arguments:
datestring -- a string
Returns:
String -- The date in format "dd.MM." or "Failed"
"""
simple_date = re.compile(r"\d{1,2}(\.)\d{1,2}")
date = simple_date.search(datestring)
if date:
dates = date.group().split(".")
if len(dates[0]) == 1:
dates[0] = add_zero(dates[0])
if len(dates[1]) == 1:
dates[1] = add_zero(dates[1])
if date_is_valid(dates):
return '.'.join(dates) + '.'
return "Failed"
|
python
|
def get_simple_date(datestring):
"""Transforms a datestring into shorter date 7.9.2017 > 07.09
Expects the datestring to be format 07.09.2017. If this is not the
case, returns string "Failed".
Keyword arguments:
datestring -- a string
Returns:
String -- The date in format "dd.MM." or "Failed"
"""
simple_date = re.compile(r"\d{1,2}(\.)\d{1,2}")
date = simple_date.search(datestring)
if date:
dates = date.group().split(".")
if len(dates[0]) == 1:
dates[0] = add_zero(dates[0])
if len(dates[1]) == 1:
dates[1] = add_zero(dates[1])
if date_is_valid(dates):
return '.'.join(dates) + '.'
return "Failed"
|
[
"def",
"get_simple_date",
"(",
"datestring",
")",
":",
"simple_date",
"=",
"re",
".",
"compile",
"(",
"r\"\\d{1,2}(\\.)\\d{1,2}\"",
")",
"date",
"=",
"simple_date",
".",
"search",
"(",
"datestring",
")",
"if",
"date",
":",
"dates",
"=",
"date",
".",
"group",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"dates",
"[",
"0",
"]",
")",
"==",
"1",
":",
"dates",
"[",
"0",
"]",
"=",
"add_zero",
"(",
"dates",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"dates",
"[",
"1",
"]",
")",
"==",
"1",
":",
"dates",
"[",
"1",
"]",
"=",
"add_zero",
"(",
"dates",
"[",
"1",
"]",
")",
"if",
"date_is_valid",
"(",
"dates",
")",
":",
"return",
"'.'",
".",
"join",
"(",
"dates",
")",
"+",
"'.'",
"return",
"\"Failed\""
] |
Transforms a datestring into shorter date 7.9.2017 > 07.09
Expects the datestring to be format 07.09.2017. If this is not the
case, returns string "Failed".
Keyword arguments:
datestring -- a string
Returns:
String -- The date in format "dd.MM." or "Failed"
|
[
"Transforms",
"a",
"datestring",
"into",
"shorter",
"date",
"7",
".",
"9",
".",
"2017",
">",
"07",
".",
"09"
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L32-L55
|
246,242 |
coumbole/mailscanner
|
mailscanner/parser.py
|
get_month
|
def get_month(datestring):
"""Transforms a written month into corresponding month number.
E.g. November -> 11, or May -> 05.
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
"""
convert_written = re.compile(r"jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec", re.IGNORECASE)
month = convert_written.search(datestring)
month_number = None
# If there's a match, convert the month to its corresponding number
if month:
month_number = strptime(month.group(), "%b").tm_mon
if month_number < 10:
month_number = add_zero(month_number)
return str(month_number)
|
python
|
def get_month(datestring):
"""Transforms a written month into corresponding month number.
E.g. November -> 11, or May -> 05.
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
"""
convert_written = re.compile(r"jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec", re.IGNORECASE)
month = convert_written.search(datestring)
month_number = None
# If there's a match, convert the month to its corresponding number
if month:
month_number = strptime(month.group(), "%b").tm_mon
if month_number < 10:
month_number = add_zero(month_number)
return str(month_number)
|
[
"def",
"get_month",
"(",
"datestring",
")",
":",
"convert_written",
"=",
"re",
".",
"compile",
"(",
"r\"jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec\"",
",",
"re",
".",
"IGNORECASE",
")",
"month",
"=",
"convert_written",
".",
"search",
"(",
"datestring",
")",
"month_number",
"=",
"None",
"# If there's a match, convert the month to its corresponding number",
"if",
"month",
":",
"month_number",
"=",
"strptime",
"(",
"month",
".",
"group",
"(",
")",
",",
"\"%b\"",
")",
".",
"tm_mon",
"if",
"month_number",
"<",
"10",
":",
"month_number",
"=",
"add_zero",
"(",
"month_number",
")",
"return",
"str",
"(",
"month_number",
")"
] |
Transforms a written month into corresponding month number.
E.g. November -> 11, or May -> 05.
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
|
[
"Transforms",
"a",
"written",
"month",
"into",
"corresponding",
"month",
"number",
"."
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L58-L79
|
246,243 |
coumbole/mailscanner
|
mailscanner/parser.py
|
get_day_of_month
|
def get_day_of_month(datestring):
"""Transforms an ordinal number into plain number with padding zero.
E.g. 3rd -> 03, or 12th -> 12
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
"""
get_day = re.compile(r"\d{1,2}(st|nd|rd|th)?", re.IGNORECASE)
day = get_day.search(datestring)
the_day = None
if day:
if bool(re.search(r"[st|nd|rd|th]", day.group().lower())):
the_day = day.group()[:-2]
else:
the_day = day.group()
if int(the_day) < 10:
the_day = add_zero(the_day)
return str(the_day)
|
python
|
def get_day_of_month(datestring):
"""Transforms an ordinal number into plain number with padding zero.
E.g. 3rd -> 03, or 12th -> 12
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
"""
get_day = re.compile(r"\d{1,2}(st|nd|rd|th)?", re.IGNORECASE)
day = get_day.search(datestring)
the_day = None
if day:
if bool(re.search(r"[st|nd|rd|th]", day.group().lower())):
the_day = day.group()[:-2]
else:
the_day = day.group()
if int(the_day) < 10:
the_day = add_zero(the_day)
return str(the_day)
|
[
"def",
"get_day_of_month",
"(",
"datestring",
")",
":",
"get_day",
"=",
"re",
".",
"compile",
"(",
"r\"\\d{1,2}(st|nd|rd|th)?\"",
",",
"re",
".",
"IGNORECASE",
")",
"day",
"=",
"get_day",
".",
"search",
"(",
"datestring",
")",
"the_day",
"=",
"None",
"if",
"day",
":",
"if",
"bool",
"(",
"re",
".",
"search",
"(",
"r\"[st|nd|rd|th]\"",
",",
"day",
".",
"group",
"(",
")",
".",
"lower",
"(",
")",
")",
")",
":",
"the_day",
"=",
"day",
".",
"group",
"(",
")",
"[",
":",
"-",
"2",
"]",
"else",
":",
"the_day",
"=",
"day",
".",
"group",
"(",
")",
"if",
"int",
"(",
"the_day",
")",
"<",
"10",
":",
"the_day",
"=",
"add_zero",
"(",
"the_day",
")",
"return",
"str",
"(",
"the_day",
")"
] |
Transforms an ordinal number into plain number with padding zero.
E.g. 3rd -> 03, or 12th -> 12
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
|
[
"Transforms",
"an",
"ordinal",
"number",
"into",
"plain",
"number",
"with",
"padding",
"zero",
"."
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L81-L104
|
246,244 |
coumbole/mailscanner
|
mailscanner/parser.py
|
Parser.strip_string
|
def strip_string(self, string, *args):
"""Strips matching regular expressions from string
Keyword arguments:
string -- The given string, that will be stripped
*args -- List of regex strings, that are used in parsing
Returns:
String with *args removed from string
"""
res = string
for r in args:
res = re.sub(r, "", res.strip(),
flags=re.IGNORECASE|re.MULTILINE)
return res.strip()
|
python
|
def strip_string(self, string, *args):
"""Strips matching regular expressions from string
Keyword arguments:
string -- The given string, that will be stripped
*args -- List of regex strings, that are used in parsing
Returns:
String with *args removed from string
"""
res = string
for r in args:
res = re.sub(r, "", res.strip(),
flags=re.IGNORECASE|re.MULTILINE)
return res.strip()
|
[
"def",
"strip_string",
"(",
"self",
",",
"string",
",",
"*",
"args",
")",
":",
"res",
"=",
"string",
"for",
"r",
"in",
"args",
":",
"res",
"=",
"re",
".",
"sub",
"(",
"r",
",",
"\"\"",
",",
"res",
".",
"strip",
"(",
")",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
"return",
"res",
".",
"strip",
"(",
")"
] |
Strips matching regular expressions from string
Keyword arguments:
string -- The given string, that will be stripped
*args -- List of regex strings, that are used in parsing
Returns:
String with *args removed from string
|
[
"Strips",
"matching",
"regular",
"expressions",
"from",
"string"
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L112-L126
|
246,245 |
coumbole/mailscanner
|
mailscanner/parser.py
|
Parser.strip_between
|
def strip_between(self, string, start, end):
"""Deletes everything between regexes start and end from string"""
regex = start + r'.*?' + end + r'\s*'
res = re.sub(regex, '', string,
flags=re.DOTALL|re.IGNORECASE|re.MULTILINE)
return res
|
python
|
def strip_between(self, string, start, end):
"""Deletes everything between regexes start and end from string"""
regex = start + r'.*?' + end + r'\s*'
res = re.sub(regex, '', string,
flags=re.DOTALL|re.IGNORECASE|re.MULTILINE)
return res
|
[
"def",
"strip_between",
"(",
"self",
",",
"string",
",",
"start",
",",
"end",
")",
":",
"regex",
"=",
"start",
"+",
"r'.*?'",
"+",
"end",
"+",
"r'\\s*'",
"res",
"=",
"re",
".",
"sub",
"(",
"regex",
",",
"''",
",",
"string",
",",
"flags",
"=",
"re",
".",
"DOTALL",
"|",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
"return",
"res"
] |
Deletes everything between regexes start and end from string
|
[
"Deletes",
"everything",
"between",
"regexes",
"start",
"and",
"end",
"from",
"string"
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L128-L133
|
246,246 |
coumbole/mailscanner
|
mailscanner/parser.py
|
Parser.distance_between
|
def distance_between(self, string, start, end):
"""Returns number of lines between start and end"""
count = 0
started = False
for line in string.split("\n"):
if self.scan_line(line, start) and not started:
started = True
if self.scan_line(line, end):
return count
if started:
count += 1
return count
|
python
|
def distance_between(self, string, start, end):
"""Returns number of lines between start and end"""
count = 0
started = False
for line in string.split("\n"):
if self.scan_line(line, start) and not started:
started = True
if self.scan_line(line, end):
return count
if started:
count += 1
return count
|
[
"def",
"distance_between",
"(",
"self",
",",
"string",
",",
"start",
",",
"end",
")",
":",
"count",
"=",
"0",
"started",
"=",
"False",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"self",
".",
"scan_line",
"(",
"line",
",",
"start",
")",
"and",
"not",
"started",
":",
"started",
"=",
"True",
"if",
"self",
".",
"scan_line",
"(",
"line",
",",
"end",
")",
":",
"return",
"count",
"if",
"started",
":",
"count",
"+=",
"1",
"return",
"count"
] |
Returns number of lines between start and end
|
[
"Returns",
"number",
"of",
"lines",
"between",
"start",
"and",
"end"
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L135-L151
|
246,247 |
coumbole/mailscanner
|
mailscanner/parser.py
|
Parser.scan_line
|
def scan_line(self, line, regex):
"""Checks if regex is in line, returns bool"""
return bool(re.search(regex, line, flags=re.IGNORECASE))
|
python
|
def scan_line(self, line, regex):
"""Checks if regex is in line, returns bool"""
return bool(re.search(regex, line, flags=re.IGNORECASE))
|
[
"def",
"scan_line",
"(",
"self",
",",
"line",
",",
"regex",
")",
":",
"return",
"bool",
"(",
"re",
".",
"search",
"(",
"regex",
",",
"line",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
")"
] |
Checks if regex is in line, returns bool
|
[
"Checks",
"if",
"regex",
"is",
"in",
"line",
"returns",
"bool"
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L153-L155
|
246,248 |
coumbole/mailscanner
|
mailscanner/parser.py
|
Parser.scan_message
|
def scan_message(self, message, regex):
"""Scans regex from msg and returns the line that matches
Keyword arguments:
message -- A (long) string, e.g. email body that will be
scanned.
regex -- A regular expression string that the message will be
scanned against.
Returns:
Matching line or empty string
"""
for line in message.split("\n"):
if bool(re.search(
regex,
line,
flags=re.IGNORECASE|re.MULTILINE)):
return line
return ""
|
python
|
def scan_message(self, message, regex):
"""Scans regex from msg and returns the line that matches
Keyword arguments:
message -- A (long) string, e.g. email body that will be
scanned.
regex -- A regular expression string that the message will be
scanned against.
Returns:
Matching line or empty string
"""
for line in message.split("\n"):
if bool(re.search(
regex,
line,
flags=re.IGNORECASE|re.MULTILINE)):
return line
return ""
|
[
"def",
"scan_message",
"(",
"self",
",",
"message",
",",
"regex",
")",
":",
"for",
"line",
"in",
"message",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"bool",
"(",
"re",
".",
"search",
"(",
"regex",
",",
"line",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
":",
"return",
"line",
"return",
"\"\""
] |
Scans regex from msg and returns the line that matches
Keyword arguments:
message -- A (long) string, e.g. email body that will be
scanned.
regex -- A regular expression string that the message will be
scanned against.
Returns:
Matching line or empty string
|
[
"Scans",
"regex",
"from",
"msg",
"and",
"returns",
"the",
"line",
"that",
"matches"
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L157-L176
|
246,249 |
coumbole/mailscanner
|
mailscanner/parser.py
|
Parser.format_date
|
def format_date(self, dl_string):
"""Formats various date formats to dd.MM.
Examples
- January 15th --> 15.01.
- 15.01.2017 --> 15.01.
- 15th of January --> 15.01.
- 15.1. --> 15.01.
Keyword arguments:
dl_string -- a string to be formatted
Returns:
Date string in format dd.MM. or "None.None"
"""
thedate = get_simple_date(dl_string)
if thedate != "Failed" and thedate:
return thedate
day = get_day_of_month(dl_string)
month = get_month(dl_string)
return day + '.' + month + '.'
|
python
|
def format_date(self, dl_string):
"""Formats various date formats to dd.MM.
Examples
- January 15th --> 15.01.
- 15.01.2017 --> 15.01.
- 15th of January --> 15.01.
- 15.1. --> 15.01.
Keyword arguments:
dl_string -- a string to be formatted
Returns:
Date string in format dd.MM. or "None.None"
"""
thedate = get_simple_date(dl_string)
if thedate != "Failed" and thedate:
return thedate
day = get_day_of_month(dl_string)
month = get_month(dl_string)
return day + '.' + month + '.'
|
[
"def",
"format_date",
"(",
"self",
",",
"dl_string",
")",
":",
"thedate",
"=",
"get_simple_date",
"(",
"dl_string",
")",
"if",
"thedate",
"!=",
"\"Failed\"",
"and",
"thedate",
":",
"return",
"thedate",
"day",
"=",
"get_day_of_month",
"(",
"dl_string",
")",
"month",
"=",
"get_month",
"(",
"dl_string",
")",
"return",
"day",
"+",
"'.'",
"+",
"month",
"+",
"'.'"
] |
Formats various date formats to dd.MM.
Examples
- January 15th --> 15.01.
- 15.01.2017 --> 15.01.
- 15th of January --> 15.01.
- 15.1. --> 15.01.
Keyword arguments:
dl_string -- a string to be formatted
Returns:
Date string in format dd.MM. or "None.None"
|
[
"Formats",
"various",
"date",
"formats",
"to",
"dd",
".",
"MM",
"."
] |
ead19ac8c7dee27e507c1593032863232c13f636
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L182-L204
|
246,250 |
kilometer-io/kilometer-python
|
kilometer/__init__.py
|
EventsAPIClient.add_user
|
def add_user(self, user_id, custom_properties=None, headers=None, endpoint_url=None):
"""
Creates a new identified user if he doesn't exist.
:param str user_id: identified user's ID
:param dict custom_properties: user properties
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/users'
headers = headers or self._default_headers()
payload = {"user_id": user_id}
if custom_properties is not None:
payload["user_properties"] = custom_properties
response = requests.post(url, headers=headers, json=payload)
return response
|
python
|
def add_user(self, user_id, custom_properties=None, headers=None, endpoint_url=None):
"""
Creates a new identified user if he doesn't exist.
:param str user_id: identified user's ID
:param dict custom_properties: user properties
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/users'
headers = headers or self._default_headers()
payload = {"user_id": user_id}
if custom_properties is not None:
payload["user_properties"] = custom_properties
response = requests.post(url, headers=headers, json=payload)
return response
|
[
"def",
"add_user",
"(",
"self",
",",
"user_id",
",",
"custom_properties",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"endpoint_url",
"or",
"self",
".",
"_endpoint_url",
"url",
"=",
"endpoint_url",
"+",
"'/users'",
"headers",
"=",
"headers",
"or",
"self",
".",
"_default_headers",
"(",
")",
"payload",
"=",
"{",
"\"user_id\"",
":",
"user_id",
"}",
"if",
"custom_properties",
"is",
"not",
"None",
":",
"payload",
"[",
"\"user_properties\"",
"]",
"=",
"custom_properties",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"payload",
")",
"return",
"response"
] |
Creates a new identified user if he doesn't exist.
:param str user_id: identified user's ID
:param dict custom_properties: user properties
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
|
[
"Creates",
"a",
"new",
"identified",
"user",
"if",
"he",
"doesn",
"t",
"exist",
"."
] |
22a720cfed5aa74d4957b4597f224cede2e7c0e5
|
https://github.com/kilometer-io/kilometer-python/blob/22a720cfed5aa74d4957b4597f224cede2e7c0e5/kilometer/__init__.py#L44-L66
|
246,251 |
kilometer-io/kilometer-python
|
kilometer/__init__.py
|
EventsAPIClient.add_event
|
def add_event(self, user_id, event_name, event_properties=None, headers=None, endpoint_url=None):
"""
Send an identified event. If a user doesn't exist it will create one.
:param str user_id: identified user's ID
:param str event_name: event name (e.g. "visit_website")
:param dict event_properties: properties that describe the event's details
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/users/' + user_id + '/events'
headers = headers or self._default_headers()
event_properties = event_properties or {}
payload = {
"event_name": event_name,
"custom_properties": event_properties
}
response = requests.post(url, headers=headers, json=payload)
return response
|
python
|
def add_event(self, user_id, event_name, event_properties=None, headers=None, endpoint_url=None):
"""
Send an identified event. If a user doesn't exist it will create one.
:param str user_id: identified user's ID
:param str event_name: event name (e.g. "visit_website")
:param dict event_properties: properties that describe the event's details
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/users/' + user_id + '/events'
headers = headers or self._default_headers()
event_properties = event_properties or {}
payload = {
"event_name": event_name,
"custom_properties": event_properties
}
response = requests.post(url, headers=headers, json=payload)
return response
|
[
"def",
"add_event",
"(",
"self",
",",
"user_id",
",",
"event_name",
",",
"event_properties",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"endpoint_url",
"or",
"self",
".",
"_endpoint_url",
"url",
"=",
"endpoint_url",
"+",
"'/users/'",
"+",
"user_id",
"+",
"'/events'",
"headers",
"=",
"headers",
"or",
"self",
".",
"_default_headers",
"(",
")",
"event_properties",
"=",
"event_properties",
"or",
"{",
"}",
"payload",
"=",
"{",
"\"event_name\"",
":",
"event_name",
",",
"\"custom_properties\"",
":",
"event_properties",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"payload",
")",
"return",
"response"
] |
Send an identified event. If a user doesn't exist it will create one.
:param str user_id: identified user's ID
:param str event_name: event name (e.g. "visit_website")
:param dict event_properties: properties that describe the event's details
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
|
[
"Send",
"an",
"identified",
"event",
".",
"If",
"a",
"user",
"doesn",
"t",
"exist",
"it",
"will",
"create",
"one",
"."
] |
22a720cfed5aa74d4957b4597f224cede2e7c0e5
|
https://github.com/kilometer-io/kilometer-python/blob/22a720cfed5aa74d4957b4597f224cede2e7c0e5/kilometer/__init__.py#L68-L92
|
246,252 |
kilometer-io/kilometer-python
|
kilometer/__init__.py
|
EventsAPIClient.decrease_user_property
|
def decrease_user_property(self, user_id, property_name, value=0, headers=None, endpoint_url=None):
"""
Decrease a user's property by a value.
:param str user_id: identified user's ID
:param str property_name: user property name to increase
:param number value: amount by which to decrease the property
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + "/users/" + user_id + "/properties/" + property_name + "/decrease/" + value.__str__()
headers = headers or self._default_headers(content_type="")
response = requests.post(url, headers=headers)
return response
|
python
|
def decrease_user_property(self, user_id, property_name, value=0, headers=None, endpoint_url=None):
"""
Decrease a user's property by a value.
:param str user_id: identified user's ID
:param str property_name: user property name to increase
:param number value: amount by which to decrease the property
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + "/users/" + user_id + "/properties/" + property_name + "/decrease/" + value.__str__()
headers = headers or self._default_headers(content_type="")
response = requests.post(url, headers=headers)
return response
|
[
"def",
"decrease_user_property",
"(",
"self",
",",
"user_id",
",",
"property_name",
",",
"value",
"=",
"0",
",",
"headers",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"endpoint_url",
"or",
"self",
".",
"_endpoint_url",
"url",
"=",
"endpoint_url",
"+",
"\"/users/\"",
"+",
"user_id",
"+",
"\"/properties/\"",
"+",
"property_name",
"+",
"\"/decrease/\"",
"+",
"value",
".",
"__str__",
"(",
")",
"headers",
"=",
"headers",
"or",
"self",
".",
"_default_headers",
"(",
"content_type",
"=",
"\"\"",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"return",
"response"
] |
Decrease a user's property by a value.
:param str user_id: identified user's ID
:param str property_name: user property name to increase
:param number value: amount by which to decrease the property
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
|
[
"Decrease",
"a",
"user",
"s",
"property",
"by",
"a",
"value",
"."
] |
22a720cfed5aa74d4957b4597f224cede2e7c0e5
|
https://github.com/kilometer-io/kilometer-python/blob/22a720cfed5aa74d4957b4597f224cede2e7c0e5/kilometer/__init__.py#L114-L132
|
246,253 |
kilometer-io/kilometer-python
|
kilometer/__init__.py
|
EventsAPIClient.update_user_properties
|
def update_user_properties(self, user_id, user_properties, headers=None, endpoint_url=None):
"""
Update a user's properties with values provided in "user_properties" dictionary
:param str user_id: identified user's ID
:param dict user_properties: user properties to update with a new values
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/users/' + user_id + '/properties'
headers = headers or self._default_headers()
payload = user_properties
response = requests.put(url, headers=headers, json=payload)
return response
|
python
|
def update_user_properties(self, user_id, user_properties, headers=None, endpoint_url=None):
"""
Update a user's properties with values provided in "user_properties" dictionary
:param str user_id: identified user's ID
:param dict user_properties: user properties to update with a new values
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/users/' + user_id + '/properties'
headers = headers or self._default_headers()
payload = user_properties
response = requests.put(url, headers=headers, json=payload)
return response
|
[
"def",
"update_user_properties",
"(",
"self",
",",
"user_id",
",",
"user_properties",
",",
"headers",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"endpoint_url",
"or",
"self",
".",
"_endpoint_url",
"url",
"=",
"endpoint_url",
"+",
"'/users/'",
"+",
"user_id",
"+",
"'/properties'",
"headers",
"=",
"headers",
"or",
"self",
".",
"_default_headers",
"(",
")",
"payload",
"=",
"user_properties",
"response",
"=",
"requests",
".",
"put",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"payload",
")",
"return",
"response"
] |
Update a user's properties with values provided in "user_properties" dictionary
:param str user_id: identified user's ID
:param dict user_properties: user properties to update with a new values
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
|
[
"Update",
"a",
"user",
"s",
"properties",
"with",
"values",
"provided",
"in",
"user_properties",
"dictionary"
] |
22a720cfed5aa74d4957b4597f224cede2e7c0e5
|
https://github.com/kilometer-io/kilometer-python/blob/22a720cfed5aa74d4957b4597f224cede2e7c0e5/kilometer/__init__.py#L134-L152
|
246,254 |
kilometer-io/kilometer-python
|
kilometer/__init__.py
|
EventsAPIClient.link_user_to_group
|
def link_user_to_group(self, user_id, group_id, headers=None, endpoint_url=None):
"""
Links a user to a group
:param str user_id: identified user's ID
:param str group_id: group ID
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/groups/' + group_id + '/link/' + user_id
headers = headers or self._default_headers()
response = requests.post(url, headers=headers)
return response
|
python
|
def link_user_to_group(self, user_id, group_id, headers=None, endpoint_url=None):
"""
Links a user to a group
:param str user_id: identified user's ID
:param str group_id: group ID
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/groups/' + group_id + '/link/' + user_id
headers = headers or self._default_headers()
response = requests.post(url, headers=headers)
return response
|
[
"def",
"link_user_to_group",
"(",
"self",
",",
"user_id",
",",
"group_id",
",",
"headers",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"endpoint_url",
"or",
"self",
".",
"_endpoint_url",
"url",
"=",
"endpoint_url",
"+",
"'/groups/'",
"+",
"group_id",
"+",
"'/link/'",
"+",
"user_id",
"headers",
"=",
"headers",
"or",
"self",
".",
"_default_headers",
"(",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"return",
"response"
] |
Links a user to a group
:param str user_id: identified user's ID
:param str group_id: group ID
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
|
[
"Links",
"a",
"user",
"to",
"a",
"group"
] |
22a720cfed5aa74d4957b4597f224cede2e7c0e5
|
https://github.com/kilometer-io/kilometer-python/blob/22a720cfed5aa74d4957b4597f224cede2e7c0e5/kilometer/__init__.py#L154-L171
|
246,255 |
kilometer-io/kilometer-python
|
kilometer/__init__.py
|
EventsAPIClient.update_group_properties
|
def update_group_properties(self, group_id, group_properties, headers=None, endpoint_url=None):
"""
Update a group's properties with values provided in "group_properties" dictionary
:param str group_id: group ID
:param dict group_properties: group properties to update with a new values
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/groups/' + group_id + '/properties'
headers = headers or self._default_headers()
payload = group_properties
response = requests.put(url, headers=headers, json=payload)
return response
|
python
|
def update_group_properties(self, group_id, group_properties, headers=None, endpoint_url=None):
"""
Update a group's properties with values provided in "group_properties" dictionary
:param str group_id: group ID
:param dict group_properties: group properties to update with a new values
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
"""
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + '/groups/' + group_id + '/properties'
headers = headers or self._default_headers()
payload = group_properties
response = requests.put(url, headers=headers, json=payload)
return response
|
[
"def",
"update_group_properties",
"(",
"self",
",",
"group_id",
",",
"group_properties",
",",
"headers",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"endpoint_url",
"=",
"endpoint_url",
"or",
"self",
".",
"_endpoint_url",
"url",
"=",
"endpoint_url",
"+",
"'/groups/'",
"+",
"group_id",
"+",
"'/properties'",
"headers",
"=",
"headers",
"or",
"self",
".",
"_default_headers",
"(",
")",
"payload",
"=",
"group_properties",
"response",
"=",
"requests",
".",
"put",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"payload",
")",
"return",
"response"
] |
Update a group's properties with values provided in "group_properties" dictionary
:param str group_id: group ID
:param dict group_properties: group properties to update with a new values
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Response
|
[
"Update",
"a",
"group",
"s",
"properties",
"with",
"values",
"provided",
"in",
"group_properties",
"dictionary"
] |
22a720cfed5aa74d4957b4597f224cede2e7c0e5
|
https://github.com/kilometer-io/kilometer-python/blob/22a720cfed5aa74d4957b4597f224cede2e7c0e5/kilometer/__init__.py#L173-L191
|
246,256 |
langloisjp/pysvcmetrics
|
statsdclient.py
|
StatsdClient.timing
|
def timing(self, stats, value):
"""
Log timing information
>>> client = StatsdClient()
>>> client.timing('example.timing', 500)
>>> client.timing(('example.timing23', 'example.timing29'), 500)
"""
self.update_stats(stats, value, self.SC_TIMING)
|
python
|
def timing(self, stats, value):
"""
Log timing information
>>> client = StatsdClient()
>>> client.timing('example.timing', 500)
>>> client.timing(('example.timing23', 'example.timing29'), 500)
"""
self.update_stats(stats, value, self.SC_TIMING)
|
[
"def",
"timing",
"(",
"self",
",",
"stats",
",",
"value",
")",
":",
"self",
".",
"update_stats",
"(",
"stats",
",",
"value",
",",
"self",
".",
"SC_TIMING",
")"
] |
Log timing information
>>> client = StatsdClient()
>>> client.timing('example.timing', 500)
>>> client.timing(('example.timing23', 'example.timing29'), 500)
|
[
"Log",
"timing",
"information"
] |
a126fc029ab645d9db46c0f5712c416cdf80e370
|
https://github.com/langloisjp/pysvcmetrics/blob/a126fc029ab645d9db46c0f5712c416cdf80e370/statsdclient.py#L30-L38
|
246,257 |
langloisjp/pysvcmetrics
|
statsdclient.py
|
StatsdClient.count
|
def count(self, stats, value, sample_rate=1):
"""
Updates one or more stats counters by arbitrary value
>>> client = StatsdClient()
>>> client.count('example.counter', 17)
"""
self.update_stats(stats, value, self.SC_COUNT, sample_rate)
|
python
|
def count(self, stats, value, sample_rate=1):
"""
Updates one or more stats counters by arbitrary value
>>> client = StatsdClient()
>>> client.count('example.counter', 17)
"""
self.update_stats(stats, value, self.SC_COUNT, sample_rate)
|
[
"def",
"count",
"(",
"self",
",",
"stats",
",",
"value",
",",
"sample_rate",
"=",
"1",
")",
":",
"self",
".",
"update_stats",
"(",
"stats",
",",
"value",
",",
"self",
".",
"SC_COUNT",
",",
"sample_rate",
")"
] |
Updates one or more stats counters by arbitrary value
>>> client = StatsdClient()
>>> client.count('example.counter', 17)
|
[
"Updates",
"one",
"or",
"more",
"stats",
"counters",
"by",
"arbitrary",
"value"
] |
a126fc029ab645d9db46c0f5712c416cdf80e370
|
https://github.com/langloisjp/pysvcmetrics/blob/a126fc029ab645d9db46c0f5712c416cdf80e370/statsdclient.py#L79-L86
|
246,258 |
langloisjp/pysvcmetrics
|
statsdclient.py
|
StatsdClient.timeit
|
def timeit(self, metric, func, *args, **kwargs):
"""
Times given function and log metric in ms for duration of execution.
>>> import time
>>> client = StatsdClient()
>>> client.timeit("latency", time.sleep, 0.5)
"""
(res, seconds) = timeit(func, *args, **kwargs)
self.timing(metric, seconds * 1000.0)
return res
|
python
|
def timeit(self, metric, func, *args, **kwargs):
"""
Times given function and log metric in ms for duration of execution.
>>> import time
>>> client = StatsdClient()
>>> client.timeit("latency", time.sleep, 0.5)
"""
(res, seconds) = timeit(func, *args, **kwargs)
self.timing(metric, seconds * 1000.0)
return res
|
[
"def",
"timeit",
"(",
"self",
",",
"metric",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"res",
",",
"seconds",
")",
"=",
"timeit",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"timing",
"(",
"metric",
",",
"seconds",
"*",
"1000.0",
")",
"return",
"res"
] |
Times given function and log metric in ms for duration of execution.
>>> import time
>>> client = StatsdClient()
>>> client.timeit("latency", time.sleep, 0.5)
|
[
"Times",
"given",
"function",
"and",
"log",
"metric",
"in",
"ms",
"for",
"duration",
"of",
"execution",
"."
] |
a126fc029ab645d9db46c0f5712c416cdf80e370
|
https://github.com/langloisjp/pysvcmetrics/blob/a126fc029ab645d9db46c0f5712c416cdf80e370/statsdclient.py#L88-L98
|
246,259 |
langloisjp/pysvcmetrics
|
statsdclient.py
|
StatsdClient.format
|
def format(keys, value, _type, prefix=""):
"""
General format function.
>>> StatsdClient.format("example.format", 2, "T")
{'example.format': '2|T'}
>>> StatsdClient.format(("example.format31", "example.format37"), "2",
... "T")
{'example.format31': '2|T', 'example.format37': '2|T'}
>>> StatsdClient.format("example.format", 2, "T", "prefix.")
{'prefix.example.format': '2|T'}
"""
data = {}
value = "{0}|{1}".format(value, _type)
# TODO: Allow any iterable except strings
if not isinstance(keys, (list, tuple)):
keys = [keys]
for key in keys:
data[prefix + key] = value
return data
|
python
|
def format(keys, value, _type, prefix=""):
"""
General format function.
>>> StatsdClient.format("example.format", 2, "T")
{'example.format': '2|T'}
>>> StatsdClient.format(("example.format31", "example.format37"), "2",
... "T")
{'example.format31': '2|T', 'example.format37': '2|T'}
>>> StatsdClient.format("example.format", 2, "T", "prefix.")
{'prefix.example.format': '2|T'}
"""
data = {}
value = "{0}|{1}".format(value, _type)
# TODO: Allow any iterable except strings
if not isinstance(keys, (list, tuple)):
keys = [keys]
for key in keys:
data[prefix + key] = value
return data
|
[
"def",
"format",
"(",
"keys",
",",
"value",
",",
"_type",
",",
"prefix",
"=",
"\"\"",
")",
":",
"data",
"=",
"{",
"}",
"value",
"=",
"\"{0}|{1}\"",
".",
"format",
"(",
"value",
",",
"_type",
")",
"# TODO: Allow any iterable except strings",
"if",
"not",
"isinstance",
"(",
"keys",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"for",
"key",
"in",
"keys",
":",
"data",
"[",
"prefix",
"+",
"key",
"]",
"=",
"value",
"return",
"data"
] |
General format function.
>>> StatsdClient.format("example.format", 2, "T")
{'example.format': '2|T'}
>>> StatsdClient.format(("example.format31", "example.format37"), "2",
... "T")
{'example.format31': '2|T', 'example.format37': '2|T'}
>>> StatsdClient.format("example.format", 2, "T", "prefix.")
{'prefix.example.format': '2|T'}
|
[
"General",
"format",
"function",
"."
] |
a126fc029ab645d9db46c0f5712c416cdf80e370
|
https://github.com/langloisjp/pysvcmetrics/blob/a126fc029ab645d9db46c0f5712c416cdf80e370/statsdclient.py#L111-L130
|
246,260 |
nivardus/kclboot
|
kclboot/bootstrapper.py
|
Bootstrapper.jars
|
def jars(self, absolute=True):
'''
List of jars in the jar path
'''
jars = glob(os.path.join(self._jar_path, '*.jar'))
return jars if absolute else map(lambda j: os.path.abspath(j), jars)
|
python
|
def jars(self, absolute=True):
'''
List of jars in the jar path
'''
jars = glob(os.path.join(self._jar_path, '*.jar'))
return jars if absolute else map(lambda j: os.path.abspath(j), jars)
|
[
"def",
"jars",
"(",
"self",
",",
"absolute",
"=",
"True",
")",
":",
"jars",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_jar_path",
",",
"'*.jar'",
")",
")",
"return",
"jars",
"if",
"absolute",
"else",
"map",
"(",
"lambda",
"j",
":",
"os",
".",
"path",
".",
"abspath",
"(",
"j",
")",
",",
"jars",
")"
] |
List of jars in the jar path
|
[
"List",
"of",
"jars",
"in",
"the",
"jar",
"path"
] |
aee054d9186938bec51f19e9ed8deed6ac6fe492
|
https://github.com/nivardus/kclboot/blob/aee054d9186938bec51f19e9ed8deed6ac6fe492/kclboot/bootstrapper.py#L61-L66
|
246,261 |
nivardus/kclboot
|
kclboot/bootstrapper.py
|
Bootstrapper.download_jars_to
|
def download_jars_to(cls, folder):
'''
Download missing jars to a specific folder
'''
if not os.path.exists(folder):
os.makedirs(folder)
for info in JARS:
jar = MavenJar(info[0], info[1], info[2])
path = os.path.join(folder, jar.filename)
if os.path.isfile(path):
print("Skipping already downloaded file: %s" % jar.filename)
continue
print("Downloading %s..." % jar.filename)
jar.download_to(folder)
|
python
|
def download_jars_to(cls, folder):
'''
Download missing jars to a specific folder
'''
if not os.path.exists(folder):
os.makedirs(folder)
for info in JARS:
jar = MavenJar(info[0], info[1], info[2])
path = os.path.join(folder, jar.filename)
if os.path.isfile(path):
print("Skipping already downloaded file: %s" % jar.filename)
continue
print("Downloading %s..." % jar.filename)
jar.download_to(folder)
|
[
"def",
"download_jars_to",
"(",
"cls",
",",
"folder",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"for",
"info",
"in",
"JARS",
":",
"jar",
"=",
"MavenJar",
"(",
"info",
"[",
"0",
"]",
",",
"info",
"[",
"1",
"]",
",",
"info",
"[",
"2",
"]",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"jar",
".",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"print",
"(",
"\"Skipping already downloaded file: %s\"",
"%",
"jar",
".",
"filename",
")",
"continue",
"print",
"(",
"\"Downloading %s...\"",
"%",
"jar",
".",
"filename",
")",
"jar",
".",
"download_to",
"(",
"folder",
")"
] |
Download missing jars to a specific folder
|
[
"Download",
"missing",
"jars",
"to",
"a",
"specific",
"folder"
] |
aee054d9186938bec51f19e9ed8deed6ac6fe492
|
https://github.com/nivardus/kclboot/blob/aee054d9186938bec51f19e9ed8deed6ac6fe492/kclboot/bootstrapper.py#L82-L97
|
246,262 |
KelSolaar/Oncilla
|
oncilla/reStructuredText_to_html.py
|
reStructuredText_to_html
|
def reStructuredText_to_html(input, output, css_file):
"""
Outputs a reStructuredText file to html.
:param input: Input reStructuredText file to convert.
:type input: unicode
:param output: Output html file.
:type output: unicode
:param css_file: Css file.
:type css_file: unicode
:return: Definition success.
:rtype: bool
"""
LOGGER.info("{0} | Converting '{1}' reStructuredText file to html!".format(
reStructuredText_to_html.__name__, input))
os.system("{0} --stylesheet-path='{1}' '{2}' > '{3}'".format(RST2HTML,
os.path.join(os.path.dirname(__file__), css_file),
input,
output))
LOGGER.info("{0} | Formatting html file!".format("Tidy"))
os.system("tidy -config {0} -m '{1}'".format(os.path.join(os.path.dirname(__file__), TIDY_SETTINGS_FILE), output))
file = File(output)
file.cache()
LOGGER.info("{0} | Replacing spaces with tabs!".format(reStructuredText_to_html.__name__))
file.content = [line.replace(" " * 4, "\t") for line in file.content]
file.write()
return True
|
python
|
def reStructuredText_to_html(input, output, css_file):
"""
Outputs a reStructuredText file to html.
:param input: Input reStructuredText file to convert.
:type input: unicode
:param output: Output html file.
:type output: unicode
:param css_file: Css file.
:type css_file: unicode
:return: Definition success.
:rtype: bool
"""
LOGGER.info("{0} | Converting '{1}' reStructuredText file to html!".format(
reStructuredText_to_html.__name__, input))
os.system("{0} --stylesheet-path='{1}' '{2}' > '{3}'".format(RST2HTML,
os.path.join(os.path.dirname(__file__), css_file),
input,
output))
LOGGER.info("{0} | Formatting html file!".format("Tidy"))
os.system("tidy -config {0} -m '{1}'".format(os.path.join(os.path.dirname(__file__), TIDY_SETTINGS_FILE), output))
file = File(output)
file.cache()
LOGGER.info("{0} | Replacing spaces with tabs!".format(reStructuredText_to_html.__name__))
file.content = [line.replace(" " * 4, "\t") for line in file.content]
file.write()
return True
|
[
"def",
"reStructuredText_to_html",
"(",
"input",
",",
"output",
",",
"css_file",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"{0} | Converting '{1}' reStructuredText file to html!\"",
".",
"format",
"(",
"reStructuredText_to_html",
".",
"__name__",
",",
"input",
")",
")",
"os",
".",
"system",
"(",
"\"{0} --stylesheet-path='{1}' '{2}' > '{3}'\"",
".",
"format",
"(",
"RST2HTML",
",",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"css_file",
")",
",",
"input",
",",
"output",
")",
")",
"LOGGER",
".",
"info",
"(",
"\"{0} | Formatting html file!\"",
".",
"format",
"(",
"\"Tidy\"",
")",
")",
"os",
".",
"system",
"(",
"\"tidy -config {0} -m '{1}'\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"TIDY_SETTINGS_FILE",
")",
",",
"output",
")",
")",
"file",
"=",
"File",
"(",
"output",
")",
"file",
".",
"cache",
"(",
")",
"LOGGER",
".",
"info",
"(",
"\"{0} | Replacing spaces with tabs!\"",
".",
"format",
"(",
"reStructuredText_to_html",
".",
"__name__",
")",
")",
"file",
".",
"content",
"=",
"[",
"line",
".",
"replace",
"(",
"\" \"",
"*",
"4",
",",
"\"\\t\"",
")",
"for",
"line",
"in",
"file",
".",
"content",
"]",
"file",
".",
"write",
"(",
")",
"return",
"True"
] |
Outputs a reStructuredText file to html.
:param input: Input reStructuredText file to convert.
:type input: unicode
:param output: Output html file.
:type output: unicode
:param css_file: Css file.
:type css_file: unicode
:return: Definition success.
:rtype: bool
|
[
"Outputs",
"a",
"reStructuredText",
"file",
"to",
"html",
"."
] |
2b4db3704cf2c22a09a207681cb041fff555a994
|
https://github.com/KelSolaar/Oncilla/blob/2b4db3704cf2c22a09a207681cb041fff555a994/oncilla/reStructuredText_to_html.py#L56-L86
|
246,263 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
attributes_from_dict
|
def attributes_from_dict(document):
"""Convert a Json representation of a set of attribute instances into a
dictionary.
Parameters
----------
document : Json object
Json serialization of attribute instances
Returns
-------
dict(Attribute)
Dictionary of attribute instance objects keyed by their name
"""
attributes = dict()
for attr in document:
name = str(attr['name'])
attributes[name] = Attribute(
name,
attr['value']
)
return attributes
|
python
|
def attributes_from_dict(document):
"""Convert a Json representation of a set of attribute instances into a
dictionary.
Parameters
----------
document : Json object
Json serialization of attribute instances
Returns
-------
dict(Attribute)
Dictionary of attribute instance objects keyed by their name
"""
attributes = dict()
for attr in document:
name = str(attr['name'])
attributes[name] = Attribute(
name,
attr['value']
)
return attributes
|
[
"def",
"attributes_from_dict",
"(",
"document",
")",
":",
"attributes",
"=",
"dict",
"(",
")",
"for",
"attr",
"in",
"document",
":",
"name",
"=",
"str",
"(",
"attr",
"[",
"'name'",
"]",
")",
"attributes",
"[",
"name",
"]",
"=",
"Attribute",
"(",
"name",
",",
"attr",
"[",
"'value'",
"]",
")",
"return",
"attributes"
] |
Convert a Json representation of a set of attribute instances into a
dictionary.
Parameters
----------
document : Json object
Json serialization of attribute instances
Returns
-------
dict(Attribute)
Dictionary of attribute instance objects keyed by their name
|
[
"Convert",
"a",
"Json",
"representation",
"of",
"a",
"set",
"of",
"attribute",
"instances",
"into",
"a",
"dictionary",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L369-L390
|
246,264 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
attributes_to_dict
|
def attributes_to_dict(attributes):
"""Transform a dictionary of attribute instances into a list of Json
objects, i.e., list of key-value pairs.
Parameters
----------
attributes : dict(Attribute)
Dictionary of attribute instances
Returns
-------
list(dict(name:..., value:...))
List of key-value pairs.
"""
result = []
for key in attributes:
result.append({
'name' : key,
'value' : attributes[key].value
})
return result
|
python
|
def attributes_to_dict(attributes):
"""Transform a dictionary of attribute instances into a list of Json
objects, i.e., list of key-value pairs.
Parameters
----------
attributes : dict(Attribute)
Dictionary of attribute instances
Returns
-------
list(dict(name:..., value:...))
List of key-value pairs.
"""
result = []
for key in attributes:
result.append({
'name' : key,
'value' : attributes[key].value
})
return result
|
[
"def",
"attributes_to_dict",
"(",
"attributes",
")",
":",
"result",
"=",
"[",
"]",
"for",
"key",
"in",
"attributes",
":",
"result",
".",
"append",
"(",
"{",
"'name'",
":",
"key",
",",
"'value'",
":",
"attributes",
"[",
"key",
"]",
".",
"value",
"}",
")",
"return",
"result"
] |
Transform a dictionary of attribute instances into a list of Json
objects, i.e., list of key-value pairs.
Parameters
----------
attributes : dict(Attribute)
Dictionary of attribute instances
Returns
-------
list(dict(name:..., value:...))
List of key-value pairs.
|
[
"Transform",
"a",
"dictionary",
"of",
"attribute",
"instances",
"into",
"a",
"list",
"of",
"Json",
"objects",
"i",
".",
"e",
".",
"list",
"of",
"key",
"-",
"value",
"pairs",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L393-L413
|
246,265 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
to_dict
|
def to_dict(attributes, definitions):
"""Create a dictionary of attributes from a given list of key-value pairs.
Detects duplicate definitions of the same attribute and raises an exception.
Expects a list of dictionaries (e.g., Json object) objects having 'name'
and 'value' keys. The type of the element associated with the 'value' key is
arbitrary. Raises a ValueError exception if the given array violates the
expected format.
The list of attribute definitions defines the set valid attribute names .
Raises an ValueError exception if an attribute with an invalid name is
in the attributes array.
If the list of attributes is None an empty dictionary will be returned.
Parameters
----------
attributes : list()
Expects a list of Attributes of dictionaries with 'name' and 'value'
elements.
definitions: list(dict('id': ..., ...))
List of attribute definitons.
Returns
-------
Dictionary
Dictionary of attribute instances keyed by their name
"""
# Create a list of valis parameter names
valid_names = {}
for para in definitions:
valid_names[para.identifier] = para
result = {}
if not attributes is None:
for element in attributes:
if isinstance(element, dict):
# Create attribute from dictionary
for key in ['name', 'value']:
if not key in element:
raise ValueError('object has no key ' + key + ': ' + str(element))
name = str(element['name'])
if not name in valid_names:
raise ValueError('invalid parameter name: ' + name)
try:
value = valid_names[name].data_type.from_string(
element['value']
)
except ValueError as ex:
raise ValueError(str(ex))
attr = Attribute(name, value)
else:
# Element is expected to be an attribute object
attr = element
# Make sure that the attribute value is of valid type. Make
# sure that attr.name is valid.
if attr.name in valid_names:
valid_names[attr.name].data_type.test_value(attr.value)
else:
raise ValueError('invalid parameter name: ' + attr.name)
if attr.name in result:
raise ValueError('duplicate attribute: ' + attr.name)
result[attr.name] = attr
return result
|
python
|
def to_dict(attributes, definitions):
"""Create a dictionary of attributes from a given list of key-value pairs.
Detects duplicate definitions of the same attribute and raises an exception.
Expects a list of dictionaries (e.g., Json object) objects having 'name'
and 'value' keys. The type of the element associated with the 'value' key is
arbitrary. Raises a ValueError exception if the given array violates the
expected format.
The list of attribute definitions defines the set valid attribute names .
Raises an ValueError exception if an attribute with an invalid name is
in the attributes array.
If the list of attributes is None an empty dictionary will be returned.
Parameters
----------
attributes : list()
Expects a list of Attributes of dictionaries with 'name' and 'value'
elements.
definitions: list(dict('id': ..., ...))
List of attribute definitons.
Returns
-------
Dictionary
Dictionary of attribute instances keyed by their name
"""
# Create a list of valis parameter names
valid_names = {}
for para in definitions:
valid_names[para.identifier] = para
result = {}
if not attributes is None:
for element in attributes:
if isinstance(element, dict):
# Create attribute from dictionary
for key in ['name', 'value']:
if not key in element:
raise ValueError('object has no key ' + key + ': ' + str(element))
name = str(element['name'])
if not name in valid_names:
raise ValueError('invalid parameter name: ' + name)
try:
value = valid_names[name].data_type.from_string(
element['value']
)
except ValueError as ex:
raise ValueError(str(ex))
attr = Attribute(name, value)
else:
# Element is expected to be an attribute object
attr = element
# Make sure that the attribute value is of valid type. Make
# sure that attr.name is valid.
if attr.name in valid_names:
valid_names[attr.name].data_type.test_value(attr.value)
else:
raise ValueError('invalid parameter name: ' + attr.name)
if attr.name in result:
raise ValueError('duplicate attribute: ' + attr.name)
result[attr.name] = attr
return result
|
[
"def",
"to_dict",
"(",
"attributes",
",",
"definitions",
")",
":",
"# Create a list of valis parameter names",
"valid_names",
"=",
"{",
"}",
"for",
"para",
"in",
"definitions",
":",
"valid_names",
"[",
"para",
".",
"identifier",
"]",
"=",
"para",
"result",
"=",
"{",
"}",
"if",
"not",
"attributes",
"is",
"None",
":",
"for",
"element",
"in",
"attributes",
":",
"if",
"isinstance",
"(",
"element",
",",
"dict",
")",
":",
"# Create attribute from dictionary",
"for",
"key",
"in",
"[",
"'name'",
",",
"'value'",
"]",
":",
"if",
"not",
"key",
"in",
"element",
":",
"raise",
"ValueError",
"(",
"'object has no key '",
"+",
"key",
"+",
"': '",
"+",
"str",
"(",
"element",
")",
")",
"name",
"=",
"str",
"(",
"element",
"[",
"'name'",
"]",
")",
"if",
"not",
"name",
"in",
"valid_names",
":",
"raise",
"ValueError",
"(",
"'invalid parameter name: '",
"+",
"name",
")",
"try",
":",
"value",
"=",
"valid_names",
"[",
"name",
"]",
".",
"data_type",
".",
"from_string",
"(",
"element",
"[",
"'value'",
"]",
")",
"except",
"ValueError",
"as",
"ex",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"ex",
")",
")",
"attr",
"=",
"Attribute",
"(",
"name",
",",
"value",
")",
"else",
":",
"# Element is expected to be an attribute object",
"attr",
"=",
"element",
"# Make sure that the attribute value is of valid type. Make",
"# sure that attr.name is valid.",
"if",
"attr",
".",
"name",
"in",
"valid_names",
":",
"valid_names",
"[",
"attr",
".",
"name",
"]",
".",
"data_type",
".",
"test_value",
"(",
"attr",
".",
"value",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'invalid parameter name: '",
"+",
"attr",
".",
"name",
")",
"if",
"attr",
".",
"name",
"in",
"result",
":",
"raise",
"ValueError",
"(",
"'duplicate attribute: '",
"+",
"attr",
".",
"name",
")",
"result",
"[",
"attr",
".",
"name",
"]",
"=",
"attr",
"return",
"result"
] |
Create a dictionary of attributes from a given list of key-value pairs.
Detects duplicate definitions of the same attribute and raises an exception.
Expects a list of dictionaries (e.g., Json object) objects having 'name'
and 'value' keys. The type of the element associated with the 'value' key is
arbitrary. Raises a ValueError exception if the given array violates the
expected format.
The list of attribute definitions defines the set valid attribute names .
Raises an ValueError exception if an attribute with an invalid name is
in the attributes array.
If the list of attributes is None an empty dictionary will be returned.
Parameters
----------
attributes : list()
Expects a list of Attributes of dictionaries with 'name' and 'value'
elements.
definitions: list(dict('id': ..., ...))
List of attribute definitons.
Returns
-------
Dictionary
Dictionary of attribute instances keyed by their name
|
[
"Create",
"a",
"dictionary",
"of",
"attributes",
"from",
"a",
"given",
"list",
"of",
"key",
"-",
"value",
"pairs",
".",
"Detects",
"duplicate",
"definitions",
"of",
"the",
"same",
"attribute",
"and",
"raises",
"an",
"exception",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L416-L478
|
246,266 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
AttributeDefinition.from_dict
|
def from_dict(document):
"""Create attribute definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeDefinition
"""
if 'default' in document:
default = document['default']
else:
default = None
return AttributeDefinition(
document['id'],
document['name'],
document['description'],
AttributeType.from_dict(document['type']),
default=default
)
|
python
|
def from_dict(document):
"""Create attribute definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeDefinition
"""
if 'default' in document:
default = document['default']
else:
default = None
return AttributeDefinition(
document['id'],
document['name'],
document['description'],
AttributeType.from_dict(document['type']),
default=default
)
|
[
"def",
"from_dict",
"(",
"document",
")",
":",
"if",
"'default'",
"in",
"document",
":",
"default",
"=",
"document",
"[",
"'default'",
"]",
"else",
":",
"default",
"=",
"None",
"return",
"AttributeDefinition",
"(",
"document",
"[",
"'id'",
"]",
",",
"document",
"[",
"'name'",
"]",
",",
"document",
"[",
"'description'",
"]",
",",
"AttributeType",
".",
"from_dict",
"(",
"document",
"[",
"'type'",
"]",
")",
",",
"default",
"=",
"default",
")"
] |
Create attribute definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeDefinition
|
[
"Create",
"attribute",
"definition",
"form",
"Json",
"-",
"like",
"object",
"represenation",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L90-L112
|
246,267 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
AttributeDefinition.to_dict
|
def to_dict(self):
"""Convert attribute definition into a dictionary.
Returns
-------
dict
Json-like dictionary representation of the attribute definition
"""
obj = {
'id' : self.identifier,
'name' : self.name,
'description' : self.description,
'type' : self.data_type.to_dict()
}
if not self.default is None:
obj['default'] = self.default
return obj
|
python
|
def to_dict(self):
"""Convert attribute definition into a dictionary.
Returns
-------
dict
Json-like dictionary representation of the attribute definition
"""
obj = {
'id' : self.identifier,
'name' : self.name,
'description' : self.description,
'type' : self.data_type.to_dict()
}
if not self.default is None:
obj['default'] = self.default
return obj
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"obj",
"=",
"{",
"'id'",
":",
"self",
".",
"identifier",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'type'",
":",
"self",
".",
"data_type",
".",
"to_dict",
"(",
")",
"}",
"if",
"not",
"self",
".",
"default",
"is",
"None",
":",
"obj",
"[",
"'default'",
"]",
"=",
"self",
".",
"default",
"return",
"obj"
] |
Convert attribute definition into a dictionary.
Returns
-------
dict
Json-like dictionary representation of the attribute definition
|
[
"Convert",
"attribute",
"definition",
"into",
"a",
"dictionary",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L114-L130
|
246,268 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
AttributeType.from_dict
|
def from_dict(document):
"""Create data type definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeType
"""
# Get the type name from the document
type_name = document['name']
if type_name == ATTR_TYPE_INT:
return IntType()
elif type_name == ATTR_TYPE_FLOAT:
return FloatType()
elif type_name == ATTR_TYPE_ENUM:
return EnumType(document['values'])
elif type_name == ATTR_TYPE_DICT:
return DictType()
elif type_name == ATTR_TYPE_LIST:
return ListType()
else:
raise ValueError('invalid attribute type: ' + str(type_name))
|
python
|
def from_dict(document):
"""Create data type definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeType
"""
# Get the type name from the document
type_name = document['name']
if type_name == ATTR_TYPE_INT:
return IntType()
elif type_name == ATTR_TYPE_FLOAT:
return FloatType()
elif type_name == ATTR_TYPE_ENUM:
return EnumType(document['values'])
elif type_name == ATTR_TYPE_DICT:
return DictType()
elif type_name == ATTR_TYPE_LIST:
return ListType()
else:
raise ValueError('invalid attribute type: ' + str(type_name))
|
[
"def",
"from_dict",
"(",
"document",
")",
":",
"# Get the type name from the document",
"type_name",
"=",
"document",
"[",
"'name'",
"]",
"if",
"type_name",
"==",
"ATTR_TYPE_INT",
":",
"return",
"IntType",
"(",
")",
"elif",
"type_name",
"==",
"ATTR_TYPE_FLOAT",
":",
"return",
"FloatType",
"(",
")",
"elif",
"type_name",
"==",
"ATTR_TYPE_ENUM",
":",
"return",
"EnumType",
"(",
"document",
"[",
"'values'",
"]",
")",
"elif",
"type_name",
"==",
"ATTR_TYPE_DICT",
":",
"return",
"DictType",
"(",
")",
"elif",
"type_name",
"==",
"ATTR_TYPE_LIST",
":",
"return",
"ListType",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'invalid attribute type: '",
"+",
"str",
"(",
"type_name",
")",
")"
] |
Create data type definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeType
|
[
"Create",
"data",
"type",
"definition",
"form",
"Json",
"-",
"like",
"object",
"represenation",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L153-L178
|
246,269 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
DictType.from_string
|
def from_string(self, value):
"""Convert string to dictionary."""
# Remove optional {}
if value.startswith('{') and value.endswith('}'):
text = value[1:-1].strip()
else:
text = value.strip()
# Result is a dictionary
result = {}
# Convert each pair of <int>:<float> into a key, value pair.
for val in text.split(','):
tokens = val.split(':')
if len(tokens) != 2:
raise ValueError('invalid entry in dictionary: ' + val)
result[str(int(tokens[0].strip()))] = float(tokens[1].strip())
return result
|
python
|
def from_string(self, value):
"""Convert string to dictionary."""
# Remove optional {}
if value.startswith('{') and value.endswith('}'):
text = value[1:-1].strip()
else:
text = value.strip()
# Result is a dictionary
result = {}
# Convert each pair of <int>:<float> into a key, value pair.
for val in text.split(','):
tokens = val.split(':')
if len(tokens) != 2:
raise ValueError('invalid entry in dictionary: ' + val)
result[str(int(tokens[0].strip()))] = float(tokens[1].strip())
return result
|
[
"def",
"from_string",
"(",
"self",
",",
"value",
")",
":",
"# Remove optional {}",
"if",
"value",
".",
"startswith",
"(",
"'{'",
")",
"and",
"value",
".",
"endswith",
"(",
"'}'",
")",
":",
"text",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"text",
"=",
"value",
".",
"strip",
"(",
")",
"# Result is a dictionary",
"result",
"=",
"{",
"}",
"# Convert each pair of <int>:<float> into a key, value pair.",
"for",
"val",
"in",
"text",
".",
"split",
"(",
"','",
")",
":",
"tokens",
"=",
"val",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"tokens",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'invalid entry in dictionary: '",
"+",
"val",
")",
"result",
"[",
"str",
"(",
"int",
"(",
"tokens",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
")",
"]",
"=",
"float",
"(",
"tokens",
"[",
"1",
"]",
".",
"strip",
"(",
")",
")",
"return",
"result"
] |
Convert string to dictionary.
|
[
"Convert",
"string",
"to",
"dictionary",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L227-L242
|
246,270 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
EnumType.from_string
|
def from_string(self, value):
"""Convert string to enum value."""
if not isinstance(value, basestring):
raise ValueError('expected string value: ' + str(type(value)))
self.test_value(value)
return value
|
python
|
def from_string(self, value):
"""Convert string to enum value."""
if not isinstance(value, basestring):
raise ValueError('expected string value: ' + str(type(value)))
self.test_value(value)
return value
|
[
"def",
"from_string",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'expected string value: '",
"+",
"str",
"(",
"type",
"(",
"value",
")",
")",
")",
"self",
".",
"test_value",
"(",
"value",
")",
"return",
"value"
] |
Convert string to enum value.
|
[
"Convert",
"string",
"to",
"enum",
"value",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L264-L269
|
246,271 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
EnumType.to_dict
|
def to_dict(self):
"""Convert enum data type definition into a dictionary. Overrides the
super class method to add list of enumeration values.
Returns
-------
dict
Json-like dictionary representation of the attribute data type
"""
obj = super(EnumType, self).to_dict()
obj['values'] = self.values
return obj
|
python
|
def to_dict(self):
"""Convert enum data type definition into a dictionary. Overrides the
super class method to add list of enumeration values.
Returns
-------
dict
Json-like dictionary representation of the attribute data type
"""
obj = super(EnumType, self).to_dict()
obj['values'] = self.values
return obj
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"obj",
"=",
"super",
"(",
"EnumType",
",",
"self",
")",
".",
"to_dict",
"(",
")",
"obj",
"[",
"'values'",
"]",
"=",
"self",
".",
"values",
"return",
"obj"
] |
Convert enum data type definition into a dictionary. Overrides the
super class method to add list of enumeration values.
Returns
-------
dict
Json-like dictionary representation of the attribute data type
|
[
"Convert",
"enum",
"data",
"type",
"definition",
"into",
"a",
"dictionary",
".",
"Overrides",
"the",
"super",
"class",
"method",
"to",
"add",
"list",
"of",
"enumeration",
"values",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L277-L288
|
246,272 |
heikomuller/sco-datastore
|
scodata/attribute.py
|
ListType.from_string
|
def from_string(self, value):
"""Convert string to list."""
# Remove optional []
if value.startswith('[') and value.endswith(']'):
text = value[1:-1].strip()
else:
text = value.strip()
# Result is a list
result = []
# If value starts with '(' assume a list of pairs
if text.startswith('('):
tokens = text.split(',')
if len(tokens) % 2 != 0:
raise ValueError('not a valid list of pairs')
pos = 0
while (pos < len(tokens)):
val1 = float(tokens[pos].strip()[1:].strip())
val2 = float(tokens[pos + 1].strip()[:-1])
result.append((val1, val2))
pos += 2
else:
for val in text.split(','):
result.append(float(val))
# Ensure that the result contains at least two elements
if len(result) < 2:
raise ValueError('invalid number of elements in list: ' + str(len(result)))
return result
|
python
|
def from_string(self, value):
"""Convert string to list."""
# Remove optional []
if value.startswith('[') and value.endswith(']'):
text = value[1:-1].strip()
else:
text = value.strip()
# Result is a list
result = []
# If value starts with '(' assume a list of pairs
if text.startswith('('):
tokens = text.split(',')
if len(tokens) % 2 != 0:
raise ValueError('not a valid list of pairs')
pos = 0
while (pos < len(tokens)):
val1 = float(tokens[pos].strip()[1:].strip())
val2 = float(tokens[pos + 1].strip()[:-1])
result.append((val1, val2))
pos += 2
else:
for val in text.split(','):
result.append(float(val))
# Ensure that the result contains at least two elements
if len(result) < 2:
raise ValueError('invalid number of elements in list: ' + str(len(result)))
return result
|
[
"def",
"from_string",
"(",
"self",
",",
"value",
")",
":",
"# Remove optional []",
"if",
"value",
".",
"startswith",
"(",
"'['",
")",
"and",
"value",
".",
"endswith",
"(",
"']'",
")",
":",
"text",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"text",
"=",
"value",
".",
"strip",
"(",
")",
"# Result is a list",
"result",
"=",
"[",
"]",
"# If value starts with '(' assume a list of pairs",
"if",
"text",
".",
"startswith",
"(",
"'('",
")",
":",
"tokens",
"=",
"text",
".",
"split",
"(",
"','",
")",
"if",
"len",
"(",
"tokens",
")",
"%",
"2",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'not a valid list of pairs'",
")",
"pos",
"=",
"0",
"while",
"(",
"pos",
"<",
"len",
"(",
"tokens",
")",
")",
":",
"val1",
"=",
"float",
"(",
"tokens",
"[",
"pos",
"]",
".",
"strip",
"(",
")",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
")",
"val2",
"=",
"float",
"(",
"tokens",
"[",
"pos",
"+",
"1",
"]",
".",
"strip",
"(",
")",
"[",
":",
"-",
"1",
"]",
")",
"result",
".",
"append",
"(",
"(",
"val1",
",",
"val2",
")",
")",
"pos",
"+=",
"2",
"else",
":",
"for",
"val",
"in",
"text",
".",
"split",
"(",
"','",
")",
":",
"result",
".",
"append",
"(",
"float",
"(",
"val",
")",
")",
"# Ensure that the result contains at least two elements",
"if",
"len",
"(",
"result",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'invalid number of elements in list: '",
"+",
"str",
"(",
"len",
"(",
"result",
")",
")",
")",
"return",
"result"
] |
Convert string to list.
|
[
"Convert",
"string",
"to",
"list",
"."
] |
7180a6b51150667e47629da566aedaa742e39342
|
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/attribute.py#L329-L355
|
246,273 |
minhhoit/yacms
|
yacms/generic/managers.py
|
KeywordManager.get_or_create_iexact
|
def get_or_create_iexact(self, **kwargs):
"""
Case insensitive title version of ``get_or_create``. Also
allows for multiple existing results.
"""
lookup = dict(**kwargs)
try:
lookup["title__iexact"] = lookup.pop("title")
except KeyError:
pass
try:
return self.filter(**lookup)[0], False
except IndexError:
return self.create(**kwargs), True
|
python
|
def get_or_create_iexact(self, **kwargs):
"""
Case insensitive title version of ``get_or_create``. Also
allows for multiple existing results.
"""
lookup = dict(**kwargs)
try:
lookup["title__iexact"] = lookup.pop("title")
except KeyError:
pass
try:
return self.filter(**lookup)[0], False
except IndexError:
return self.create(**kwargs), True
|
[
"def",
"get_or_create_iexact",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"lookup",
"=",
"dict",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"lookup",
"[",
"\"title__iexact\"",
"]",
"=",
"lookup",
".",
"pop",
"(",
"\"title\"",
")",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"filter",
"(",
"*",
"*",
"lookup",
")",
"[",
"0",
"]",
",",
"False",
"except",
"IndexError",
":",
"return",
"self",
".",
"create",
"(",
"*",
"*",
"kwargs",
")",
",",
"True"
] |
Case insensitive title version of ``get_or_create``. Also
allows for multiple existing results.
|
[
"Case",
"insensitive",
"title",
"version",
"of",
"get_or_create",
".",
"Also",
"allows",
"for",
"multiple",
"existing",
"results",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/managers.py#L46-L59
|
246,274 |
minhhoit/yacms
|
yacms/generic/managers.py
|
KeywordManager.delete_unused
|
def delete_unused(self, keyword_ids=None):
"""
Removes all instances that are not assigned to any object. Limits
processing to ``keyword_ids`` if given.
"""
if keyword_ids is None:
keywords = self.all()
else:
keywords = self.filter(id__in=keyword_ids)
keywords.filter(assignments__isnull=True).delete()
|
python
|
def delete_unused(self, keyword_ids=None):
"""
Removes all instances that are not assigned to any object. Limits
processing to ``keyword_ids`` if given.
"""
if keyword_ids is None:
keywords = self.all()
else:
keywords = self.filter(id__in=keyword_ids)
keywords.filter(assignments__isnull=True).delete()
|
[
"def",
"delete_unused",
"(",
"self",
",",
"keyword_ids",
"=",
"None",
")",
":",
"if",
"keyword_ids",
"is",
"None",
":",
"keywords",
"=",
"self",
".",
"all",
"(",
")",
"else",
":",
"keywords",
"=",
"self",
".",
"filter",
"(",
"id__in",
"=",
"keyword_ids",
")",
"keywords",
".",
"filter",
"(",
"assignments__isnull",
"=",
"True",
")",
".",
"delete",
"(",
")"
] |
Removes all instances that are not assigned to any object. Limits
processing to ``keyword_ids`` if given.
|
[
"Removes",
"all",
"instances",
"that",
"are",
"not",
"assigned",
"to",
"any",
"object",
".",
"Limits",
"processing",
"to",
"keyword_ids",
"if",
"given",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/managers.py#L61-L70
|
246,275 |
hirokiky/uiro
|
uiro/template.py
|
setup_lookup
|
def setup_lookup(apps, lookup_class=TemplateLookup):
""" Registering template directories of apps to Lookup.
Lookups will be set up as dictionary, app name
as key and lookup for this app will be it's value.
Each lookups is correspond to each template directories of apps._lookups.
The directory should be named 'templates', and put under app directory.
"""
global _lookups
_lookups = {}
for app in apps:
app_template_dir = os.path.join(os.path.dirname(app.__file__),
'templates')
app_lookup = lookup_class(directories=[app_template_dir],
output_encoding='utf-8',
encoding_errors='replace')
_lookups[app.__name__] = app_lookup
|
python
|
def setup_lookup(apps, lookup_class=TemplateLookup):
""" Registering template directories of apps to Lookup.
Lookups will be set up as dictionary, app name
as key and lookup for this app will be it's value.
Each lookups is correspond to each template directories of apps._lookups.
The directory should be named 'templates', and put under app directory.
"""
global _lookups
_lookups = {}
for app in apps:
app_template_dir = os.path.join(os.path.dirname(app.__file__),
'templates')
app_lookup = lookup_class(directories=[app_template_dir],
output_encoding='utf-8',
encoding_errors='replace')
_lookups[app.__name__] = app_lookup
|
[
"def",
"setup_lookup",
"(",
"apps",
",",
"lookup_class",
"=",
"TemplateLookup",
")",
":",
"global",
"_lookups",
"_lookups",
"=",
"{",
"}",
"for",
"app",
"in",
"apps",
":",
"app_template_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"app",
".",
"__file__",
")",
",",
"'templates'",
")",
"app_lookup",
"=",
"lookup_class",
"(",
"directories",
"=",
"[",
"app_template_dir",
"]",
",",
"output_encoding",
"=",
"'utf-8'",
",",
"encoding_errors",
"=",
"'replace'",
")",
"_lookups",
"[",
"app",
".",
"__name__",
"]",
"=",
"app_lookup"
] |
Registering template directories of apps to Lookup.
Lookups will be set up as dictionary, app name
as key and lookup for this app will be it's value.
Each lookups is correspond to each template directories of apps._lookups.
The directory should be named 'templates', and put under app directory.
|
[
"Registering",
"template",
"directories",
"of",
"apps",
"to",
"Lookup",
"."
] |
8436976b21ac9b0eac4243768f5ada12479b9e00
|
https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/template.py#L8-L25
|
246,276 |
hirokiky/uiro
|
uiro/template.py
|
get_app_template
|
def get_app_template(name):
""" Getter function of templates for each applications.
Argument `name` will be interpreted as colon separated, the left value
means application name, right value means a template name.
get_app_template('blog:dashboarb.mako')
It will return a template for dashboard page of `blog` application.
"""
app_name, template_name = name.split(':')
return get_lookups()[app_name].get_template(template_name)
|
python
|
def get_app_template(name):
""" Getter function of templates for each applications.
Argument `name` will be interpreted as colon separated, the left value
means application name, right value means a template name.
get_app_template('blog:dashboarb.mako')
It will return a template for dashboard page of `blog` application.
"""
app_name, template_name = name.split(':')
return get_lookups()[app_name].get_template(template_name)
|
[
"def",
"get_app_template",
"(",
"name",
")",
":",
"app_name",
",",
"template_name",
"=",
"name",
".",
"split",
"(",
"':'",
")",
"return",
"get_lookups",
"(",
")",
"[",
"app_name",
"]",
".",
"get_template",
"(",
"template_name",
")"
] |
Getter function of templates for each applications.
Argument `name` will be interpreted as colon separated, the left value
means application name, right value means a template name.
get_app_template('blog:dashboarb.mako')
It will return a template for dashboard page of `blog` application.
|
[
"Getter",
"function",
"of",
"templates",
"for",
"each",
"applications",
"."
] |
8436976b21ac9b0eac4243768f5ada12479b9e00
|
https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/template.py#L38-L49
|
246,277 |
ActiveState/simplealchemy
|
simplealchemy.py
|
setup
|
def setup(db_class, simple_object_cls, primary_keys):
"""A simple API to configure the metadata"""
table_name = simple_object_cls.__name__
column_names = simple_object_cls.FIELDS
metadata = MetaData()
table = Table(table_name, metadata,
*[Column(cname, _get_best_column_type(cname),
primary_key=cname in primary_keys)
for cname in column_names])
db_class.metadata = metadata
db_class.mapper_class = simple_object_cls
db_class.table = table
mapper(simple_object_cls, table)
|
python
|
def setup(db_class, simple_object_cls, primary_keys):
"""A simple API to configure the metadata"""
table_name = simple_object_cls.__name__
column_names = simple_object_cls.FIELDS
metadata = MetaData()
table = Table(table_name, metadata,
*[Column(cname, _get_best_column_type(cname),
primary_key=cname in primary_keys)
for cname in column_names])
db_class.metadata = metadata
db_class.mapper_class = simple_object_cls
db_class.table = table
mapper(simple_object_cls, table)
|
[
"def",
"setup",
"(",
"db_class",
",",
"simple_object_cls",
",",
"primary_keys",
")",
":",
"table_name",
"=",
"simple_object_cls",
".",
"__name__",
"column_names",
"=",
"simple_object_cls",
".",
"FIELDS",
"metadata",
"=",
"MetaData",
"(",
")",
"table",
"=",
"Table",
"(",
"table_name",
",",
"metadata",
",",
"*",
"[",
"Column",
"(",
"cname",
",",
"_get_best_column_type",
"(",
"cname",
")",
",",
"primary_key",
"=",
"cname",
"in",
"primary_keys",
")",
"for",
"cname",
"in",
"column_names",
"]",
")",
"db_class",
".",
"metadata",
"=",
"metadata",
"db_class",
".",
"mapper_class",
"=",
"simple_object_cls",
"db_class",
".",
"table",
"=",
"table",
"mapper",
"(",
"simple_object_cls",
",",
"table",
")"
] |
A simple API to configure the metadata
|
[
"A",
"simple",
"API",
"to",
"configure",
"the",
"metadata"
] |
f745847793f57701776a804ec74791a1f6a66947
|
https://github.com/ActiveState/simplealchemy/blob/f745847793f57701776a804ec74791a1f6a66947/simplealchemy.py#L26-L41
|
246,278 |
ActiveState/simplealchemy
|
simplealchemy.py
|
sqlalchemy_escape
|
def sqlalchemy_escape(val, escape_char, special_chars):
"""Escape a string according for use in LIKE operator
>>> sqlalchemy_escape("text_table", "\\", "%_")
'text\_table'
"""
if sys.version_info[:2] >= (3, 0):
assert isinstance(val, str)
else:
assert isinstance(val, basestring)
result = []
for c in val:
if c in special_chars + escape_char:
result.extend(escape_char + c)
else:
result.extend(c)
return ''.join(result)
|
python
|
def sqlalchemy_escape(val, escape_char, special_chars):
"""Escape a string according for use in LIKE operator
>>> sqlalchemy_escape("text_table", "\\", "%_")
'text\_table'
"""
if sys.version_info[:2] >= (3, 0):
assert isinstance(val, str)
else:
assert isinstance(val, basestring)
result = []
for c in val:
if c in special_chars + escape_char:
result.extend(escape_char + c)
else:
result.extend(c)
return ''.join(result)
|
[
"def",
"sqlalchemy_escape",
"(",
"val",
",",
"escape_char",
",",
"special_chars",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
">=",
"(",
"3",
",",
"0",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"str",
")",
"else",
":",
"assert",
"isinstance",
"(",
"val",
",",
"basestring",
")",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"val",
":",
"if",
"c",
"in",
"special_chars",
"+",
"escape_char",
":",
"result",
".",
"extend",
"(",
"escape_char",
"+",
"c",
")",
"else",
":",
"result",
".",
"extend",
"(",
"c",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] |
Escape a string according for use in LIKE operator
>>> sqlalchemy_escape("text_table", "\\", "%_")
'text\_table'
|
[
"Escape",
"a",
"string",
"according",
"for",
"use",
"in",
"LIKE",
"operator"
] |
f745847793f57701776a804ec74791a1f6a66947
|
https://github.com/ActiveState/simplealchemy/blob/f745847793f57701776a804ec74791a1f6a66947/simplealchemy.py#L44-L60
|
246,279 |
ActiveState/simplealchemy
|
simplealchemy.py
|
_remove_unicode_keys
|
def _remove_unicode_keys(dictobj):
"""Convert keys from 'unicode' to 'str' type.
workaround for <http://bugs.python.org/issue2646>
"""
if sys.version_info[:2] >= (3, 0): return dictobj
assert isinstance(dictobj, dict)
newdict = {}
for key, value in dictobj.items():
if type(key) is unicode:
key = key.encode('utf-8')
newdict[key] = value
return newdict
|
python
|
def _remove_unicode_keys(dictobj):
"""Convert keys from 'unicode' to 'str' type.
workaround for <http://bugs.python.org/issue2646>
"""
if sys.version_info[:2] >= (3, 0): return dictobj
assert isinstance(dictobj, dict)
newdict = {}
for key, value in dictobj.items():
if type(key) is unicode:
key = key.encode('utf-8')
newdict[key] = value
return newdict
|
[
"def",
"_remove_unicode_keys",
"(",
"dictobj",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
">=",
"(",
"3",
",",
"0",
")",
":",
"return",
"dictobj",
"assert",
"isinstance",
"(",
"dictobj",
",",
"dict",
")",
"newdict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"dictobj",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"key",
")",
"is",
"unicode",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"newdict",
"[",
"key",
"]",
"=",
"value",
"return",
"newdict"
] |
Convert keys from 'unicode' to 'str' type.
workaround for <http://bugs.python.org/issue2646>
|
[
"Convert",
"keys",
"from",
"unicode",
"to",
"str",
"type",
"."
] |
f745847793f57701776a804ec74791a1f6a66947
|
https://github.com/ActiveState/simplealchemy/blob/f745847793f57701776a804ec74791a1f6a66947/simplealchemy.py#L239-L253
|
246,280 |
ActiveState/simplealchemy
|
simplealchemy.py
|
SimpleDatabase.reset
|
def reset(self):
"""Reset the database
Drop all tables and recreate them
"""
self.metadata.drop_all(self.engine)
self.metadata.create_all(self.engine)
|
python
|
def reset(self):
"""Reset the database
Drop all tables and recreate them
"""
self.metadata.drop_all(self.engine)
self.metadata.create_all(self.engine)
|
[
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"metadata",
".",
"drop_all",
"(",
"self",
".",
"engine",
")",
"self",
".",
"metadata",
".",
"create_all",
"(",
"self",
".",
"engine",
")"
] |
Reset the database
Drop all tables and recreate them
|
[
"Reset",
"the",
"database"
] |
f745847793f57701776a804ec74791a1f6a66947
|
https://github.com/ActiveState/simplealchemy/blob/f745847793f57701776a804ec74791a1f6a66947/simplealchemy.py#L95-L101
|
246,281 |
ActiveState/simplealchemy
|
simplealchemy.py
|
SimpleDatabase.transaction
|
def transaction(self, session=None):
"""Start a new transaction based on the passed session object. If session
is not passed, then create one and make sure of closing it finally.
"""
local_session = None
if session is None:
local_session = session = self.create_scoped_session()
try:
yield session
finally:
# Since ``local_session`` was created locally, close it here itself
if local_session is not None:
# but wait!
# http://groups.google.com/group/sqlalchemy/browse_thread/thread/7c1eb642435adde7
# To workaround this issue with sqlalchemy, we can either:
# 1) pass the session object explicitly
# 2) do not close the session at all (bad idea - could lead to memory leaks)
#
# Till pypm implements atomic transations in client.installer,
# we retain this hack (i.e., we choose (2) for now)
pass
|
python
|
def transaction(self, session=None):
"""Start a new transaction based on the passed session object. If session
is not passed, then create one and make sure of closing it finally.
"""
local_session = None
if session is None:
local_session = session = self.create_scoped_session()
try:
yield session
finally:
# Since ``local_session`` was created locally, close it here itself
if local_session is not None:
# but wait!
# http://groups.google.com/group/sqlalchemy/browse_thread/thread/7c1eb642435adde7
# To workaround this issue with sqlalchemy, we can either:
# 1) pass the session object explicitly
# 2) do not close the session at all (bad idea - could lead to memory leaks)
#
# Till pypm implements atomic transations in client.installer,
# we retain this hack (i.e., we choose (2) for now)
pass
|
[
"def",
"transaction",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"local_session",
"=",
"None",
"if",
"session",
"is",
"None",
":",
"local_session",
"=",
"session",
"=",
"self",
".",
"create_scoped_session",
"(",
")",
"try",
":",
"yield",
"session",
"finally",
":",
"# Since ``local_session`` was created locally, close it here itself",
"if",
"local_session",
"is",
"not",
"None",
":",
"# but wait!",
"# http://groups.google.com/group/sqlalchemy/browse_thread/thread/7c1eb642435adde7",
"# To workaround this issue with sqlalchemy, we can either:",
"# 1) pass the session object explicitly",
"# 2) do not close the session at all (bad idea - could lead to memory leaks)",
"#",
"# Till pypm implements atomic transations in client.installer,",
"# we retain this hack (i.e., we choose (2) for now)",
"pass"
] |
Start a new transaction based on the passed session object. If session
is not passed, then create one and make sure of closing it finally.
|
[
"Start",
"a",
"new",
"transaction",
"based",
"on",
"the",
"passed",
"session",
"object",
".",
"If",
"session",
"is",
"not",
"passed",
"then",
"create",
"one",
"and",
"make",
"sure",
"of",
"closing",
"it",
"finally",
"."
] |
f745847793f57701776a804ec74791a1f6a66947
|
https://github.com/ActiveState/simplealchemy/blob/f745847793f57701776a804ec74791a1f6a66947/simplealchemy.py#L107-L127
|
246,282 |
ActiveState/simplealchemy
|
simplealchemy.py
|
SimpleObject.create_from
|
def create_from(cls, another, **kwargs):
"""Create from another object of different type.
Another object must be from a derived class of SimpleObject (which
contains FIELDS)
"""
reused_fields = {}
for field, value in another.get_fields():
if field in cls.FIELDS:
reused_fields[field] = value
reused_fields.update(kwargs)
return cls(**reused_fields)
|
python
|
def create_from(cls, another, **kwargs):
"""Create from another object of different type.
Another object must be from a derived class of SimpleObject (which
contains FIELDS)
"""
reused_fields = {}
for field, value in another.get_fields():
if field in cls.FIELDS:
reused_fields[field] = value
reused_fields.update(kwargs)
return cls(**reused_fields)
|
[
"def",
"create_from",
"(",
"cls",
",",
"another",
",",
"*",
"*",
"kwargs",
")",
":",
"reused_fields",
"=",
"{",
"}",
"for",
"field",
",",
"value",
"in",
"another",
".",
"get_fields",
"(",
")",
":",
"if",
"field",
"in",
"cls",
".",
"FIELDS",
":",
"reused_fields",
"[",
"field",
"]",
"=",
"value",
"reused_fields",
".",
"update",
"(",
"kwargs",
")",
"return",
"cls",
"(",
"*",
"*",
"reused_fields",
")"
] |
Create from another object of different type.
Another object must be from a derived class of SimpleObject (which
contains FIELDS)
|
[
"Create",
"from",
"another",
"object",
"of",
"different",
"type",
"."
] |
f745847793f57701776a804ec74791a1f6a66947
|
https://github.com/ActiveState/simplealchemy/blob/f745847793f57701776a804ec74791a1f6a66947/simplealchemy.py#L154-L165
|
246,283 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.brightness
|
def brightness(sequence_number, brightness):
"""Create a brightness message"""
return MessageWriter().string("brightness").uint64(sequence_number).uint8(int(brightness*255)).get()
|
python
|
def brightness(sequence_number, brightness):
"""Create a brightness message"""
return MessageWriter().string("brightness").uint64(sequence_number).uint8(int(brightness*255)).get()
|
[
"def",
"brightness",
"(",
"sequence_number",
",",
"brightness",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"brightness\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint8",
"(",
"int",
"(",
"brightness",
"*",
"255",
")",
")",
".",
"get",
"(",
")"
] |
Create a brightness message
|
[
"Create",
"a",
"brightness",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L11-L13
|
246,284 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.mainswitch_state
|
def mainswitch_state(sequence_number, state):
"""Create a mainswitch.state message"""
return MessageWriter().string("mainswitch.state").uint64(sequence_number).bool(state).get()
|
python
|
def mainswitch_state(sequence_number, state):
"""Create a mainswitch.state message"""
return MessageWriter().string("mainswitch.state").uint64(sequence_number).bool(state).get()
|
[
"def",
"mainswitch_state",
"(",
"sequence_number",
",",
"state",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"mainswitch.state\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"bool",
"(",
"state",
")",
".",
"get",
"(",
")"
] |
Create a mainswitch.state message
|
[
"Create",
"a",
"mainswitch",
".",
"state",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L15-L17
|
246,285 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.animation_add
|
def animation_add(sequence_number, animation_id, name):
"""Create a animation.add message"""
return MessageWriter().string("animation.add").uint64(sequence_number).uint32(animation_id).string(name).get()
|
python
|
def animation_add(sequence_number, animation_id, name):
"""Create a animation.add message"""
return MessageWriter().string("animation.add").uint64(sequence_number).uint32(animation_id).string(name).get()
|
[
"def",
"animation_add",
"(",
"sequence_number",
",",
"animation_id",
",",
"name",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"animation.add\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"animation_id",
")",
".",
"string",
"(",
"name",
")",
".",
"get",
"(",
")"
] |
Create a animation.add message
|
[
"Create",
"a",
"animation",
".",
"add",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L19-L21
|
246,286 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_active
|
def scene_active(sequence_number, scene_id):
"""Create a scene.setactive message"""
return MessageWriter().string("scene.setactive").uint64(sequence_number).uint32(scene_id).get()
|
python
|
def scene_active(sequence_number, scene_id):
"""Create a scene.setactive message"""
return MessageWriter().string("scene.setactive").uint64(sequence_number).uint32(scene_id).get()
|
[
"def",
"scene_active",
"(",
"sequence_number",
",",
"scene_id",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.setactive\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"get",
"(",
")"
] |
Create a scene.setactive message
|
[
"Create",
"a",
"scene",
".",
"setactive",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L23-L25
|
246,287 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_add
|
def scene_add(sequence_number, scene_id, animation_id, name, color, velocity, config):
"""Create a scene.add message"""
(red, green, blue) = (int(color[0]*255), int(color[1]*255), int(color[2]*255))
return MessageWriter().string("scene.add").uint64(sequence_number).uint32(scene_id).uint32(animation_id).string(name) \
.uint8_3(red, green, blue).uint32(int(velocity * 1000)).string(config).get()
|
python
|
def scene_add(sequence_number, scene_id, animation_id, name, color, velocity, config):
"""Create a scene.add message"""
(red, green, blue) = (int(color[0]*255), int(color[1]*255), int(color[2]*255))
return MessageWriter().string("scene.add").uint64(sequence_number).uint32(scene_id).uint32(animation_id).string(name) \
.uint8_3(red, green, blue).uint32(int(velocity * 1000)).string(config).get()
|
[
"def",
"scene_add",
"(",
"sequence_number",
",",
"scene_id",
",",
"animation_id",
",",
"name",
",",
"color",
",",
"velocity",
",",
"config",
")",
":",
"(",
"red",
",",
"green",
",",
"blue",
")",
"=",
"(",
"int",
"(",
"color",
"[",
"0",
"]",
"*",
"255",
")",
",",
"int",
"(",
"color",
"[",
"1",
"]",
"*",
"255",
")",
",",
"int",
"(",
"color",
"[",
"2",
"]",
"*",
"255",
")",
")",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.add\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"uint32",
"(",
"animation_id",
")",
".",
"string",
"(",
"name",
")",
".",
"uint8_3",
"(",
"red",
",",
"green",
",",
"blue",
")",
".",
"uint32",
"(",
"int",
"(",
"velocity",
"*",
"1000",
")",
")",
".",
"string",
"(",
"config",
")",
".",
"get",
"(",
")"
] |
Create a scene.add message
|
[
"Create",
"a",
"scene",
".",
"add",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L27-L31
|
246,288 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_remove
|
def scene_remove(sequence_number, scene_id):
"""Create a scene.rm message"""
return MessageWriter().string("scene.rm").uint64(sequence_number).uint32(scene_id).get()
|
python
|
def scene_remove(sequence_number, scene_id):
"""Create a scene.rm message"""
return MessageWriter().string("scene.rm").uint64(sequence_number).uint32(scene_id).get()
|
[
"def",
"scene_remove",
"(",
"sequence_number",
",",
"scene_id",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.rm\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"get",
"(",
")"
] |
Create a scene.rm message
|
[
"Create",
"a",
"scene",
".",
"rm",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L33-L35
|
246,289 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_name
|
def scene_name(sequence_number, scene_id, name):
"""Create a scene.name message"""
return MessageWriter().string("scene.name").uint64(sequence_number).uint32(scene_id).string(name).get()
|
python
|
def scene_name(sequence_number, scene_id, name):
"""Create a scene.name message"""
return MessageWriter().string("scene.name").uint64(sequence_number).uint32(scene_id).string(name).get()
|
[
"def",
"scene_name",
"(",
"sequence_number",
",",
"scene_id",
",",
"name",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.name\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"string",
"(",
"name",
")",
".",
"get",
"(",
")"
] |
Create a scene.name message
|
[
"Create",
"a",
"scene",
".",
"name",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L37-L39
|
246,290 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_config
|
def scene_config(sequence_number, scene_id, config):
"""Create a scene.config message"""
return MessageWriter().string("scene.config").uint64(sequence_number).uint32(scene_id).string(config).get()
|
python
|
def scene_config(sequence_number, scene_id, config):
"""Create a scene.config message"""
return MessageWriter().string("scene.config").uint64(sequence_number).uint32(scene_id).string(config).get()
|
[
"def",
"scene_config",
"(",
"sequence_number",
",",
"scene_id",
",",
"config",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.config\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"string",
"(",
"config",
")",
".",
"get",
"(",
")"
] |
Create a scene.config message
|
[
"Create",
"a",
"scene",
".",
"config",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L41-L43
|
246,291 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_color
|
def scene_color(sequence_number, scene_id, color):
"""Create a scene.color message"""
return MessageWriter().string("scene.color").uint64(sequence_number).uint32(scene_id) \
.uint8_3(int(color[0]*255), int(color[1]*255), int(color[2]*255)).get()
|
python
|
def scene_color(sequence_number, scene_id, color):
"""Create a scene.color message"""
return MessageWriter().string("scene.color").uint64(sequence_number).uint32(scene_id) \
.uint8_3(int(color[0]*255), int(color[1]*255), int(color[2]*255)).get()
|
[
"def",
"scene_color",
"(",
"sequence_number",
",",
"scene_id",
",",
"color",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.color\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"uint8_3",
"(",
"int",
"(",
"color",
"[",
"0",
"]",
"*",
"255",
")",
",",
"int",
"(",
"color",
"[",
"1",
"]",
"*",
"255",
")",
",",
"int",
"(",
"color",
"[",
"2",
"]",
"*",
"255",
")",
")",
".",
"get",
"(",
")"
] |
Create a scene.color message
|
[
"Create",
"a",
"scene",
".",
"color",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L45-L48
|
246,292 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageBuilder.scene_velocity
|
def scene_velocity(sequence_number, scene_id, velocity):
"""Create a scene.velocity message"""
return MessageWriter().string("scene.velocity").uint64(sequence_number).uint32(scene_id).uint32(int(velocity*1000)).get()
|
python
|
def scene_velocity(sequence_number, scene_id, velocity):
"""Create a scene.velocity message"""
return MessageWriter().string("scene.velocity").uint64(sequence_number).uint32(scene_id).uint32(int(velocity*1000)).get()
|
[
"def",
"scene_velocity",
"(",
"sequence_number",
",",
"scene_id",
",",
"velocity",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.velocity\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"uint32",
"(",
"int",
"(",
"velocity",
"*",
"1000",
")",
")",
".",
"get",
"(",
")"
] |
Create a scene.velocity message
|
[
"Create",
"a",
"scene",
".",
"velocity",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L50-L52
|
246,293 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageWriter.uint8
|
def uint8(self, val):
"""append a frame containing a uint8"""
try:
self.msg += [pack("B", val)]
except struct.error:
raise ValueError("Expected uint32")
return self
|
python
|
def uint8(self, val):
"""append a frame containing a uint8"""
try:
self.msg += [pack("B", val)]
except struct.error:
raise ValueError("Expected uint32")
return self
|
[
"def",
"uint8",
"(",
"self",
",",
"val",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"B\"",
",",
"val",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
"ValueError",
"(",
"\"Expected uint32\"",
")",
"return",
"self"
] |
append a frame containing a uint8
|
[
"append",
"a",
"frame",
"containing",
"a",
"uint8"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L72-L78
|
246,294 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageWriter.uint8_3
|
def uint8_3(self, val1, val2, val3):
"""append a frame containing 3 uint8"""
try:
self.msg += [pack("BBB", val1, val2, val3)]
except struct.error:
raise ValueError("Expected uint8")
return self
|
python
|
def uint8_3(self, val1, val2, val3):
"""append a frame containing 3 uint8"""
try:
self.msg += [pack("BBB", val1, val2, val3)]
except struct.error:
raise ValueError("Expected uint8")
return self
|
[
"def",
"uint8_3",
"(",
"self",
",",
"val1",
",",
"val2",
",",
"val3",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"BBB\"",
",",
"val1",
",",
"val2",
",",
"val3",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
"ValueError",
"(",
"\"Expected uint8\"",
")",
"return",
"self"
] |
append a frame containing 3 uint8
|
[
"append",
"a",
"frame",
"containing",
"3",
"uint8"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L79-L85
|
246,295 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageWriter.uint32
|
def uint32(self, val):
"""append a frame containing a uint32"""
try:
self.msg += [pack("!I", val)]
except struct.error:
raise ValueError("Expected uint32")
return self
|
python
|
def uint32(self, val):
"""append a frame containing a uint32"""
try:
self.msg += [pack("!I", val)]
except struct.error:
raise ValueError("Expected uint32")
return self
|
[
"def",
"uint32",
"(",
"self",
",",
"val",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"!I\"",
",",
"val",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
"ValueError",
"(",
"\"Expected uint32\"",
")",
"return",
"self"
] |
append a frame containing a uint32
|
[
"append",
"a",
"frame",
"containing",
"a",
"uint32"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L86-L92
|
246,296 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageWriter.uint64
|
def uint64(self, val):
"""append a frame containing a uint64"""
try:
self.msg += [pack("!Q", val)]
except struct.error:
raise ValueError("Expected uint64")
return self
|
python
|
def uint64(self, val):
"""append a frame containing a uint64"""
try:
self.msg += [pack("!Q", val)]
except struct.error:
raise ValueError("Expected uint64")
return self
|
[
"def",
"uint64",
"(",
"self",
",",
"val",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"!Q\"",
",",
"val",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
"ValueError",
"(",
"\"Expected uint64\"",
")",
"return",
"self"
] |
append a frame containing a uint64
|
[
"append",
"a",
"frame",
"containing",
"a",
"uint64"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L93-L99
|
246,297 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageParser.brightness
|
def brightness(frames):
"""parse a brightness message"""
reader = MessageReader(frames)
res = reader.string("command").uint32("brightness").assert_end().get()
if res.command != "brightness":
raise MessageParserError("Command is not 'brightness'")
return (res.brightness/1000,)
|
python
|
def brightness(frames):
"""parse a brightness message"""
reader = MessageReader(frames)
res = reader.string("command").uint32("brightness").assert_end().get()
if res.command != "brightness":
raise MessageParserError("Command is not 'brightness'")
return (res.brightness/1000,)
|
[
"def",
"brightness",
"(",
"frames",
")",
":",
"reader",
"=",
"MessageReader",
"(",
"frames",
")",
"res",
"=",
"reader",
".",
"string",
"(",
"\"command\"",
")",
".",
"uint32",
"(",
"\"brightness\"",
")",
".",
"assert_end",
"(",
")",
".",
"get",
"(",
")",
"if",
"res",
".",
"command",
"!=",
"\"brightness\"",
":",
"raise",
"MessageParserError",
"(",
"\"Command is not 'brightness'\"",
")",
"return",
"(",
"res",
".",
"brightness",
"/",
"1000",
",",
")"
] |
parse a brightness message
|
[
"parse",
"a",
"brightness",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L108-L114
|
246,298 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageParser.mainswitch_state
|
def mainswitch_state(frames):
"""parse a mainswitch.state message"""
reader = MessageReader(frames)
res = reader.string("command").bool("state").assert_end().get()
if res.command != "mainswitch.state":
raise MessageParserError("Command is not 'mainswitch.state'")
return (res.state,)
|
python
|
def mainswitch_state(frames):
"""parse a mainswitch.state message"""
reader = MessageReader(frames)
res = reader.string("command").bool("state").assert_end().get()
if res.command != "mainswitch.state":
raise MessageParserError("Command is not 'mainswitch.state'")
return (res.state,)
|
[
"def",
"mainswitch_state",
"(",
"frames",
")",
":",
"reader",
"=",
"MessageReader",
"(",
"frames",
")",
"res",
"=",
"reader",
".",
"string",
"(",
"\"command\"",
")",
".",
"bool",
"(",
"\"state\"",
")",
".",
"assert_end",
"(",
")",
".",
"get",
"(",
")",
"if",
"res",
".",
"command",
"!=",
"\"mainswitch.state\"",
":",
"raise",
"MessageParserError",
"(",
"\"Command is not 'mainswitch.state'\"",
")",
"return",
"(",
"res",
".",
"state",
",",
")"
] |
parse a mainswitch.state message
|
[
"parse",
"a",
"mainswitch",
".",
"state",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L117-L123
|
246,299 |
zaturox/glin
|
glin/zmq/messages.py
|
MessageParser.scene_add
|
def scene_add(frames):
"""parse a scene.add message"""
reader = MessageReader(frames)
results = reader.string("command").uint32("animation_id").string("name").uint8_3("color").uint32("velocity").string("config").get()
if results.command != "scene.add":
raise MessageParserError("Command is not 'scene.add'")
return (results.animation_id, results.name, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]),
results.velocity/1000, results.config)
|
python
|
def scene_add(frames):
"""parse a scene.add message"""
reader = MessageReader(frames)
results = reader.string("command").uint32("animation_id").string("name").uint8_3("color").uint32("velocity").string("config").get()
if results.command != "scene.add":
raise MessageParserError("Command is not 'scene.add'")
return (results.animation_id, results.name, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]),
results.velocity/1000, results.config)
|
[
"def",
"scene_add",
"(",
"frames",
")",
":",
"reader",
"=",
"MessageReader",
"(",
"frames",
")",
"results",
"=",
"reader",
".",
"string",
"(",
"\"command\"",
")",
".",
"uint32",
"(",
"\"animation_id\"",
")",
".",
"string",
"(",
"\"name\"",
")",
".",
"uint8_3",
"(",
"\"color\"",
")",
".",
"uint32",
"(",
"\"velocity\"",
")",
".",
"string",
"(",
"\"config\"",
")",
".",
"get",
"(",
")",
"if",
"results",
".",
"command",
"!=",
"\"scene.add\"",
":",
"raise",
"MessageParserError",
"(",
"\"Command is not 'scene.add'\"",
")",
"return",
"(",
"results",
".",
"animation_id",
",",
"results",
".",
"name",
",",
"np",
".",
"array",
"(",
"[",
"results",
".",
"color",
"[",
"0",
"]",
"/",
"255",
",",
"results",
".",
"color",
"[",
"1",
"]",
"/",
"255",
",",
"results",
".",
"color",
"[",
"2",
"]",
"/",
"255",
"]",
")",
",",
"results",
".",
"velocity",
"/",
"1000",
",",
"results",
".",
"config",
")"
] |
parse a scene.add message
|
[
"parse",
"a",
"scene",
".",
"add",
"message"
] |
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
|
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L126-L133
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.