code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# whether the script is visible
self.grid_script._widget.setVisible(self.button_script.get_value())
# whether we should be able to edit it.
if not self.combo_autoscript.get_index()==0: self.script.disable()
else: self.script.enabl... | def _synchronize_controls(self) | Updates the gui based on button configs. | 11.460652 | 10.378679 | 1.10425 |
# multi plot, right number of plots and curves = great!
if self.button_multi.is_checked() \
and len(self._curves) == len(self.plot_widgets) \
and len(self._curves) == n: return
# single plot, right number of curves = great!
if not self.button_mult... | def _set_number_of_plots(self, n) | Adjusts number of plots & curves to the desired value the gui. | 3.331403 | 3.28873 | 1.012976 |
# no axes to link!
if len(self.plot_widgets) <= 1: return
# get the first plotItem
a = self.plot_widgets[0].plotItem.getViewBox()
# now loop through all the axes and link / unlink the axes
for n in range(1,len(self.plot_widgets)):
... | def _update_linked_axes(self) | Loops over the axes and links / unlinks them. | 4.430912 | 4.23739 | 1.04567 |
if name in self.const_specs:
return self.const_specs[name].link(self)
if '.' in name:
include_name, component = name.split('.', 1)
if include_name in self.included_scopes:
return self.included_scopes[include_name].resolve_const_spec(
... | def resolve_const_spec(self, name, lineno) | Finds and links the ConstSpec with the given name. | 3.665476 | 3.385738 | 1.082622 |
if name in self.type_specs:
return self.type_specs[name].link(self)
if '.' in name:
include_name, component = name.split('.', 1)
if include_name in self.included_scopes:
return self.included_scopes[include_name].resolve_type_spec(
... | def resolve_type_spec(self, name, lineno) | Finds and links the TypeSpec with the given name. | 3.62125 | 3.440767 | 1.052454 |
if name in self.service_specs:
return self.service_specs[name].link(self)
if '.' in name:
include_name, component = name.split('.', 2)
if include_name in self.included_scopes:
return self.included_scopes[
include_name
... | def resolve_service_spec(self, name, lineno) | Finds and links the ServiceSpec with the given name. | 3.982422 | 3.736913 | 1.065698 |
# The compiler already ensures this. If we still get here with a
# conflict, that's a bug.
assert name not in self.included_scopes
self.included_scopes[name] = included_scope
self.add_surface(name, module) | def add_include(self, name, included_scope, module) | Register an imported module into this scope.
Raises ``ThriftCompilerError`` if the name has already been used. | 7.223856 | 8.144806 | 0.886928 |
assert service_spec is not None
if service_spec.name in self.service_specs:
raise ThriftCompilerError(
'Cannot define service "%s". That name is already taken.'
% service_spec.name
)
self.service_specs[service_spec.name] = service... | def add_service_spec(self, service_spec) | Registers the given ``ServiceSpec`` into the scope.
Raises ``ThriftCompilerError`` if the name has already been used. | 3.432147 | 2.804315 | 1.22388 |
if const_spec.name in self.const_specs:
raise ThriftCompilerError(
'Cannot define constant "%s". That name is already taken.'
% const_spec.name
)
self.const_specs[const_spec.name] = const_spec | def add_const_spec(self, const_spec) | Adds a ConstSpec to the compliation scope.
If the ConstSpec's ``save`` attribute is True, the constant will be
added to the module at the top-level. | 3.33458 | 3.61728 | 0.921847 |
assert surface is not None
if hasattr(self.module, name):
raise ThriftCompilerError(
'Cannot define "%s". The name has already been used.' % name
)
setattr(self.module, name, surface) | def add_surface(self, name, surface) | Adds a top-level attribute with the given name to the module. | 6.330403 | 5.149217 | 1.229391 |
assert type is not None
if name in self.type_specs:
raise ThriftCompilerError(
'Cannot define type "%s" at line %d. '
'Another type with that name already exists.'
% (name, lineno)
)
self.type_specs[name] = spec | def add_type_spec(self, name, spec, lineno) | Adds the given type to the scope.
:param str name:
Name of the new type
:param spec:
``TypeSpec`` object containing information on the type, or a
``TypeReference`` if this is meant to be resolved during the
``link`` stage.
:param lineno:
... | 3.58088 | 4.256819 | 0.84121 |
if a is None: return None
# make sure it's a numpy array
a = _n.array(a)
# quickest option
if level in [0,1,False]: return a
# otherwise assemble the python code to execute
code = 'a.reshape(-1, level).'+method+'(axis=1)'
# execute, making sure the array can be resha... | def coarsen_array(a, level=2, method='mean') | Returns a coarsened (binned) version of the data. Currently supports
any of the numpy array operations, e.g. min, max, mean, std, ...
level=2 means every two data points will be binned.
level=0 or 1 just returns a copy of the array | 6.612615 | 6.926072 | 0.954743 |
# Normal coarsening
if not exponential:
# Coarsen the data
xc = coarsen_array(x, level, 'mean')
yc = coarsen_array(y, level, 'mean')
# Coarsen the y error in quadrature
if not ey is None:
if not is_iterable(ey): ey = [ey]*len(y)
... | def coarsen_data(x, y, ey=None, ex=None, level=2, exponential=False) | Coarsens the supplied data set. Returns coarsened arrays of x, y, along with
quadrature-coarsened arrays of ey and ex if specified.
Parameters
----------
x, y
Data arrays. Can be lists (will convert to numpy arrays).
These are coarsened by taking an average.
ey=None, ex=None
... | 2.512928 | 2.514738 | 0.99928 |
# coarsen x
if not ylevel:
Z_coarsened = Z
else:
temp = []
for z in Z: temp.append(coarsen_array(z, ylevel, method))
Z_coarsened = _n.array(temp)
# coarsen y
if xlevel:
Z_coarsened = Z_coarsened.transpose()
temp = []
for z in Z_coarsened... | def coarsen_matrix(Z, xlevel=0, ylevel=0, method='average') | This returns a coarsened numpy matrix.
method can be 'average', 'maximum', or 'minimum' | 2.16849 | 2.193958 | 0.988392 |
if start == 0:
print("Nothing you multiply zero by gives you anything but zero. Try picking something small.")
return None
if end == 0:
print("It takes an infinite number of steps to get to zero. Try a small number?")
return None
# figure out our multiplication scale
... | def erange(start, end, steps) | Returns a numpy array over the specified range taking geometric steps.
See also numpy.logspace() | 8.268836 | 7.988797 | 1.035054 |
if _s.fun.is_iterable(s) and not type(s) == str: return False
try:
float(s)
return 1
except:
try:
complex(s)
return 2
except:
try:
complex(s.replace('(','').replace(')','').replace('i','j'))
... | def is_a_number(s) | This takes an object and determines whether it's a number or a string
representing a number. | 4.343009 | 4.399415 | 0.987179 |
new_a = _n.array(a)
if n==0: return new_a
fill_array = _n.array([])
fill_array.resize(_n.abs(n))
# fill up the fill array before we do the shift
if fill is "average": fill_array = 0.0*fill_array + _n.average(a)
elif fill is "wrap" and n >= 0:
for i in range(0,n): fill_arra... | def array_shift(a, n, fill="average") | This will return an array with all the elements shifted forward in index by n.
a is the array
n is the amount by which to shift (can be positive or negative)
fill="average" fill the new empty elements with the average of the array
fill="wrap" fill the new empty elements with the lopped-of... | 2.477232 | 2.393803 | 1.034852 |
covariance = []
for n in range(0, len(error)):
covariance.append([])
for m in range(0, len(error)):
covariance[n].append(correlation[n][m]*error[n]*error[m])
return _n.array(covariance) | def assemble_covariance(error, correlation) | This takes an error vector and a correlation matrix and assembles the covariance | 2.795051 | 2.677628 | 1.043854 |
c = {}
for key in list(b.keys()): c[key]=b[key]
for key in list(a.keys()): c[key]=a[key]
return c | def combine_dictionaries(a, b) | returns the combined dictionary. a's values preferentially chosen | 2.736476 | 2.423359 | 1.129208 |
# make it a kickass copy of the original
c = _n.array(c)
# first get the error vector
e = []
for n in range(0, len(c[0])): e.append(_n.sqrt(c[n][n]))
# now cycle through the matrix, dividing by e[1]*e[2]
for n in range(0, len(c[0])):
for m in range(0, len(c[0])):
... | def decompose_covariance(c) | This decomposes a covariance matrix into an error vector and a correlation matrix | 3.812724 | 3.386137 | 1.125981 |
D_ydata = []
D_xdata = []
for n in range(1, len(xdata)-1):
D_xdata.append(xdata[n])
D_ydata.append((ydata[n+1]-ydata[n-1])/(xdata[n+1]-xdata[n-1]))
return [D_xdata, D_ydata] | def derivative(xdata, ydata) | performs d(ydata)/d(xdata) with nearest-neighbor slopes
must be well-ordered, returns new arrays [xdata, dydx_data]
neighbors: | 1.903239 | 1.953176 | 0.974433 |
x = []
dydx = []
nmax = len(xdata)-1
for n in range(nmax+1):
# get the indices of the data to fit
i1 = max(0, n-neighbors)
i2 = min(nmax, n+neighbors)
# get the sub data to fit
xmini = _n.array(xdata[i1:i2+1])
ymini = _n.array(ydata[i1:i2+1])
... | def derivative_fit(xdata, ydata, neighbors=1) | loops over the data points, performing a least-squares linear fit of the
nearest neighbors at each point. Returns an array of x-values and slopes.
xdata should probably be well-ordered.
neighbors How many data point on the left and right to include. | 2.905946 | 3.161386 | 0.9192 |
Z = _n.array(Z)
X = _n.array(X)
points = len(Z)*subsample
# define a function for searching
def zero_me(new_x): return f(new_x)-target_old_x
# do a simple search to find the new_x that gives old_x = min(X)
target_old_x = min(X)
new_xmin = find_zero_bisect(zero_me, new_xmin, new_... | def distort_matrix_X(Z, X, f, new_xmin, new_xmax, subsample=3) | Applies a distortion (remapping) to the matrix Z (and x-values X) using function f.
returns new_Z, new_X
f is an INVERSE function old_x(new_x)
Z is a matrix. X is an array where X[n] is the x-value associated with the array Z[n].
new_xmin, new_xmax is the possible range of the distorted x-variable fo... | 3.29623 | 3.286994 | 1.00281 |
# just use the same methodology as before by transposing, distorting X, then
# transposing back
new_Z, new_Y = distort_matrix_X(Z.transpose(), Y, f, new_ymin, new_ymax, subsample)
return new_Z.transpose(), new_Y | def distort_matrix_Y(Z, Y, f, new_ymin, new_ymax, subsample=3) | Applies a distortion (remapping) to the matrix Z (and y-values Y) using function f.
returns new_Z, new_Y
f is a function old_y(new_y)
Z is a matrix. Y is an array where Y[n] is the y-value associated with the array Z[:,n].
new_ymin, new_ymax is the range of the distorted x-variable for generating Z
... | 4.877916 | 4.857413 | 1.004221 |
prev = f(xmin)
this = f(xmin+xstep)
for x in frange(xmin+xstep,xmax,xstep):
next = f(x+xstep)
# see if we're on top
if this < prev and this < next: return x, this
prev = this
this = next
return x, this | def dumbguy_minimize(f, xmin, xmax, xstep) | This just steps x and looks for a peak
returns x, f(x) | 4.260284 | 4.056373 | 1.050269 |
# empty case
if len(array) == 0: return 0
output_value = 1
for x in array:
# test it and die if it's not a number
test = is_a_number(x)
if not test: return False
# mention if it's complex
output_value = max(output_value,test)
return output_value | def elements_are_numbers(array) | Tests whether the elements of the supplied array are numbers. | 7.020308 | 6.849551 | 1.02493 |
if not _s.fun.is_iterable(a): a = [a]
a = list(a)
while len(a)>len(b): a.pop(-1)
while len(a)<len(b): a.append(a[-1])
return a | def equalize_list_lengths(a,b) | Modifies the length of list a to match b. Returns a.
a can also not be a list (will convert it to one).
a will not be modified. | 3.363735 | 3.055763 | 1.100784 |
if recursion<0: return None
# get an initial guess as to the baseline
ymin = min(array)
ymax = max(array)
for n in range(max_iterations):
# bisect the range to estimate the baseline
y1 = (ymin+ymax)/2.0
# now see how many peaks this finds. p could have 40 for all we... | def find_N_peaks(array, N=4, max_iterations=100, rec_max_iterations=3, recursion=1) | This will run the find_peaks algorythm, adjusting the baseline until exactly N peaks are found. | 6.034048 | 5.991753 | 1.007059 |
peaks = []
if return_subarrays:
subarray_values = []
subarray_indices = []
# loop over the data
n = 0
while n < len(array):
# see if we're above baseline, then start the "we're in a peak" loop
if array[n] > baseline:
# start keeping track of the ... | def find_peaks(array, baseline=0.1, return_subarrays=False) | This will try to identify the indices of the peaks in array, returning a list of indices in ascending order.
Runs along the data set until it jumps above baseline. Then it considers all the subsequent data above the baseline
as part of the peak, and records the maximum of this data as one peak value. | 2.943504 | 2.891572 | 1.01796 |
if f(xmax)*f(xmin) > 0:
print("find_zero_bisect(): no zero on the range",xmin,"to",xmax)
return None
temp = min(xmin,xmax)
xmax = max(xmin,xmax)
xmin = temp
xmid = (xmin+xmax)*0.5
while xmax-xmin > xprecision:
y = f(xmid)
# pick the direction with one guy ... | def find_zero_bisect(f, xmin, xmax, xprecision) | This will bisect the range and zero in on zero. | 3.549504 | 3.428303 | 1.035353 |
x = _n.array(xdata)
y = _n.array(ydata)
ax = _n.average(x)
ay = _n.average(y)
axx = _n.average(x*x)
ayx = _n.average(y*x)
slope = (ayx - ay*ax) / (axx - ax*ax)
intercept = ay - slope*ax
return slope, intercept | def fit_linear(xdata, ydata) | Returns slope and intercept of line of best fit:
y = a*x + b
through the supplied data.
Parameters
----------
xdata, ydata:
Arrays of x data and y data (having matching lengths). | 2.374418 | 2.934097 | 0.80925 |
start = 1.0*start
end = 1.0*end
inc = 1.0*inc
# if we got a dumb increment
if not inc: return _n.array([start,end])
# if the increment is going the wrong direction
if 1.0*(end-start)/inc < 0.0:
inc = -inc
# get the integer steps
ns = _n.array(list(range(0, int(1.... | def frange(start, end, inc=1.0) | A range function, that accepts float increments and reversed direction.
See also numpy.linspace() | 4.157352 | 4.447421 | 0.934778 |
# Make a fitter object, which handily interprets string functions
# The "+0*x" is a trick to ensure the function takes x as an argument
# (makes it a little more idiot proof).
fitty = _s.data.fitter().set_functions(f+"+0*x",'')
# Make sure both errors are arrays of the right length
... | def generate_fake_data(f='2*x-5', x=_n.linspace(-5,5,11), ey=1, ex=0, include_errors=False, **kwargs) | Generates a set of fake data from the underlying "reality" (or mean
behavior) function f.
Parameters
----------
f:
Underlying "reality" function or mean behavior. This can be any
python-evaluable string, and will have access to all the numpy
functions (e.g., cos), scipy's sp... | 5.892694 | 5.438829 | 1.083449 |
# try for ipython
if 'get_ipython' in globals():
a = list(get_ipython().history_manager.input_hist_raw)
a.reverse()
return a
elif 'SPYDER_SHELL_ID' in _os.environ:
try:
p = _os.path.join(_settings.path_user, ".spyder2", "history.py")
a = read_lin... | def get_shell_history() | This only works with some shells. | 5.115251 | 5.034451 | 1.01605 |
i = array.searchsorted(value)
if i == len(array): return -1
else: return i | def index(value, array) | Array search that behaves like I want it to. Totally dumb, I know. | 5.37859 | 5.244314 | 1.025604 |
a = (array-value)**2
return index(a.min(), a) | def index_nearest(value, array) | expects a _n.array
returns the global minimum of (value-array)^2 | 10.253634 | 9.051103 | 1.13286 |
for n in range(starting_index, len(array)-1):
if (value-array[n] )*direction >= 0 \
and (value-array[n+1])*direction < 0: return n
# no crossing found
return -1 | def index_next_crossing(value, array, starting_index=0, direction=1) | starts at starting_index, and walks through the array until
it finds a crossing point with value
set direction=-1 for down crossing | 4.815204 | 4.976423 | 0.967603 |
index = 0
# search for the last array item that value is larger than
for n in range(0,len(array)):
if value >= array[n]: index = n+1
array.insert(index, value)
return index | def insert_ordered(value, array) | This will insert the value into the array, keeping it sorted, and returning the
index where it was inserted | 4.728665 | 5.131335 | 0.921527 |
# sort the arrays and make sure they're numpy arrays
[xdata, ydata] = sort_matrix([xdata,ydata],0)
xdata = _n.array(xdata)
ydata = _n.array(ydata)
if xmin is None: xmin = min(xdata)
if xmax is None: xmax = max(xdata)
# find the index range
imin = xdata.searchsorted(xmin)
imax... | def integrate_data(xdata, ydata, xmin=None, xmax=None, autozero=0) | Numerically integrates up the ydata using the trapezoid approximation.
estimate the bin width (scaled by the specified amount).
Returns (xdata, integrated ydata).
autozero is the number of data points to use as an estimate of the background
(then subtracted before integrating). | 2.22508 | 2.185979 | 1.017887 |
for n in range(max_iterations):
# start at the middle
x = 0.5*(xmin+xmax)
df = f(x)-f0
if _n.fabs(df) < tolerance: return x
# if we're high, set xmin to x etc...
if df > 0: xmin=x
else: xmax=x
print("Couldn't find value!")
return 0.5*(xmi... | def invert_increasing_function(f, f0, xmin, xmax, tolerance, max_iterations=100) | This will try try to qickly find a point on the f(x) curve between xmin and xmax that is
equal to f0 within tolerance. | 5.324298 | 5.27145 | 1.010025 |
# make sure they're numpy arrays, and make copies to avoid the referencing error
y = _n.array(y)
t = _n.array(t)
# if we're doing the power of 2, do it
if pow2:
keep = 2**int(_n.log2(len(y)))
# now resize the data
y.resize(keep)
t.resize(keep)
# Window th... | def fft(t, y, pow2=False, window=None, rescale=False) | FFT of y, assuming complex or real-valued inputs. This goes through the
numpy fourier transform process, assembling and returning (frequencies,
complex fft) given time and signal data y.
Parameters
----------
t,y
Time (t) and signal (y) arrays with which to perform the fft. Note the t
... | 4.249974 | 4.091009 | 1.038857 |
# do the actual fft
f, Y = fft(t,y,pow2,window,rescale)
# take twice the negative frequency branch, because it contains the
# extra frequency point when the number of points is odd.
f = _n.abs(f[int(len(f)/2)::-1])
P = _n.abs(Y[int(len(Y)/2)::-1])**2 / (f[1]-f[0])
# Since this i... | def psd(t, y, pow2=False, window=None, rescale=False) | Single-sided power spectral density, assuming real valued inputs. This goes
through the numpy fourier transform process, assembling and returning
(frequencies, psd) given time and signal data y.
Note it is defined such that sum(psd)*df, where df is the frequency
spacing, is the variance of the or... | 6.539889 | 6.168815 | 1.060153 |
# have the user select some files
if paths==None:
paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*')
if paths == []: return
for path in paths:
lines = read_lines(path)
if depth: N=min(len(lines),depth)
else: N=len(lines)
for n in range(0,N):
... | def replace_in_files(search, replace, depth=0, paths=None, confirm=True) | Does a line-by-line search and replace, but only up to the "depth" line. | 5.279463 | 5.059477 | 1.04348 |
# have the user select some files
paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*')
if paths == []: return
for path in paths:
_shutil.copy(path, path+".backup")
lines = read_lines(path)
for n in range(0,len(lines)):
if lines[n].find(search_string) >= 0:
... | def replace_lines_in_files(search_string, replacement_line) | Finds lines containing the search string and replaces the whole line with
the specified replacement string. | 6.587368 | 6.606096 | 0.997165 |
l = list(array)
l.reverse()
return _n.array(l) | def reverse(array) | returns a reversed numpy array | 7.434413 | 6.092354 | 1.220286 |
iterable = is_iterable(x)
if not iterable: x = [x]
# make a copy to be safe
x = _n.array(x)
# loop over the elements
for i in range(len(x)):
# Handle the weird cases
if not x[i] in [None, _n.inf, _n.nan]:
sig_figs = -int(_n.floor(_n.log10(abs(x[i])... | def round_sigfigs(x, n=2) | Rounds the number to the specified significant figures. x can also be
a list or array of numbers (in these cases, a numpy array is returned). | 3.469812 | 3.516241 | 0.986796 |
i = feature(ydata)
return xdata-xdata[i]+x0, ydata | def shift_feature_to_x0(xdata, ydata, x0=0, feature=imax) | Finds a feature in the the ydata and shifts xdata so the feature is centered
at x0. Returns shifted xdata, ydata. Try me with plot.tweaks.manipulate_shown_data()!
xdata,ydata data set
x0=0 where to shift the peak
feature=imax function taking an array/list and returning the index of sa... | 7.024232 | 6.517807 | 1.077699 |
new_xdata = smooth_array(_n.array(xdata), amount)
new_ydata = smooth_array(_n.array(ydata), amount)
if yerror is None: new_yerror = None
else: new_yerror = smooth_array(_n.array(yerror), amount)
return [new_xdata, new_ydata, new_yerror] | def smooth_data(xdata, ydata, yerror, amount=1) | Returns smoothed [xdata, ydata, yerror]. Does not destroy the input arrays. | 2.266601 | 2.153764 | 1.052391 |
a = _n.array(a)
return a[:,a[n,:].argsort()] | def sort_matrix(a,n=0) | This will rearrange the array a[n] from lowest to highest, and
rearrange the rest of a[i]'s in the same way. It is dumb and slow.
Returns a numpy array. | 9.102055 | 11.86659 | 0.767032 |
new = []
for i in range(i1,i2+1):
new.append(matrix[i][j1:j2+1])
return _n.array(new) | def submatrix(matrix,i1,i2,j1,j2) | returns the submatrix defined by the index bounds i1-i2 and j1-j2
Endpoints included! | 3.43235 | 3.193951 | 1.074641 |
# make sure it's a numpy array
if not isinstance(xdata, _n.ndarray): xdata = _n.array(xdata)
# make sure xmin and xmax are numbers
if xmin is None: xmin = min(xdata)
if xmax is None: xmax = max(xdata)
# get all the indices satisfying the trim condition
ns = _n.argwhere((xdata >= xmin... | def trim_data(xmin, xmax, xdata, *args) | Removes all the data except that in which xdata is between xmin and xmax.
This does not mutilate the input arrays, and additional arrays
can be supplied via args (provided they match xdata in shape)
xmin and xmax can be None | 2.68845 | 2.639595 | 1.018508 |
# dumb conditions
if len(conditions) == 0: return arrays
if len(arrays) == 0: return []
# find the indices to keep
all_conditions = conditions[0]
for n in range(1,len(conditions)): all_conditions = all_conditions & conditions[n]
ns = _n.argwhere(all_conditions).transpos... | def trim_data_uber(arrays, conditions) | Non-destructively selects data from the supplied list of arrays based on
the supplied list of conditions. Importantly, if any of the conditions are
not met for the n'th data point, the n'th data point is rejected for
all supplied arrays.
Example
-------
x = numpy.linspace(0,10,20)
y = num... | 4.286561 | 4.71758 | 0.908636 |
'''Fetch a response from the Geocoding API.'''
fields['vintage'] = self.vintage
fields['benchmark'] = self.benchmark
fields['format'] = 'json'
if 'layers' in kwargs:
fields['layers'] = kwargs['layers']
returntype = kwargs.get('returntype', 'geographies')
... | def _fetch(self, searchtype, fields, **kwargs) | Fetch a response from the Geocoding API. | 4.093833 | 3.882907 | 1.054322 |
'''Geocode a (lon, lat) coordinate.'''
kwargs['returntype'] = 'geographies'
fields = {
'x': x,
'y': y
}
return self._fetch('coordinates', fields, **kwargs) | def coordinates(self, x, y, **kwargs) | Geocode a (lon, lat) coordinate. | 7.459626 | 5.426737 | 1.374606 |
'''Geocode an address.'''
fields = {
'street': street,
'city': city,
'state': state,
'zip': zipcode,
}
return self._fetch('address', fields, **kwargs) | def address(self, street, city=None, state=None, zipcode=None, **kwargs) | Geocode an address. | 3.415413 | 3.529228 | 0.967751 |
'''Geocode an an address passed as one string.
e.g. "4600 Silver Hill Rd, Suitland, MD 20746"
'''
fields = {
'address': address,
}
return self._fetch('onelineaddress', fields, **kwargs) | def onelineaddress(self, address, **kwargs) | Geocode an an address passed as one string.
e.g. "4600 Silver Hill Rd, Suitland, MD 20746" | 8.416977 | 2.508384 | 3.355538 |
'''
Send either a CSV file or data to the addressbatch API.
According to the Census, "there is currently an upper limit of 1000 records per batch file."
If a file, must have no header and fields id,street,city,state,zip
If data, should be a list of dicts with the above fields (al... | def addressbatch(self, data, **kwargs) | Send either a CSV file or data to the addressbatch API.
According to the Census, "there is currently an upper limit of 1000 records per batch file."
If a file, must have no header and fields id,street,city,state,zip
If data, should be a list of dicts with the above fields (although ID is optiona... | 5.416944 | 2.110293 | 2.566916 |
if name == None: name = self.get_name()
if name == "" or not type(name)==str: return "Error: Bad name."
# assemble the path to the colormap
path = _os.path.join(_settings.path_home, "colormaps", name+".cmap")
# make sure the file exists
if not _os.path.exists(... | def load_colormap(self, name=None) | Loads a colormap of the supplied name. None means used the internal
name. (See self.get_name()) | 3.826314 | 3.622331 | 1.056313 |
if name == None: name = self.get_name()
if name == "" or not type(name)==str: return "Error: invalid name."
# get the colormaps directory
colormaps = _os.path.join(_settings.path_home, 'colormaps')
# make sure we have the colormaps directory
_settings.MakeDir(c... | def save_colormap(self, name=None) | Saves the colormap with the specified name. None means use internal
name. (See get_name()) | 3.804145 | 3.554427 | 1.070256 |
if name == None: name = self.get_name()
if name == "" or not type(name)==str: return "Error: invalid name."
# assemble the path to the colormap
path = _os.path.join(_settings.path_home, 'colormaps', name+".cmap")
_os.unlink(path)
return self | def delete_colormap(self, name=None) | Deletes the colormap with the specified name. None means use the internal
name (see get_name()) | 5.814429 | 5.451941 | 1.066488 |
if not type(name)==str:
print("set_name(): Name must be a string.")
return
self._name = name
return self | def set_name(self, name="My Colormap") | Sets the name.
Make sure the name is something your OS could name a file. | 4.834431 | 5.164208 | 0.936142 |
if image=="auto": image = _pylab.gca().images[0]
self._image=image
self.update_image() | def set_image(self, image='auto') | Set which pylab image to tweak. | 6.226748 | 4.742185 | 1.313055 |
if self._image:
self._image.set_cmap(self.get_cmap())
_pylab.draw() | def update_image(self) | Set's the image's cmap. | 7.553135 | 4.26065 | 1.772766 |
# make sure we have more than 2; otherwise don't pop it, just return it
if len(self._colorpoint_list) > 2:
# do the popping
x = self._colorpoint_list.pop(n)
# make sure the endpoints are 0 and 1
self._colorpoint_list[0][0] = 0.0
se... | def pop_colorpoint(self, n=0) | Removes and returns the specified colorpoint. Will always leave two behind. | 4.344876 | 4.229735 | 1.027222 |
L = self._colorpoint_list
# if position = 0 or 1, push the end points inward
if position <= 0.0:
L.insert(0,[0.0,color1,color2])
elif position >= 1.0:
L.append([1.0,color1,color2])
# otherwise, find the position where it belongs
else:... | def insert_colorpoint(self, position=0.5, color1=[1.0,1.0,0.0], color2=[1.0,1.0,0.0]) | Inserts the specified color into the list. | 3.667506 | 3.668417 | 0.999752 |
if n==0.0 : position = 0.0
elif n==len(self._colorpoint_list)-1: position = 1.0
else: position = max(self._colorpoint_list[n-1][0], position)
self._colorpoint_list[n] = [position, color1, color2]
self.update_image()
self.save_colormap... | def modify_colorpoint(self, n, position=0.5, color1=[1.0,1.0,1.0], color2=[1.0,1.0,1.0]) | Changes the values of an existing colorpoint, then updates the colormap. | 4.192662 | 4.088211 | 1.025549 |
# now generate the colormap from the ordered list
r = []
g = []
b = []
for p in self._colorpoint_list:
r.append((p[0], p[1][0]*1.0, p[2][0]*1.0))
g.append((p[0], p[1][1]*1.0, p[2][1]*1.0))
b.append((p[0], p[1][2]*1.0, p[2][2]*1.0))
... | def get_cmap(self) | Generates a pylab cmap object from the colorpoint data. | 3.076939 | 2.754695 | 1.11698 |
# set our name
self.set_name(str(self._combobox_cmaps.currentText()))
# load the colormap
self.load_colormap()
# rebuild the interface
self._build_gui()
self._button_save.setEnabled(False) | def _signal_load(self) | Load the selected cmap. | 6.854298 | 5.216774 | 1.313896 |
self.set_name(str(self._combobox_cmaps.currentText()))
self.save_colormap()
self._button_save.setEnabled(False)
self._load_cmap_list() | def _button_save_clicked(self) | Save the selected cmap. | 6.507658 | 4.117705 | 1.580409 |
name = str(self._combobox_cmaps.currentText())
self.delete_colormap(name)
self._combobox_cmaps.setEditText("")
self._load_cmap_list() | def _button_delete_clicked(self) | Save the selected cmap. | 5.796655 | 3.780089 | 1.53347 |
self._button_save.setEnabled(True)
cp = self._colorpoint_list[n]
# if they're linked, set both
if self._checkboxes[n].isChecked():
self.modify_colorpoint(n, cp[0], [c.red()/255.0, c.green()/255.0, c.blue()/255.0],
[c.red... | def _color_dialog_changed(self, n, top, c) | Updates the color of the slider. | 1.756934 | 1.74771 | 1.005278 |
self._button_save.setEnabled(True)
self.insert_colorpoint(self._colorpoint_list[n][0],
self._colorpoint_list[n][1],
self._colorpoint_list[n][2])
self._build_gui() | def _button_plus_clicked(self, n) | Create a new colorpoint. | 4.586721 | 3.233644 | 1.418437 |
self._button_save.setEnabled(True)
self.pop_colorpoint(n)
self._build_gui() | def _button_minus_clicked(self, n) | Remove a new colorpoint. | 17.112541 | 7.54962 | 2.266676 |
self._button_save.setEnabled(True)
self.modify_colorpoint(n, self._sliders[n].value()*0.001, self._colorpoint_list[n][1], self._colorpoint_list[n][2]) | def _slider_changed(self, n) | updates the colormap / plot | 5.606382 | 5.359916 | 1.045983 |
self._button_save.setEnabled(True)
if top: self._color_dialogs_top[n].open()
else: self._color_dialogs_bottom[n].open() | def _color_button_clicked(self, n,top) | Opens the dialog. | 5.54341 | 4.633984 | 1.196252 |
# store the current name
name = self.get_name()
# clear the list
self._combobox_cmaps.blockSignals(True)
self._combobox_cmaps.clear()
# list the existing contents
paths = _settings.ListDir('colormaps')
# loop over the paths and add the names to... | def _load_cmap_list(self) | Searches the colormaps directory for all files, populates the list. | 3.229313 | 3.023291 | 1.068145 |
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files (*)"
# if this type of pref doesn't exist, we need to make a new one
if default_directory in _settings.keys(): default = _settings[default_directory]
else: ... | def save(filters='*.*', text='Save THIS, facehead!', default_directory='default_directory', force_extension=None) | Pops up a save dialog and returns the string path of the selected file.
Parameters
----------
filters='*.*'
Which file types should appear in the dialog.
text='Save THIS, facehead!'
Title text for the dialog.
default_directory='default_directory'
Key for the spinmob.sett... | 4.961846 | 5.054291 | 0.98171 |
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files (*)"
# if this type of pref doesn't exist, we need to make a new one
if default_directory in _settings.keys(): default = _settings[default_directory]
else: ... | def load(filters="*.*", text='Select a file, FACEFACE!', default_directory='default_directory') | Pops up a dialog for opening a single file. Returns a string path or None. | 5.854009 | 5.865815 | 0.997987 |
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files (*)"
# if this type of pref doesn't exist, we need to make a new one
if default_directory in _settings.keys(): default = _settings[default_directory]
else: ... | def load_multiple(filters="*.*", text='Select some files, FACEFACE!', default_directory='default_directory') | Pops up a dialog for opening more than one file. Returns a list of string paths or None. | 5.740606 | 5.744807 | 0.999269 |
prefs_file = open(self.prefs_path, 'w')
for n in range(0,len(self.prefs)):
if len(list(self.prefs.items())[n]) > 1:
prefs_file.write(str(list(self.prefs.items())[n][0]) + ' = ' +
str(list(self.prefs.items())[n][1]) + '\n')
pre... | def Dump(self) | Dumps the current prefs to the preferences.txt file | 2.486096 | 2.159074 | 1.151464 |
type_specs = {}
types = []
for name, type_spec in self.scope.type_specs.items():
type_spec = type_spec.link(self.scope)
type_specs[name] = type_spec
if type_spec.surface is not None:
self.scope.add_surface(name, type_spec.surface)
... | def link(self) | Resolve and link all types in the scope. | 3.0677 | 2.692972 | 1.13915 |
if name is None:
name = os.path.splitext(os.path.basename(path))[0]
callermod = inspect.getmodule(inspect.stack()[1][0])
name = '%s.%s' % (callermod.__name__, name)
if name in sys.modules:
return sys.modules[name]
if not os.path.isabs(path):
callerfile = callermod.__f... | def install(path, name=None) | Compiles a Thrift file and installs it as a submodule of the caller.
Given a tree organized like so::
foo/
__init__.py
bar.py
my_service.thrift
You would do,
.. code-block:: python
my_service = thriftrw.install('my_service.thrift')
To install ``m... | 2.250866 | 2.587824 | 0.869791 |
return self.compiler.compile(name, document).link().surface | def loads(self, name, document) | Parse and compile the given Thrift document.
:param str name:
Name of the Thrift document.
:param str document:
The Thrift IDL as a string. | 36.123722 | 52.908096 | 0.682764 |
if name is None:
name = os.path.splitext(os.path.basename(path))[0]
# TODO do we care if the file extension is .thrift?
with open(path, 'r') as f:
document = f.read()
return self.compiler.compile(name, document, path).link().surface | def load(self, path, name=None) | Load and compile the given Thrift file.
:param str path:
Path to the ``.thrift`` file.
:param str name:
Name of the generated module. Defaults to the base name of the
file.
:returns:
The compiled module. | 5.133122 | 5.232479 | 0.981012 |
url = "https://oauth.vk.com/authorize"
params = {
"client_id": client_id,
"scope": scope,
"redirect_uri": redirect_uri,
"display": display,
"response_type": response_type,
"version": version,
"state": state,
"revoke": revoke
}
params ... | def get_url_implicit_flow_user(client_id, scope,
redirect_uri='https://oauth.vk.com/blank.html', display='page',
response_type='token', version=None, state=None, revoke=1) | https://vk.com/dev/implicit_flow_user
:return: url | 1.521235 | 1.619195 | 0.939501 |
url = "https://oauth.vk.com/authorize"
params = {
"client_id": client_id,
"redirect_uri": redirect_uri,
"display": display,
"response_type": "code"
}
if scope:
params['scope'] = scope
if state:
params['state'] = state
return u"{url}?{params... | def get_url_authcode_flow_user(client_id, redirect_uri, display="page", scope=None, state=None) | Authorization Code Flow for User Access Token
Use Authorization Code Flow to run VK API methods from the server side of an application.
Access token received this way is not bound to an ip address but set of permissions that can be granted is limited for security reasons.
Args:
client_id (int): Ap... | 1.699646 | 2.054208 | 0.827397 |
# add columns of data to the databox
d['x'] = _n.linspace(0,10,100)
d['y'] = _n.cos(d['x']) + 0.1*_n.random.rand(100)
# update the curve
c.setData(d['x'], d['y']) | def get_fake_data(*a) | Called whenever someone presses the "fire" button. | 6.041722 | 5.357213 | 1.127773 |
#print opts
for k in opts:
if k == 'bounds':
#print opts[k]
self.setMinimum(opts[k][0], update=False)
self.setMaximum(opts[k][1], update=False)
#for i in [0,1]:
#if opts[k][i] is None:
... | def setOpts(self, **opts) | Changes the behavior of the SpinBox. Accepts most of the arguments
allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`. | 2.992662 | 2.879174 | 1.039417 |
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][1] = m
if update:
self.setValue() | def setMaximum(self, m, update=True) | Set the maximum allowed value (or None for no limit) | 9.141963 | 8.970525 | 1.019111 |
le = self.lineEdit()
text = asUnicode(le.text())
if self.opts['suffix'] == '':
le.setSelection(0, len(text))
else:
try:
index = text.index(' ')
except ValueError:
return
le.setSelection(0, index) | def selectNumber(self) | Select the numerical portion of the text to allow quick editing by the user. | 5.559425 | 4.816124 | 1.154336 |
if self.opts['int']:
return int(self.val)
else:
return float(self.val) | def value(self) | Return the value of this SpinBox. | 5.553987 | 4.442578 | 1.250172 |
if value is None:
value = self.value()
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
value = bounds[0]
if bounds[1] is not None and value > bounds[1]:
value = bounds[1]
if self.opts['in... | def setValue(self, value=None, update=True, delaySignal=False) | Set the value of this spin.
If the value is out of bounds, it will be clipped to the nearest boundary.
If the spin is integer type, the value will be coerced to int.
Returns the actual value set.
If value is None, then the current value is used (this is for resetting
th... | 3.813915 | 3.671256 | 1.038858 |
strn = self.lineEdit().text()
suf = self.opts['suffix']
if len(suf) > 0:
if strn[-len(suf):] != suf:
return False
#raise Exception("Units are invalid.")
strn = strn[:-len(suf)]
try:
val = fn.siEval(strn)
exc... | def interpret(self) | Return value of text. Return False if text is invalid, raise exception if text is intermediate | 5.605177 | 5.029209 | 1.114525 |
#print "Edit finished."
if asUnicode(self.lineEdit().text()) == self.lastText:
#print "no text change."
return
try:
val = self.interpret()
except:
return
if val is False:
#print "value invalid:", str(se... | def editingFinishedEvent(self) | Edit has finished; set value. | 5.836359 | 5.47796 | 1.065426 |
field_names = cls._meta.get_all_field_names()
fields = {}
text = []
finalizer = None
scaffold = scaffolding.scaffold_for_model(cls)
for field_name in field_names:
generator = getattr(scaffold, field_name, None)
if generator:
... | def make_factory(self, cls, count) | Get the generators from the Scaffolding class within the model. | 3.171947 | 2.894125 | 1.095995 |
indel_len = pd.Series(index=fs_df.index)
indel_len[fs_df['Reference_Allele']=='-'] = fs_df['Tumor_Allele'][fs_df['Reference_Allele']=='-'].str.len()
indel_len[fs_df['Tumor_Allele']=='-'] = fs_df['Reference_Allele'][fs_df['Tumor_Allele']=='-'].str.len()
indel_len = indel_len.fillna(0).astype(int)
... | def compute_indel_length(fs_df) | Computes the indel length accounting for wether it is an insertion or
deletion.
Parameters
----------
fs_df : pd.DataFrame
mutation input as dataframe only containing indel mutations
Returns
-------
indel_len : pd.Series
length of indels | 1.7697 | 1.952548 | 0.906354 |
# keep only frameshifts
mut_df = mut_df[is_indel_annotation(mut_df)]
if indel_len_col:
# calculate length
mut_df.loc[:, 'indel len'] = compute_indel_length(mut_df)
if indel_type_col:
is_ins = mut_df['Reference_Allele']=='-'
is_del = mut_df['Tumor_Allele']=='-'
... | def keep_indels(mut_df,
indel_len_col=True,
indel_type_col=True) | Filters out all mutations that are not indels.
Requires that one of the alleles have '-' indicating either an insertion
or deletion depending if found in reference allele or somatic allele
columns, respectively.
Parameters
----------
mut_df : pd.DataFrame
mutation input file as a dataf... | 2.6098 | 2.560558 | 1.019231 |
# keep only frameshifts
mut_df = mut_df[is_frameshift_annotation(mut_df)]
if indel_len_col:
# calculate length
mut_df.loc[:, 'indel len'] = compute_indel_length(mut_df)
return mut_df | def keep_frameshifts(mut_df,
indel_len_col=True) | Filters out all mutations that are not frameshift indels.
Requires that one of the alleles have '-' indicating either an insertion
or deletion depending if found in reference allele or somatic allele
columns, respectively.
Parameters
----------
mut_df : pd.DataFrame
mutation input file... | 3.564994 | 4.714593 | 0.756162 |
# calculate length, 0-based coordinates
#indel_len = mut_df['End_Position'] - mut_df['Start_Position']
if 'indel len' in mut_df.columns:
indel_len = mut_df['indel len']
else:
indel_len = compute_indel_length(mut_df)
# only non multiples of 3 are frameshifts
is_fs = (indel_l... | def is_frameshift_len(mut_df) | Simply returns a series indicating whether each corresponding mutation
is a frameshift.
This is based on the length of the indel. Thus may be fooled by frameshifts
at exon-intron boundaries or other odd cases.
Parameters
----------
mut_df : pd.DataFrame
mutation input file as a datafra... | 3.685383 | 3.749058 | 0.983016 |
fs_len = []
i = 1
tmp_bins = 0
while(tmp_bins<num_bins):
if i%3:
fs_len.append(i)
tmp_bins += 1
i += 1
return fs_len | def get_frameshift_lengths(num_bins) | Simple function that returns the lengths for each frameshift category
if `num_bins` number of frameshift categories are requested. | 3.731237 | 3.789567 | 0.984608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.