code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _set_bridge(self, v, load=False):
"""
Setter method for bridge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/bridge (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_bridge() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=bridge.bridge, is_container='container', presence=False, yang_name="bridge", rest_name="bridge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """bridge must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=bridge.bridge, is_container='container', presence=False, yang_name="bridge", rest_name="bridge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='container', is_config=True)""",
})
self.__bridge = t
if hasattr(self, '_set'):
self._set() | def function[_set_bridge, parameter[self, v, load]]:
constant[
Setter method for bridge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/bridge (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_bridge() directly.
]
if call[name[hasattr], parameter[name[v], constant[_utype]]] begin[:]
variable[v] assign[=] call[name[v]._utype, parameter[name[v]]]
<ast.Try object at 0x7da20c76d4b0>
name[self].__bridge assign[=] name[t]
if call[name[hasattr], parameter[name[self], constant[_set]]] begin[:]
call[name[self]._set, parameter[]] | keyword[def] identifier[_set_bridge] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identifier[t] = identifier[YANGDynClass] ( identifier[v] , identifier[base] = identifier[bridge] . identifier[bridge] , identifier[is_container] = literal[string] , identifier[presence] = keyword[False] , identifier[yang_name] = literal[string] , identifier[rest_name] = literal[string] , identifier[parent] = identifier[self] , identifier[choice] =( literal[string] , literal[string] ), identifier[path_helper] = identifier[self] . identifier[_path_helper] , identifier[extmethods] = identifier[self] . identifier[_extmethods] , identifier[register_paths] = keyword[False] , identifier[extensions] = keyword[None] , identifier[namespace] = literal[string] , identifier[defining_module] = literal[string] , identifier[yang_type] = literal[string] , identifier[is_config] = keyword[True] )
keyword[except] ( identifier[TypeError] , identifier[ValueError] ):
keyword[raise] identifier[ValueError] ({
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
})
identifier[self] . identifier[__bridge] = identifier[t]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[_set] () | def _set_bridge(self, v, load=False):
"""
Setter method for bridge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/bridge (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_bridge() directly.
"""
if hasattr(v, '_utype'):
v = v._utype(v) # depends on [control=['if'], data=[]]
try:
t = YANGDynClass(v, base=bridge.bridge, is_container='container', presence=False, yang_name='bridge', rest_name='bridge', parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='container', is_config=True) # depends on [control=['try'], data=[]]
except (TypeError, ValueError):
raise ValueError({'error-string': 'bridge must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=bridge.bridge, is_container=\'container\', presence=False, yang_name="bridge", rest_name="bridge", parent=self, choice=(u\'spanning-tree-mode\', u\'pvstp\'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace=\'urn:brocade.com:mgmt:brocade-xstp-ext\', defining_module=\'brocade-xstp-ext\', yang_type=\'container\', is_config=True)'}) # depends on [control=['except'], data=[]]
self.__bridge = t
if hasattr(self, '_set'):
self._set() # depends on [control=['if'], data=[]] |
def preorder(self):
""" iterator for nodes: root, left, right """
if not self:
return
yield self
if self.left:
for x in self.left.preorder():
yield x
if self.right:
for x in self.right.preorder():
yield x | def function[preorder, parameter[self]]:
constant[ iterator for nodes: root, left, right ]
if <ast.UnaryOp object at 0x7da1b05089a0> begin[:]
return[None]
<ast.Yield object at 0x7da1b0509060>
if name[self].left begin[:]
for taget[name[x]] in starred[call[name[self].left.preorder, parameter[]]] begin[:]
<ast.Yield object at 0x7da1b0508820>
if name[self].right begin[:]
for taget[name[x]] in starred[call[name[self].right.preorder, parameter[]]] begin[:]
<ast.Yield object at 0x7da1b050b7c0> | keyword[def] identifier[preorder] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] :
keyword[return]
keyword[yield] identifier[self]
keyword[if] identifier[self] . identifier[left] :
keyword[for] identifier[x] keyword[in] identifier[self] . identifier[left] . identifier[preorder] ():
keyword[yield] identifier[x]
keyword[if] identifier[self] . identifier[right] :
keyword[for] identifier[x] keyword[in] identifier[self] . identifier[right] . identifier[preorder] ():
keyword[yield] identifier[x] | def preorder(self):
""" iterator for nodes: root, left, right """
if not self:
return # depends on [control=['if'], data=[]]
yield self
if self.left:
for x in self.left.preorder():
yield x # depends on [control=['for'], data=['x']] # depends on [control=['if'], data=[]]
if self.right:
for x in self.right.preorder():
yield x # depends on [control=['for'], data=['x']] # depends on [control=['if'], data=[]] |
def check_call(cmd_args):
"""
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
"""
p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)
(output, err) = p.communicate()
return output | def function[check_call, parameter[cmd_args]]:
constant[
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
]
variable[p] assign[=] call[name[subprocess].Popen, parameter[name[cmd_args]]]
<ast.Tuple object at 0x7da1b004d210> assign[=] call[name[p].communicate, parameter[]]
return[name[output]] | keyword[def] identifier[check_call] ( identifier[cmd_args] ):
literal[string]
identifier[p] = identifier[subprocess] . identifier[Popen] ( identifier[cmd_args] , identifier[stdout] = identifier[subprocess] . identifier[PIPE] )
( identifier[output] , identifier[err] )= identifier[p] . identifier[communicate] ()
keyword[return] identifier[output] | def check_call(cmd_args):
"""
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
"""
p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)
(output, err) = p.communicate()
return output |
def get_rg_from_id(vmss_id):
'''get a resource group name from a VMSS ID string'''
rgname = re.search('Groups/(.+?)/providers', vmss_id).group(1)
print('Resource group: ' + rgname)
return rgname | def function[get_rg_from_id, parameter[vmss_id]]:
constant[get a resource group name from a VMSS ID string]
variable[rgname] assign[=] call[call[name[re].search, parameter[constant[Groups/(.+?)/providers], name[vmss_id]]].group, parameter[constant[1]]]
call[name[print], parameter[binary_operation[constant[Resource group: ] + name[rgname]]]]
return[name[rgname]] | keyword[def] identifier[get_rg_from_id] ( identifier[vmss_id] ):
literal[string]
identifier[rgname] = identifier[re] . identifier[search] ( literal[string] , identifier[vmss_id] ). identifier[group] ( literal[int] )
identifier[print] ( literal[string] + identifier[rgname] )
keyword[return] identifier[rgname] | def get_rg_from_id(vmss_id):
"""get a resource group name from a VMSS ID string"""
rgname = re.search('Groups/(.+?)/providers', vmss_id).group(1)
print('Resource group: ' + rgname)
return rgname |
def curie(path_to_file='.', file_name='', magic=False,
window_length=3, save=False, save_folder='.', fmt='svg', t_begin="", t_end=""):
"""
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with width= <-w> degrees)
***
The 2nd derivative is calculated from smoothed 1st derivative curve
(using the same sliding window width)
***
The estimated curie temp. is the maximum of the 2nd derivative.
Temperature steps should be in multiples of 1.0 degrees.
Parameters
__________
file_name : name of file to be opened
Optional Parameters (defaults are used if not specified)
----------
path_to_file : path to directory that contains file (default is current directory, '.')
window_length : dimension of smoothing window (input to smooth() function)
save : boolean argument to save plots (default is False)
save_folder : relative directory where plots will be saved (default is current directory, '.')
fmt : format of saved figures
t_begin: start of truncated window for search
t_end: end of truncated window for search
magic : True if MagIC formated measurements.txt file
"""
plot = 0
window_len = window_length
# read data from file
complete_path = os.path.join(path_to_file, file_name)
if magic:
data_df = pd.read_csv(complete_path, sep='\t', header=1)
T = data_df['meas_temp'].values-273
magn_key = cb.get_intensity_col(data_df)
M = data_df[magn_key].values
else:
Data = np.loadtxt(complete_path, dtype=np.float)
T = Data.transpose()[0]
M = Data.transpose()[1]
T = list(T)
M = list(M)
# cut the data if -t is one of the flags
if t_begin != "":
while T[0] < t_begin:
M.pop(0)
T.pop(0)
while T[-1] > t_end:
M.pop(-1)
T.pop(-1)
# prepare the signal:
# from M(T) array with unequal deltaT
# to M(T) array with deltaT=(1 degree).
# if delataT is larger, then points are added using linear fit between
# consecutive data points.
# exit if deltaT is not integer
i = 0
while i < (len(T) - 1):
if (T[i + 1] - T[i]) % 1 > 0.001:
print("delta T should be integer, this program will not work!")
print("temperature range:", T[i], T[i + 1])
sys.exit()
if (T[i + 1] - T[i]) == 0.:
M[i] = np.average([M[i], M[i + 1]])
M.pop(i + 1)
T.pop(i + 1)
elif (T[i + 1] - T[i]) < 0.:
M.pop(i + 1)
T.pop(i + 1)
print("check data in T=%.0f ,M[T] is ignored" % (T[i]))
elif (T[i + 1] - T[i]) > 1.:
slope, b = np.polyfit([T[i], T[i + 1]], [M[i], M[i + 1]], 1)
for j in range(int(T[i + 1]) - int(T[i]) - 1):
M.insert(i + 1, slope * (T[i] + 1.) + b)
T.insert(i + 1, (T[i] + 1.))
i = i + 1
i = i + 1
# calculate the smoothed signal
M = np.array(M, 'f')
T = np.array(T, 'f')
M_smooth = []
M_smooth = smooth(M, window_len)
# plot the original data and the smooth data
PLT = {'M_T': 1, 'der1': 2, 'der2': 3, 'Curie': 4}
plt.figure(num=PLT['M_T'], figsize=(5, 5))
string = 'M-T (sliding window=%i)' % int(window_len)
pmagplotlib.plot_xy(PLT['M_T'], T, M_smooth, sym='-')
pmagplotlib.plot_xy(PLT['M_T'], T, M, sym='--',
xlab='Temperature C', ylab='Magnetization', title=string)
# calculate first derivative
d1, T_d1 = [], []
for i in range(len(M_smooth) - 1):
Dy = M_smooth[i - 1] - M_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
d1.append(old_div(Dy, Dx))
T_d1 = T[1:len(T - 1)]
d1 = np.array(d1, 'f')
d1_smooth = smooth(d1, window_len)
# plot the first derivative
plt.figure(num=PLT['der1'], figsize=(5, 5))
string = '1st derivative (sliding window=%i)' % int(window_len)
pmagplotlib.plot_xy(PLT['der1'], T_d1, d1_smooth,
sym='-', xlab='Temperature C', title=string)
pmagplotlib.plot_xy(PLT['der1'], T_d1, d1, sym='b--')
# calculate second derivative
d2, T_d2 = [], []
for i in range(len(d1_smooth) - 1):
Dy = d1_smooth[i - 1] - d1_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
# print Dy/Dx
d2.append(old_div(Dy, Dx))
T_d2 = T[2:len(T - 2)]
d2 = np.array(d2, 'f')
d2_smooth = smooth(d2, window_len)
# plot the second derivative
plt.figure(num=PLT['der2'], figsize=(5, 5))
string = '2nd derivative (sliding window=%i)' % int(window_len)
pmagplotlib.plot_xy(PLT['der2'], T_d2, d2, sym='-',
xlab='Temperature C', title=string)
d2 = list(d2)
print('second derivative maximum is at T=%i' %
int(T_d2[d2.index(max(d2))]))
# calculate Curie temperature for different width of sliding windows
curie, curie_1 = [], []
wn = list(range(5, 50, 1))
for win in wn:
# calculate the smoothed signal
M_smooth = []
M_smooth = smooth(M, win)
# calculate first derivative
d1, T_d1 = [], []
for i in range(len(M_smooth) - 1):
Dy = M_smooth[i - 1] - M_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
d1.append(old_div(Dy, Dx))
T_d1 = T[1:len(T - 1)]
d1 = np.array(d1, 'f')
d1_smooth = smooth(d1, win)
# calculate second derivative
d2, T_d2 = [], []
for i in range(len(d1_smooth) - 1):
Dy = d1_smooth[i - 1] - d1_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
d2.append(old_div(Dy, Dx))
T_d2 = T[2:len(T - 2)]
d2 = np.array(d2, 'f')
d2_smooth = smooth(d2, win)
d2 = list(d2)
d2_smooth = list(d2_smooth)
curie.append(T_d2[d2.index(max(d2))])
curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))])
# plot Curie temp for different sliding window length
plt.figure(num=PLT['Curie'], figsize=(5, 5))
pmagplotlib.plot_xy(PLT['Curie'], wn, curie, sym='.',
xlab='Sliding Window Width (degrees)', ylab='Curie Temp', title='Curie Statistics')
files = {}
for key in list(PLT.keys()):
files[key] = str(key) + '.' + fmt
if save == True:
for key in list(PLT.keys()):
try:
plt.figure(num=PLT[key])
plt.savefig(save_folder + '/' + files[key].replace('/', '-'))
except:
print('could not save: ', PLT[key], files[key])
print("output file format not supported ")
plt.show() | def function[curie, parameter[path_to_file, file_name, magic, window_length, save, save_folder, fmt, t_begin, t_end]]:
constant[
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with width= <-w> degrees)
***
The 2nd derivative is calculated from smoothed 1st derivative curve
(using the same sliding window width)
***
The estimated curie temp. is the maximum of the 2nd derivative.
Temperature steps should be in multiples of 1.0 degrees.
Parameters
__________
file_name : name of file to be opened
Optional Parameters (defaults are used if not specified)
----------
path_to_file : path to directory that contains file (default is current directory, '.')
window_length : dimension of smoothing window (input to smooth() function)
save : boolean argument to save plots (default is False)
save_folder : relative directory where plots will be saved (default is current directory, '.')
fmt : format of saved figures
t_begin: start of truncated window for search
t_end: end of truncated window for search
magic : True if MagIC formated measurements.txt file
]
variable[plot] assign[=] constant[0]
variable[window_len] assign[=] name[window_length]
variable[complete_path] assign[=] call[name[os].path.join, parameter[name[path_to_file], name[file_name]]]
if name[magic] begin[:]
variable[data_df] assign[=] call[name[pd].read_csv, parameter[name[complete_path]]]
variable[T] assign[=] binary_operation[call[name[data_df]][constant[meas_temp]].values - constant[273]]
variable[magn_key] assign[=] call[name[cb].get_intensity_col, parameter[name[data_df]]]
variable[M] assign[=] call[name[data_df]][name[magn_key]].values
variable[T] assign[=] call[name[list], parameter[name[T]]]
variable[M] assign[=] call[name[list], parameter[name[M]]]
if compare[name[t_begin] not_equal[!=] constant[]] begin[:]
while compare[call[name[T]][constant[0]] less[<] name[t_begin]] begin[:]
call[name[M].pop, parameter[constant[0]]]
call[name[T].pop, parameter[constant[0]]]
while compare[call[name[T]][<ast.UnaryOp object at 0x7da1b26ae5f0>] greater[>] name[t_end]] begin[:]
call[name[M].pop, parameter[<ast.UnaryOp object at 0x7da1b26aff10>]]
call[name[T].pop, parameter[<ast.UnaryOp object at 0x7da1b26ad1b0>]]
variable[i] assign[=] constant[0]
while compare[name[i] less[<] binary_operation[call[name[len], parameter[name[T]]] - constant[1]]] begin[:]
if compare[binary_operation[binary_operation[call[name[T]][binary_operation[name[i] + constant[1]]] - call[name[T]][name[i]]] <ast.Mod object at 0x7da2590d6920> constant[1]] greater[>] constant[0.001]] begin[:]
call[name[print], parameter[constant[delta T should be integer, this program will not work!]]]
call[name[print], parameter[constant[temperature range:], call[name[T]][name[i]], call[name[T]][binary_operation[name[i] + constant[1]]]]]
call[name[sys].exit, parameter[]]
if compare[binary_operation[call[name[T]][binary_operation[name[i] + constant[1]]] - call[name[T]][name[i]]] equal[==] constant[0.0]] begin[:]
call[name[M]][name[i]] assign[=] call[name[np].average, parameter[list[[<ast.Subscript object at 0x7da1b26aeb60>, <ast.Subscript object at 0x7da1b26ae1a0>]]]]
call[name[M].pop, parameter[binary_operation[name[i] + constant[1]]]]
call[name[T].pop, parameter[binary_operation[name[i] + constant[1]]]]
variable[i] assign[=] binary_operation[name[i] + constant[1]]
variable[M] assign[=] call[name[np].array, parameter[name[M], constant[f]]]
variable[T] assign[=] call[name[np].array, parameter[name[T], constant[f]]]
variable[M_smooth] assign[=] list[[]]
variable[M_smooth] assign[=] call[name[smooth], parameter[name[M], name[window_len]]]
variable[PLT] assign[=] dictionary[[<ast.Constant object at 0x7da2054a5450>, <ast.Constant object at 0x7da2054a7700>, <ast.Constant object at 0x7da2054a5870>, <ast.Constant object at 0x7da2054a4580>], [<ast.Constant object at 0x7da2054a4760>, <ast.Constant object at 0x7da2054a7910>, <ast.Constant object at 0x7da2054a6230>, <ast.Constant object at 0x7da2054a7e20>]]
call[name[plt].figure, parameter[]]
variable[string] assign[=] binary_operation[constant[M-T (sliding window=%i)] <ast.Mod object at 0x7da2590d6920> call[name[int], parameter[name[window_len]]]]
call[name[pmagplotlib].plot_xy, parameter[call[name[PLT]][constant[M_T]], name[T], name[M_smooth]]]
call[name[pmagplotlib].plot_xy, parameter[call[name[PLT]][constant[M_T]], name[T], name[M]]]
<ast.Tuple object at 0x7da2054a4640> assign[=] tuple[[<ast.List object at 0x7da2054a6fe0>, <ast.List object at 0x7da2054a67a0>]]
for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[M_smooth]]] - constant[1]]]]] begin[:]
variable[Dy] assign[=] binary_operation[call[name[M_smooth]][binary_operation[name[i] - constant[1]]] - call[name[M_smooth]][binary_operation[name[i] + constant[1]]]]
variable[Dx] assign[=] binary_operation[call[name[T]][binary_operation[name[i] - constant[1]]] - call[name[T]][binary_operation[name[i] + constant[1]]]]
call[name[d1].append, parameter[call[name[old_div], parameter[name[Dy], name[Dx]]]]]
variable[T_d1] assign[=] call[name[T]][<ast.Slice object at 0x7da2054a52d0>]
variable[d1] assign[=] call[name[np].array, parameter[name[d1], constant[f]]]
variable[d1_smooth] assign[=] call[name[smooth], parameter[name[d1], name[window_len]]]
call[name[plt].figure, parameter[]]
variable[string] assign[=] binary_operation[constant[1st derivative (sliding window=%i)] <ast.Mod object at 0x7da2590d6920> call[name[int], parameter[name[window_len]]]]
call[name[pmagplotlib].plot_xy, parameter[call[name[PLT]][constant[der1]], name[T_d1], name[d1_smooth]]]
call[name[pmagplotlib].plot_xy, parameter[call[name[PLT]][constant[der1]], name[T_d1], name[d1]]]
<ast.Tuple object at 0x7da2054a4070> assign[=] tuple[[<ast.List object at 0x7da2054a51b0>, <ast.List object at 0x7da2054a4d90>]]
for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[d1_smooth]]] - constant[1]]]]] begin[:]
variable[Dy] assign[=] binary_operation[call[name[d1_smooth]][binary_operation[name[i] - constant[1]]] - call[name[d1_smooth]][binary_operation[name[i] + constant[1]]]]
variable[Dx] assign[=] binary_operation[call[name[T]][binary_operation[name[i] - constant[1]]] - call[name[T]][binary_operation[name[i] + constant[1]]]]
call[name[d2].append, parameter[call[name[old_div], parameter[name[Dy], name[Dx]]]]]
variable[T_d2] assign[=] call[name[T]][<ast.Slice object at 0x7da2054a7f70>]
variable[d2] assign[=] call[name[np].array, parameter[name[d2], constant[f]]]
variable[d2_smooth] assign[=] call[name[smooth], parameter[name[d2], name[window_len]]]
call[name[plt].figure, parameter[]]
variable[string] assign[=] binary_operation[constant[2nd derivative (sliding window=%i)] <ast.Mod object at 0x7da2590d6920> call[name[int], parameter[name[window_len]]]]
call[name[pmagplotlib].plot_xy, parameter[call[name[PLT]][constant[der2]], name[T_d2], name[d2]]]
variable[d2] assign[=] call[name[list], parameter[name[d2]]]
call[name[print], parameter[binary_operation[constant[second derivative maximum is at T=%i] <ast.Mod object at 0x7da2590d6920> call[name[int], parameter[call[name[T_d2]][call[name[d2].index, parameter[call[name[max], parameter[name[d2]]]]]]]]]]]
<ast.Tuple object at 0x7da18f00cd60> assign[=] tuple[[<ast.List object at 0x7da18f00efb0>, <ast.List object at 0x7da18f00f760>]]
variable[wn] assign[=] call[name[list], parameter[call[name[range], parameter[constant[5], constant[50], constant[1]]]]]
for taget[name[win]] in starred[name[wn]] begin[:]
variable[M_smooth] assign[=] list[[]]
variable[M_smooth] assign[=] call[name[smooth], parameter[name[M], name[win]]]
<ast.Tuple object at 0x7da18f00f5e0> assign[=] tuple[[<ast.List object at 0x7da18f00cbe0>, <ast.List object at 0x7da18f00c370>]]
for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[M_smooth]]] - constant[1]]]]] begin[:]
variable[Dy] assign[=] binary_operation[call[name[M_smooth]][binary_operation[name[i] - constant[1]]] - call[name[M_smooth]][binary_operation[name[i] + constant[1]]]]
variable[Dx] assign[=] binary_operation[call[name[T]][binary_operation[name[i] - constant[1]]] - call[name[T]][binary_operation[name[i] + constant[1]]]]
call[name[d1].append, parameter[call[name[old_div], parameter[name[Dy], name[Dx]]]]]
variable[T_d1] assign[=] call[name[T]][<ast.Slice object at 0x7da18f00c040>]
variable[d1] assign[=] call[name[np].array, parameter[name[d1], constant[f]]]
variable[d1_smooth] assign[=] call[name[smooth], parameter[name[d1], name[win]]]
<ast.Tuple object at 0x7da18f00f8b0> assign[=] tuple[[<ast.List object at 0x7da18f00ce80>, <ast.List object at 0x7da18f00cee0>]]
for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[d1_smooth]]] - constant[1]]]]] begin[:]
variable[Dy] assign[=] binary_operation[call[name[d1_smooth]][binary_operation[name[i] - constant[1]]] - call[name[d1_smooth]][binary_operation[name[i] + constant[1]]]]
variable[Dx] assign[=] binary_operation[call[name[T]][binary_operation[name[i] - constant[1]]] - call[name[T]][binary_operation[name[i] + constant[1]]]]
call[name[d2].append, parameter[call[name[old_div], parameter[name[Dy], name[Dx]]]]]
variable[T_d2] assign[=] call[name[T]][<ast.Slice object at 0x7da18f00c700>]
variable[d2] assign[=] call[name[np].array, parameter[name[d2], constant[f]]]
variable[d2_smooth] assign[=] call[name[smooth], parameter[name[d2], name[win]]]
variable[d2] assign[=] call[name[list], parameter[name[d2]]]
variable[d2_smooth] assign[=] call[name[list], parameter[name[d2_smooth]]]
call[name[curie].append, parameter[call[name[T_d2]][call[name[d2].index, parameter[call[name[max], parameter[name[d2]]]]]]]]
call[name[curie_1].append, parameter[call[name[T_d2]][call[name[d2_smooth].index, parameter[call[name[max], parameter[name[d2_smooth]]]]]]]]
call[name[plt].figure, parameter[]]
call[name[pmagplotlib].plot_xy, parameter[call[name[PLT]][constant[Curie]], name[wn], name[curie]]]
variable[files] assign[=] dictionary[[], []]
for taget[name[key]] in starred[call[name[list], parameter[call[name[PLT].keys, parameter[]]]]] begin[:]
call[name[files]][name[key]] assign[=] binary_operation[binary_operation[call[name[str], parameter[name[key]]] + constant[.]] + name[fmt]]
if compare[name[save] equal[==] constant[True]] begin[:]
for taget[name[key]] in starred[call[name[list], parameter[call[name[PLT].keys, parameter[]]]]] begin[:]
<ast.Try object at 0x7da18f8108e0>
call[name[plt].show, parameter[]] | keyword[def] identifier[curie] ( identifier[path_to_file] = literal[string] , identifier[file_name] = literal[string] , identifier[magic] = keyword[False] ,
identifier[window_length] = literal[int] , identifier[save] = keyword[False] , identifier[save_folder] = literal[string] , identifier[fmt] = literal[string] , identifier[t_begin] = literal[string] , identifier[t_end] = literal[string] ):
literal[string]
identifier[plot] = literal[int]
identifier[window_len] = identifier[window_length]
identifier[complete_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[path_to_file] , identifier[file_name] )
keyword[if] identifier[magic] :
identifier[data_df] = identifier[pd] . identifier[read_csv] ( identifier[complete_path] , identifier[sep] = literal[string] , identifier[header] = literal[int] )
identifier[T] = identifier[data_df] [ literal[string] ]. identifier[values] - literal[int]
identifier[magn_key] = identifier[cb] . identifier[get_intensity_col] ( identifier[data_df] )
identifier[M] = identifier[data_df] [ identifier[magn_key] ]. identifier[values]
keyword[else] :
identifier[Data] = identifier[np] . identifier[loadtxt] ( identifier[complete_path] , identifier[dtype] = identifier[np] . identifier[float] )
identifier[T] = identifier[Data] . identifier[transpose] ()[ literal[int] ]
identifier[M] = identifier[Data] . identifier[transpose] ()[ literal[int] ]
identifier[T] = identifier[list] ( identifier[T] )
identifier[M] = identifier[list] ( identifier[M] )
keyword[if] identifier[t_begin] != literal[string] :
keyword[while] identifier[T] [ literal[int] ]< identifier[t_begin] :
identifier[M] . identifier[pop] ( literal[int] )
identifier[T] . identifier[pop] ( literal[int] )
keyword[while] identifier[T] [- literal[int] ]> identifier[t_end] :
identifier[M] . identifier[pop] (- literal[int] )
identifier[T] . identifier[pop] (- literal[int] )
identifier[i] = literal[int]
keyword[while] identifier[i] <( identifier[len] ( identifier[T] )- literal[int] ):
keyword[if] ( identifier[T] [ identifier[i] + literal[int] ]- identifier[T] [ identifier[i] ])% literal[int] > literal[int] :
identifier[print] ( literal[string] )
identifier[print] ( literal[string] , identifier[T] [ identifier[i] ], identifier[T] [ identifier[i] + literal[int] ])
identifier[sys] . identifier[exit] ()
keyword[if] ( identifier[T] [ identifier[i] + literal[int] ]- identifier[T] [ identifier[i] ])== literal[int] :
identifier[M] [ identifier[i] ]= identifier[np] . identifier[average] ([ identifier[M] [ identifier[i] ], identifier[M] [ identifier[i] + literal[int] ]])
identifier[M] . identifier[pop] ( identifier[i] + literal[int] )
identifier[T] . identifier[pop] ( identifier[i] + literal[int] )
keyword[elif] ( identifier[T] [ identifier[i] + literal[int] ]- identifier[T] [ identifier[i] ])< literal[int] :
identifier[M] . identifier[pop] ( identifier[i] + literal[int] )
identifier[T] . identifier[pop] ( identifier[i] + literal[int] )
identifier[print] ( literal[string] %( identifier[T] [ identifier[i] ]))
keyword[elif] ( identifier[T] [ identifier[i] + literal[int] ]- identifier[T] [ identifier[i] ])> literal[int] :
identifier[slope] , identifier[b] = identifier[np] . identifier[polyfit] ([ identifier[T] [ identifier[i] ], identifier[T] [ identifier[i] + literal[int] ]],[ identifier[M] [ identifier[i] ], identifier[M] [ identifier[i] + literal[int] ]], literal[int] )
keyword[for] identifier[j] keyword[in] identifier[range] ( identifier[int] ( identifier[T] [ identifier[i] + literal[int] ])- identifier[int] ( identifier[T] [ identifier[i] ])- literal[int] ):
identifier[M] . identifier[insert] ( identifier[i] + literal[int] , identifier[slope] *( identifier[T] [ identifier[i] ]+ literal[int] )+ identifier[b] )
identifier[T] . identifier[insert] ( identifier[i] + literal[int] ,( identifier[T] [ identifier[i] ]+ literal[int] ))
identifier[i] = identifier[i] + literal[int]
identifier[i] = identifier[i] + literal[int]
identifier[M] = identifier[np] . identifier[array] ( identifier[M] , literal[string] )
identifier[T] = identifier[np] . identifier[array] ( identifier[T] , literal[string] )
identifier[M_smooth] =[]
identifier[M_smooth] = identifier[smooth] ( identifier[M] , identifier[window_len] )
identifier[PLT] ={ literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] }
identifier[plt] . identifier[figure] ( identifier[num] = identifier[PLT] [ literal[string] ], identifier[figsize] =( literal[int] , literal[int] ))
identifier[string] = literal[string] % identifier[int] ( identifier[window_len] )
identifier[pmagplotlib] . identifier[plot_xy] ( identifier[PLT] [ literal[string] ], identifier[T] , identifier[M_smooth] , identifier[sym] = literal[string] )
identifier[pmagplotlib] . identifier[plot_xy] ( identifier[PLT] [ literal[string] ], identifier[T] , identifier[M] , identifier[sym] = literal[string] ,
identifier[xlab] = literal[string] , identifier[ylab] = literal[string] , identifier[title] = identifier[string] )
identifier[d1] , identifier[T_d1] =[],[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[M_smooth] )- literal[int] ):
identifier[Dy] = identifier[M_smooth] [ identifier[i] - literal[int] ]- identifier[M_smooth] [ identifier[i] + literal[int] ]
identifier[Dx] = identifier[T] [ identifier[i] - literal[int] ]- identifier[T] [ identifier[i] + literal[int] ]
identifier[d1] . identifier[append] ( identifier[old_div] ( identifier[Dy] , identifier[Dx] ))
identifier[T_d1] = identifier[T] [ literal[int] : identifier[len] ( identifier[T] - literal[int] )]
identifier[d1] = identifier[np] . identifier[array] ( identifier[d1] , literal[string] )
identifier[d1_smooth] = identifier[smooth] ( identifier[d1] , identifier[window_len] )
identifier[plt] . identifier[figure] ( identifier[num] = identifier[PLT] [ literal[string] ], identifier[figsize] =( literal[int] , literal[int] ))
identifier[string] = literal[string] % identifier[int] ( identifier[window_len] )
identifier[pmagplotlib] . identifier[plot_xy] ( identifier[PLT] [ literal[string] ], identifier[T_d1] , identifier[d1_smooth] ,
identifier[sym] = literal[string] , identifier[xlab] = literal[string] , identifier[title] = identifier[string] )
identifier[pmagplotlib] . identifier[plot_xy] ( identifier[PLT] [ literal[string] ], identifier[T_d1] , identifier[d1] , identifier[sym] = literal[string] )
identifier[d2] , identifier[T_d2] =[],[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[d1_smooth] )- literal[int] ):
identifier[Dy] = identifier[d1_smooth] [ identifier[i] - literal[int] ]- identifier[d1_smooth] [ identifier[i] + literal[int] ]
identifier[Dx] = identifier[T] [ identifier[i] - literal[int] ]- identifier[T] [ identifier[i] + literal[int] ]
identifier[d2] . identifier[append] ( identifier[old_div] ( identifier[Dy] , identifier[Dx] ))
identifier[T_d2] = identifier[T] [ literal[int] : identifier[len] ( identifier[T] - literal[int] )]
identifier[d2] = identifier[np] . identifier[array] ( identifier[d2] , literal[string] )
identifier[d2_smooth] = identifier[smooth] ( identifier[d2] , identifier[window_len] )
identifier[plt] . identifier[figure] ( identifier[num] = identifier[PLT] [ literal[string] ], identifier[figsize] =( literal[int] , literal[int] ))
identifier[string] = literal[string] % identifier[int] ( identifier[window_len] )
identifier[pmagplotlib] . identifier[plot_xy] ( identifier[PLT] [ literal[string] ], identifier[T_d2] , identifier[d2] , identifier[sym] = literal[string] ,
identifier[xlab] = literal[string] , identifier[title] = identifier[string] )
identifier[d2] = identifier[list] ( identifier[d2] )
identifier[print] ( literal[string] %
identifier[int] ( identifier[T_d2] [ identifier[d2] . identifier[index] ( identifier[max] ( identifier[d2] ))]))
identifier[curie] , identifier[curie_1] =[],[]
identifier[wn] = identifier[list] ( identifier[range] ( literal[int] , literal[int] , literal[int] ))
keyword[for] identifier[win] keyword[in] identifier[wn] :
identifier[M_smooth] =[]
identifier[M_smooth] = identifier[smooth] ( identifier[M] , identifier[win] )
identifier[d1] , identifier[T_d1] =[],[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[M_smooth] )- literal[int] ):
identifier[Dy] = identifier[M_smooth] [ identifier[i] - literal[int] ]- identifier[M_smooth] [ identifier[i] + literal[int] ]
identifier[Dx] = identifier[T] [ identifier[i] - literal[int] ]- identifier[T] [ identifier[i] + literal[int] ]
identifier[d1] . identifier[append] ( identifier[old_div] ( identifier[Dy] , identifier[Dx] ))
identifier[T_d1] = identifier[T] [ literal[int] : identifier[len] ( identifier[T] - literal[int] )]
identifier[d1] = identifier[np] . identifier[array] ( identifier[d1] , literal[string] )
identifier[d1_smooth] = identifier[smooth] ( identifier[d1] , identifier[win] )
identifier[d2] , identifier[T_d2] =[],[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[d1_smooth] )- literal[int] ):
identifier[Dy] = identifier[d1_smooth] [ identifier[i] - literal[int] ]- identifier[d1_smooth] [ identifier[i] + literal[int] ]
identifier[Dx] = identifier[T] [ identifier[i] - literal[int] ]- identifier[T] [ identifier[i] + literal[int] ]
identifier[d2] . identifier[append] ( identifier[old_div] ( identifier[Dy] , identifier[Dx] ))
identifier[T_d2] = identifier[T] [ literal[int] : identifier[len] ( identifier[T] - literal[int] )]
identifier[d2] = identifier[np] . identifier[array] ( identifier[d2] , literal[string] )
identifier[d2_smooth] = identifier[smooth] ( identifier[d2] , identifier[win] )
identifier[d2] = identifier[list] ( identifier[d2] )
identifier[d2_smooth] = identifier[list] ( identifier[d2_smooth] )
identifier[curie] . identifier[append] ( identifier[T_d2] [ identifier[d2] . identifier[index] ( identifier[max] ( identifier[d2] ))])
identifier[curie_1] . identifier[append] ( identifier[T_d2] [ identifier[d2_smooth] . identifier[index] ( identifier[max] ( identifier[d2_smooth] ))])
identifier[plt] . identifier[figure] ( identifier[num] = identifier[PLT] [ literal[string] ], identifier[figsize] =( literal[int] , literal[int] ))
identifier[pmagplotlib] . identifier[plot_xy] ( identifier[PLT] [ literal[string] ], identifier[wn] , identifier[curie] , identifier[sym] = literal[string] ,
identifier[xlab] = literal[string] , identifier[ylab] = literal[string] , identifier[title] = literal[string] )
identifier[files] ={}
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[PLT] . identifier[keys] ()):
identifier[files] [ identifier[key] ]= identifier[str] ( identifier[key] )+ literal[string] + identifier[fmt]
keyword[if] identifier[save] == keyword[True] :
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[PLT] . identifier[keys] ()):
keyword[try] :
identifier[plt] . identifier[figure] ( identifier[num] = identifier[PLT] [ identifier[key] ])
identifier[plt] . identifier[savefig] ( identifier[save_folder] + literal[string] + identifier[files] [ identifier[key] ]. identifier[replace] ( literal[string] , literal[string] ))
keyword[except] :
identifier[print] ( literal[string] , identifier[PLT] [ identifier[key] ], identifier[files] [ identifier[key] ])
identifier[print] ( literal[string] )
identifier[plt] . identifier[show] () | def curie(path_to_file='.', file_name='', magic=False, window_length=3, save=False, save_folder='.', fmt='svg', t_begin='', t_end=''):
"""
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with width= <-w> degrees)
***
The 2nd derivative is calculated from smoothed 1st derivative curve
(using the same sliding window width)
***
The estimated curie temp. is the maximum of the 2nd derivative.
Temperature steps should be in multiples of 1.0 degrees.
Parameters
__________
file_name : name of file to be opened
Optional Parameters (defaults are used if not specified)
----------
path_to_file : path to directory that contains file (default is current directory, '.')
window_length : dimension of smoothing window (input to smooth() function)
save : boolean argument to save plots (default is False)
save_folder : relative directory where plots will be saved (default is current directory, '.')
fmt : format of saved figures
t_begin: start of truncated window for search
t_end: end of truncated window for search
magic : True if MagIC formated measurements.txt file
"""
plot = 0
window_len = window_length
# read data from file
complete_path = os.path.join(path_to_file, file_name)
if magic:
data_df = pd.read_csv(complete_path, sep='\t', header=1)
T = data_df['meas_temp'].values - 273
magn_key = cb.get_intensity_col(data_df)
M = data_df[magn_key].values # depends on [control=['if'], data=[]]
else:
Data = np.loadtxt(complete_path, dtype=np.float)
T = Data.transpose()[0]
M = Data.transpose()[1]
T = list(T)
M = list(M)
# cut the data if -t is one of the flags
if t_begin != '':
while T[0] < t_begin:
M.pop(0)
T.pop(0) # depends on [control=['while'], data=[]]
while T[-1] > t_end:
M.pop(-1)
T.pop(-1) # depends on [control=['while'], data=[]] # depends on [control=['if'], data=['t_begin']]
# prepare the signal:
# from M(T) array with unequal deltaT
# to M(T) array with deltaT=(1 degree).
# if delataT is larger, then points are added using linear fit between
# consecutive data points.
# exit if deltaT is not integer
i = 0
while i < len(T) - 1:
if (T[i + 1] - T[i]) % 1 > 0.001:
print('delta T should be integer, this program will not work!')
print('temperature range:', T[i], T[i + 1])
sys.exit() # depends on [control=['if'], data=[]]
if T[i + 1] - T[i] == 0.0:
M[i] = np.average([M[i], M[i + 1]])
M.pop(i + 1)
T.pop(i + 1) # depends on [control=['if'], data=[]]
elif T[i + 1] - T[i] < 0.0:
M.pop(i + 1)
T.pop(i + 1)
print('check data in T=%.0f ,M[T] is ignored' % T[i]) # depends on [control=['if'], data=[]]
elif T[i + 1] - T[i] > 1.0:
(slope, b) = np.polyfit([T[i], T[i + 1]], [M[i], M[i + 1]], 1)
for j in range(int(T[i + 1]) - int(T[i]) - 1):
M.insert(i + 1, slope * (T[i] + 1.0) + b)
T.insert(i + 1, T[i] + 1.0)
i = i + 1 # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
i = i + 1 # depends on [control=['while'], data=['i']]
# calculate the smoothed signal
M = np.array(M, 'f')
T = np.array(T, 'f')
M_smooth = []
M_smooth = smooth(M, window_len)
# plot the original data and the smooth data
PLT = {'M_T': 1, 'der1': 2, 'der2': 3, 'Curie': 4}
plt.figure(num=PLT['M_T'], figsize=(5, 5))
string = 'M-T (sliding window=%i)' % int(window_len)
pmagplotlib.plot_xy(PLT['M_T'], T, M_smooth, sym='-')
pmagplotlib.plot_xy(PLT['M_T'], T, M, sym='--', xlab='Temperature C', ylab='Magnetization', title=string)
# calculate first derivative
(d1, T_d1) = ([], [])
for i in range(len(M_smooth) - 1):
Dy = M_smooth[i - 1] - M_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
d1.append(old_div(Dy, Dx)) # depends on [control=['for'], data=['i']]
T_d1 = T[1:len(T - 1)]
d1 = np.array(d1, 'f')
d1_smooth = smooth(d1, window_len)
# plot the first derivative
plt.figure(num=PLT['der1'], figsize=(5, 5))
string = '1st derivative (sliding window=%i)' % int(window_len)
pmagplotlib.plot_xy(PLT['der1'], T_d1, d1_smooth, sym='-', xlab='Temperature C', title=string)
pmagplotlib.plot_xy(PLT['der1'], T_d1, d1, sym='b--')
# calculate second derivative
(d2, T_d2) = ([], [])
for i in range(len(d1_smooth) - 1):
Dy = d1_smooth[i - 1] - d1_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
# print Dy/Dx
d2.append(old_div(Dy, Dx)) # depends on [control=['for'], data=['i']]
T_d2 = T[2:len(T - 2)]
d2 = np.array(d2, 'f')
d2_smooth = smooth(d2, window_len)
# plot the second derivative
plt.figure(num=PLT['der2'], figsize=(5, 5))
string = '2nd derivative (sliding window=%i)' % int(window_len)
pmagplotlib.plot_xy(PLT['der2'], T_d2, d2, sym='-', xlab='Temperature C', title=string)
d2 = list(d2)
print('second derivative maximum is at T=%i' % int(T_d2[d2.index(max(d2))]))
# calculate Curie temperature for different width of sliding windows
(curie, curie_1) = ([], [])
wn = list(range(5, 50, 1))
for win in wn:
# calculate the smoothed signal
M_smooth = []
M_smooth = smooth(M, win)
# calculate first derivative
(d1, T_d1) = ([], [])
for i in range(len(M_smooth) - 1):
Dy = M_smooth[i - 1] - M_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
d1.append(old_div(Dy, Dx)) # depends on [control=['for'], data=['i']]
T_d1 = T[1:len(T - 1)]
d1 = np.array(d1, 'f')
d1_smooth = smooth(d1, win)
# calculate second derivative
(d2, T_d2) = ([], [])
for i in range(len(d1_smooth) - 1):
Dy = d1_smooth[i - 1] - d1_smooth[i + 1]
Dx = T[i - 1] - T[i + 1]
d2.append(old_div(Dy, Dx)) # depends on [control=['for'], data=['i']]
T_d2 = T[2:len(T - 2)]
d2 = np.array(d2, 'f')
d2_smooth = smooth(d2, win)
d2 = list(d2)
d2_smooth = list(d2_smooth)
curie.append(T_d2[d2.index(max(d2))])
curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))]) # depends on [control=['for'], data=['win']]
# plot Curie temp for different sliding window length
plt.figure(num=PLT['Curie'], figsize=(5, 5))
pmagplotlib.plot_xy(PLT['Curie'], wn, curie, sym='.', xlab='Sliding Window Width (degrees)', ylab='Curie Temp', title='Curie Statistics')
files = {}
for key in list(PLT.keys()):
files[key] = str(key) + '.' + fmt # depends on [control=['for'], data=['key']]
if save == True:
for key in list(PLT.keys()):
try:
plt.figure(num=PLT[key])
plt.savefig(save_folder + '/' + files[key].replace('/', '-')) # depends on [control=['try'], data=[]]
except:
print('could not save: ', PLT[key], files[key])
print('output file format not supported ') # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['key']] # depends on [control=['if'], data=[]]
plt.show() |
def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
Returns:
Kraus: the tensor product channel as a Kraus object.
Raises:
QiskitError: if other cannot be converted to a channel.
"""
# Convert other to Kraus
if not isinstance(other, Kraus):
other = Kraus(other)
# Get tensor matrix
ka_l, ka_r = self._data
kb_l, kb_r = other._data
if reverse:
input_dims = self.input_dims() + other.input_dims()
output_dims = self.output_dims() + other.output_dims()
kab_l = [np.kron(b, a) for a in ka_l for b in kb_l]
else:
input_dims = other.input_dims() + self.input_dims()
output_dims = other.output_dims() + self.output_dims()
kab_l = [np.kron(a, b) for a in ka_l for b in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
else:
if ka_r is None:
ka_r = ka_l
if kb_r is None:
kb_r = kb_l
if reverse:
kab_r = [np.kron(b, a) for a in ka_r for b in kb_r]
else:
kab_r = [np.kron(a, b) for a in ka_r for b in kb_r]
data = (kab_l, kab_r)
return Kraus(data, input_dims, output_dims) | def function[_tensor_product, parameter[self, other, reverse]]:
constant[Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
Returns:
Kraus: the tensor product channel as a Kraus object.
Raises:
QiskitError: if other cannot be converted to a channel.
]
if <ast.UnaryOp object at 0x7da1b05ad9f0> begin[:]
variable[other] assign[=] call[name[Kraus], parameter[name[other]]]
<ast.Tuple object at 0x7da1b05adc00> assign[=] name[self]._data
<ast.Tuple object at 0x7da1b05add20> assign[=] name[other]._data
if name[reverse] begin[:]
variable[input_dims] assign[=] binary_operation[call[name[self].input_dims, parameter[]] + call[name[other].input_dims, parameter[]]]
variable[output_dims] assign[=] binary_operation[call[name[self].output_dims, parameter[]] + call[name[other].output_dims, parameter[]]]
variable[kab_l] assign[=] <ast.ListComp object at 0x7da1b05ae800>
if <ast.BoolOp object at 0x7da1b05ae230> begin[:]
variable[kab_r] assign[=] constant[None]
variable[data] assign[=] tuple[[<ast.Name object at 0x7da1b05ad210>, <ast.Name object at 0x7da1b05ad240>]]
return[call[name[Kraus], parameter[name[data], name[input_dims], name[output_dims]]]] | keyword[def] identifier[_tensor_product] ( identifier[self] , identifier[other] , identifier[reverse] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[Kraus] ):
identifier[other] = identifier[Kraus] ( identifier[other] )
identifier[ka_l] , identifier[ka_r] = identifier[self] . identifier[_data]
identifier[kb_l] , identifier[kb_r] = identifier[other] . identifier[_data]
keyword[if] identifier[reverse] :
identifier[input_dims] = identifier[self] . identifier[input_dims] ()+ identifier[other] . identifier[input_dims] ()
identifier[output_dims] = identifier[self] . identifier[output_dims] ()+ identifier[other] . identifier[output_dims] ()
identifier[kab_l] =[ identifier[np] . identifier[kron] ( identifier[b] , identifier[a] ) keyword[for] identifier[a] keyword[in] identifier[ka_l] keyword[for] identifier[b] keyword[in] identifier[kb_l] ]
keyword[else] :
identifier[input_dims] = identifier[other] . identifier[input_dims] ()+ identifier[self] . identifier[input_dims] ()
identifier[output_dims] = identifier[other] . identifier[output_dims] ()+ identifier[self] . identifier[output_dims] ()
identifier[kab_l] =[ identifier[np] . identifier[kron] ( identifier[a] , identifier[b] ) keyword[for] identifier[a] keyword[in] identifier[ka_l] keyword[for] identifier[b] keyword[in] identifier[kb_l] ]
keyword[if] identifier[ka_r] keyword[is] keyword[None] keyword[and] identifier[kb_r] keyword[is] keyword[None] :
identifier[kab_r] = keyword[None]
keyword[else] :
keyword[if] identifier[ka_r] keyword[is] keyword[None] :
identifier[ka_r] = identifier[ka_l]
keyword[if] identifier[kb_r] keyword[is] keyword[None] :
identifier[kb_r] = identifier[kb_l]
keyword[if] identifier[reverse] :
identifier[kab_r] =[ identifier[np] . identifier[kron] ( identifier[b] , identifier[a] ) keyword[for] identifier[a] keyword[in] identifier[ka_r] keyword[for] identifier[b] keyword[in] identifier[kb_r] ]
keyword[else] :
identifier[kab_r] =[ identifier[np] . identifier[kron] ( identifier[a] , identifier[b] ) keyword[for] identifier[a] keyword[in] identifier[ka_r] keyword[for] identifier[b] keyword[in] identifier[kb_r] ]
identifier[data] =( identifier[kab_l] , identifier[kab_r] )
keyword[return] identifier[Kraus] ( identifier[data] , identifier[input_dims] , identifier[output_dims] ) | def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
Returns:
Kraus: the tensor product channel as a Kraus object.
Raises:
QiskitError: if other cannot be converted to a channel.
"""
# Convert other to Kraus
if not isinstance(other, Kraus):
other = Kraus(other) # depends on [control=['if'], data=[]]
# Get tensor matrix
(ka_l, ka_r) = self._data
(kb_l, kb_r) = other._data
if reverse:
input_dims = self.input_dims() + other.input_dims()
output_dims = self.output_dims() + other.output_dims()
kab_l = [np.kron(b, a) for a in ka_l for b in kb_l] # depends on [control=['if'], data=[]]
else:
input_dims = other.input_dims() + self.input_dims()
output_dims = other.output_dims() + self.output_dims()
kab_l = [np.kron(a, b) for a in ka_l for b in kb_l]
if ka_r is None and kb_r is None:
kab_r = None # depends on [control=['if'], data=[]]
else:
if ka_r is None:
ka_r = ka_l # depends on [control=['if'], data=['ka_r']]
if kb_r is None:
kb_r = kb_l # depends on [control=['if'], data=['kb_r']]
if reverse:
kab_r = [np.kron(b, a) for a in ka_r for b in kb_r] # depends on [control=['if'], data=[]]
else:
kab_r = [np.kron(a, b) for a in ka_r for b in kb_r]
data = (kab_l, kab_r)
return Kraus(data, input_dims, output_dims) |
def dirs(self, pattern=None):
""" D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
With the optional `pattern` argument, this only lists
directories whose names match the given pattern. For
example, ``d.dirs('build-*')``.
"""
return [p for p in self.listdir(pattern) if p.isdir()] | def function[dirs, parameter[self, pattern]]:
constant[ D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
With the optional `pattern` argument, this only lists
directories whose names match the given pattern. For
example, ``d.dirs('build-*')``.
]
return[<ast.ListComp object at 0x7da2041da6b0>] | keyword[def] identifier[dirs] ( identifier[self] , identifier[pattern] = keyword[None] ):
literal[string]
keyword[return] [ identifier[p] keyword[for] identifier[p] keyword[in] identifier[self] . identifier[listdir] ( identifier[pattern] ) keyword[if] identifier[p] . identifier[isdir] ()] | def dirs(self, pattern=None):
""" D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
With the optional `pattern` argument, this only lists
directories whose names match the given pattern. For
example, ``d.dirs('build-*')``.
"""
return [p for p in self.listdir(pattern) if p.isdir()] |
def get_list_w_id2nts(ids, id2nts, flds, dflt_null=""):
"""Return a new list of namedtuples by combining "dicts" of namedtuples or objects."""
combined_nt_list = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Fill dict with namedtuple objects for desired ids
for item_id in ids:
# 2a. Combine various namedtuples into a single namedtuple
nts = [id2nt.get(item_id) for id2nt in id2nts]
vals = _combine_nt_vals(nts, flds, dflt_null)
combined_nt_list.append(ntobj._make(vals))
return combined_nt_list | def function[get_list_w_id2nts, parameter[ids, id2nts, flds, dflt_null]]:
constant[Return a new list of namedtuples by combining "dicts" of namedtuples or objects.]
variable[combined_nt_list] assign[=] list[[]]
variable[ntobj] assign[=] call[name[cx].namedtuple, parameter[constant[Nt], call[constant[ ].join, parameter[name[flds]]]]]
for taget[name[item_id]] in starred[name[ids]] begin[:]
variable[nts] assign[=] <ast.ListComp object at 0x7da1b2347a90>
variable[vals] assign[=] call[name[_combine_nt_vals], parameter[name[nts], name[flds], name[dflt_null]]]
call[name[combined_nt_list].append, parameter[call[name[ntobj]._make, parameter[name[vals]]]]]
return[name[combined_nt_list]] | keyword[def] identifier[get_list_w_id2nts] ( identifier[ids] , identifier[id2nts] , identifier[flds] , identifier[dflt_null] = literal[string] ):
literal[string]
identifier[combined_nt_list] =[]
identifier[ntobj] = identifier[cx] . identifier[namedtuple] ( literal[string] , literal[string] . identifier[join] ( identifier[flds] ))
keyword[for] identifier[item_id] keyword[in] identifier[ids] :
identifier[nts] =[ identifier[id2nt] . identifier[get] ( identifier[item_id] ) keyword[for] identifier[id2nt] keyword[in] identifier[id2nts] ]
identifier[vals] = identifier[_combine_nt_vals] ( identifier[nts] , identifier[flds] , identifier[dflt_null] )
identifier[combined_nt_list] . identifier[append] ( identifier[ntobj] . identifier[_make] ( identifier[vals] ))
keyword[return] identifier[combined_nt_list] | def get_list_w_id2nts(ids, id2nts, flds, dflt_null=''):
"""Return a new list of namedtuples by combining "dicts" of namedtuples or objects."""
combined_nt_list = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple('Nt', ' '.join(flds))
# 2. Fill dict with namedtuple objects for desired ids
for item_id in ids:
# 2a. Combine various namedtuples into a single namedtuple
nts = [id2nt.get(item_id) for id2nt in id2nts]
vals = _combine_nt_vals(nts, flds, dflt_null)
combined_nt_list.append(ntobj._make(vals)) # depends on [control=['for'], data=['item_id']]
return combined_nt_list |
def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(
name=fullname,
loader=self.loader_class(fullname, path),
origin=path,
is_package=(path.endswith('__init__.ipynb') or path.endswith('__init__.py')),
) | def function[find_spec, parameter[self, fullname, path, target]]:
constant[
Claims modules that are under ipynb.fs
]
if call[name[fullname].startswith, parameter[name[self].package_prefix]] begin[:]
for taget[name[path]] in starred[call[name[self]._get_paths, parameter[name[fullname]]]] begin[:]
if call[name[os].path.exists, parameter[name[path]]] begin[:]
return[call[name[ModuleSpec], parameter[]]] | keyword[def] identifier[find_spec] ( identifier[self] , identifier[fullname] , identifier[path] , identifier[target] = keyword[None] ):
literal[string]
keyword[if] identifier[fullname] . identifier[startswith] ( identifier[self] . identifier[package_prefix] ):
keyword[for] identifier[path] keyword[in] identifier[self] . identifier[_get_paths] ( identifier[fullname] ):
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ):
keyword[return] identifier[ModuleSpec] (
identifier[name] = identifier[fullname] ,
identifier[loader] = identifier[self] . identifier[loader_class] ( identifier[fullname] , identifier[path] ),
identifier[origin] = identifier[path] ,
identifier[is_package] =( identifier[path] . identifier[endswith] ( literal[string] ) keyword[or] identifier[path] . identifier[endswith] ( literal[string] )),
) | def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(name=fullname, loader=self.loader_class(fullname, path), origin=path, is_package=path.endswith('__init__.ipynb') or path.endswith('__init__.py')) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['path']] # depends on [control=['if'], data=[]] |
def _send_block_request(self, transaction):
"""
A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction including the request which should be continued.
"""
transaction = self._messageLayer.send_request(transaction.request)
# ... but don't forget to reset the acknowledge flag
transaction.request.acknowledged = False
self.send_datagram(transaction.request)
if transaction.request.type == defines.Types["CON"]:
self._start_retransmission(transaction, transaction.request) | def function[_send_block_request, parameter[self, transaction]]:
constant[
A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction including the request which should be continued.
]
variable[transaction] assign[=] call[name[self]._messageLayer.send_request, parameter[name[transaction].request]]
name[transaction].request.acknowledged assign[=] constant[False]
call[name[self].send_datagram, parameter[name[transaction].request]]
if compare[name[transaction].request.type equal[==] call[name[defines].Types][constant[CON]]] begin[:]
call[name[self]._start_retransmission, parameter[name[transaction], name[transaction].request]] | keyword[def] identifier[_send_block_request] ( identifier[self] , identifier[transaction] ):
literal[string]
identifier[transaction] = identifier[self] . identifier[_messageLayer] . identifier[send_request] ( identifier[transaction] . identifier[request] )
identifier[transaction] . identifier[request] . identifier[acknowledged] = keyword[False]
identifier[self] . identifier[send_datagram] ( identifier[transaction] . identifier[request] )
keyword[if] identifier[transaction] . identifier[request] . identifier[type] == identifier[defines] . identifier[Types] [ literal[string] ]:
identifier[self] . identifier[_start_retransmission] ( identifier[transaction] , identifier[transaction] . identifier[request] ) | def _send_block_request(self, transaction):
"""
A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction including the request which should be continued.
"""
transaction = self._messageLayer.send_request(transaction.request)
# ... but don't forget to reset the acknowledge flag
transaction.request.acknowledged = False
self.send_datagram(transaction.request)
if transaction.request.type == defines.Types['CON']:
self._start_retransmission(transaction, transaction.request) # depends on [control=['if'], data=[]] |
def make_tarball(
base_name,
base_dir,
compress="gzip",
verbose=0,
dry_run=0,
owner=None,
group=None,
):
"""Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the default)
'compress'
'bzip2'
None
For 'gzip' and 'bzip2' the internal tarfile module will be used.
For 'compress' the .tar will be created using tarfile, and then
we will spawn 'compress' afterwards.
The output tar file will be named 'base_name' + ".tar",
possibly plus the appropriate compression extension (".gz",
".bz2" or ".Z"). Return the output filename.
"""
# XXX GNU tar 1.13 has a nifty option to add a prefix directory.
# It's pretty new, though, so we certainly can't require it --
# but it would be nice to take advantage of it to skip the
# "create a tree of hardlinks" step! (Would also be nice to
# detect GNU tar to use its 'z' option and save a step.)
compress_ext = {"gzip": ".gz", "bzip2": ".bz2", "compress": ".Z"}
# flags for compression program, each element of list will be an argument
tarfile_compress_flag = {"gzip": "gz", "bzip2": "bz2"}
compress_flags = {"compress": ["-f"]}
if compress is not None and compress not in compress_ext.keys():
raise ValueError(
"bad value for 'compress': must be None, 'gzip',"
"'bzip2' or 'compress'"
)
archive_name = base_name + ".tar"
if compress and compress in tarfile_compress_flag:
archive_name += compress_ext[compress]
mode = "w:" + tarfile_compress_flag.get(compress, "")
mkpath(os.path.dirname(archive_name), dry_run=dry_run)
log.info("Creating tar file %s with mode %s" % (archive_name, mode))
uid = _get_uid(owner)
gid = _get_gid(group)
def _set_uid_gid(tarinfo):
if gid is not None:
tarinfo.gid = gid
tarinfo.gname = group
if uid is not None:
tarinfo.uid = uid
tarinfo.uname = owner
return tarinfo
if not dry_run:
tar = tarfile.open(archive_name, mode=mode)
# This recursively adds everything underneath base_dir
try:
try:
# Support for the `filter' parameter was added in Python 2.7,
# earlier versions will raise TypeError.
tar.add(base_dir, filter=_set_uid_gid)
except TypeError:
tar.add(base_dir)
finally:
tar.close()
if compress and compress not in tarfile_compress_flag:
spawn(
[compress] + compress_flags[compress] + [archive_name],
dry_run=dry_run,
)
return archive_name + compress_ext[compress]
else:
return archive_name | def function[make_tarball, parameter[base_name, base_dir, compress, verbose, dry_run, owner, group]]:
constant[Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the default)
'compress'
'bzip2'
None
For 'gzip' and 'bzip2' the internal tarfile module will be used.
For 'compress' the .tar will be created using tarfile, and then
we will spawn 'compress' afterwards.
The output tar file will be named 'base_name' + ".tar",
possibly plus the appropriate compression extension (".gz",
".bz2" or ".Z"). Return the output filename.
]
variable[compress_ext] assign[=] dictionary[[<ast.Constant object at 0x7da1b2121d20>, <ast.Constant object at 0x7da1b2121d80>, <ast.Constant object at 0x7da1b21212a0>], [<ast.Constant object at 0x7da1b2121240>, <ast.Constant object at 0x7da1b21212d0>, <ast.Constant object at 0x7da1b2121210>]]
variable[tarfile_compress_flag] assign[=] dictionary[[<ast.Constant object at 0x7da1b21214e0>, <ast.Constant object at 0x7da1b2121570>], [<ast.Constant object at 0x7da1b2121450>, <ast.Constant object at 0x7da1b21213c0>]]
variable[compress_flags] assign[=] dictionary[[<ast.Constant object at 0x7da1b2121390>], [<ast.List object at 0x7da1b2121420>]]
if <ast.BoolOp object at 0x7da1b21216c0> begin[:]
<ast.Raise object at 0x7da1b2121930>
variable[archive_name] assign[=] binary_operation[name[base_name] + constant[.tar]]
if <ast.BoolOp object at 0x7da1b2121660> begin[:]
<ast.AugAssign object at 0x7da1b2121f90>
variable[mode] assign[=] binary_operation[constant[w:] + call[name[tarfile_compress_flag].get, parameter[name[compress], constant[]]]]
call[name[mkpath], parameter[call[name[os].path.dirname, parameter[name[archive_name]]]]]
call[name[log].info, parameter[binary_operation[constant[Creating tar file %s with mode %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b21227d0>, <ast.Name object at 0x7da1b21227a0>]]]]]
variable[uid] assign[=] call[name[_get_uid], parameter[name[owner]]]
variable[gid] assign[=] call[name[_get_gid], parameter[name[group]]]
def function[_set_uid_gid, parameter[tarinfo]]:
if compare[name[gid] is_not constant[None]] begin[:]
name[tarinfo].gid assign[=] name[gid]
name[tarinfo].gname assign[=] name[group]
if compare[name[uid] is_not constant[None]] begin[:]
name[tarinfo].uid assign[=] name[uid]
name[tarinfo].uname assign[=] name[owner]
return[name[tarinfo]]
if <ast.UnaryOp object at 0x7da1b2123880> begin[:]
variable[tar] assign[=] call[name[tarfile].open, parameter[name[archive_name]]]
<ast.Try object at 0x7da1b2123b80>
if <ast.BoolOp object at 0x7da1b21209d0> begin[:]
call[name[spawn], parameter[binary_operation[binary_operation[list[[<ast.Name object at 0x7da1b21239a0>]] + call[name[compress_flags]][name[compress]]] + list[[<ast.Name object at 0x7da1b2123ca0>]]]]]
return[binary_operation[name[archive_name] + call[name[compress_ext]][name[compress]]]] | keyword[def] identifier[make_tarball] (
identifier[base_name] ,
identifier[base_dir] ,
identifier[compress] = literal[string] ,
identifier[verbose] = literal[int] ,
identifier[dry_run] = literal[int] ,
identifier[owner] = keyword[None] ,
identifier[group] = keyword[None] ,
):
literal[string]
identifier[compress_ext] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] }
identifier[tarfile_compress_flag] ={ literal[string] : literal[string] , literal[string] : literal[string] }
identifier[compress_flags] ={ literal[string] :[ literal[string] ]}
keyword[if] identifier[compress] keyword[is] keyword[not] keyword[None] keyword[and] identifier[compress] keyword[not] keyword[in] identifier[compress_ext] . identifier[keys] ():
keyword[raise] identifier[ValueError] (
literal[string]
literal[string]
)
identifier[archive_name] = identifier[base_name] + literal[string]
keyword[if] identifier[compress] keyword[and] identifier[compress] keyword[in] identifier[tarfile_compress_flag] :
identifier[archive_name] += identifier[compress_ext] [ identifier[compress] ]
identifier[mode] = literal[string] + identifier[tarfile_compress_flag] . identifier[get] ( identifier[compress] , literal[string] )
identifier[mkpath] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[archive_name] ), identifier[dry_run] = identifier[dry_run] )
identifier[log] . identifier[info] ( literal[string] %( identifier[archive_name] , identifier[mode] ))
identifier[uid] = identifier[_get_uid] ( identifier[owner] )
identifier[gid] = identifier[_get_gid] ( identifier[group] )
keyword[def] identifier[_set_uid_gid] ( identifier[tarinfo] ):
keyword[if] identifier[gid] keyword[is] keyword[not] keyword[None] :
identifier[tarinfo] . identifier[gid] = identifier[gid]
identifier[tarinfo] . identifier[gname] = identifier[group]
keyword[if] identifier[uid] keyword[is] keyword[not] keyword[None] :
identifier[tarinfo] . identifier[uid] = identifier[uid]
identifier[tarinfo] . identifier[uname] = identifier[owner]
keyword[return] identifier[tarinfo]
keyword[if] keyword[not] identifier[dry_run] :
identifier[tar] = identifier[tarfile] . identifier[open] ( identifier[archive_name] , identifier[mode] = identifier[mode] )
keyword[try] :
keyword[try] :
identifier[tar] . identifier[add] ( identifier[base_dir] , identifier[filter] = identifier[_set_uid_gid] )
keyword[except] identifier[TypeError] :
identifier[tar] . identifier[add] ( identifier[base_dir] )
keyword[finally] :
identifier[tar] . identifier[close] ()
keyword[if] identifier[compress] keyword[and] identifier[compress] keyword[not] keyword[in] identifier[tarfile_compress_flag] :
identifier[spawn] (
[ identifier[compress] ]+ identifier[compress_flags] [ identifier[compress] ]+[ identifier[archive_name] ],
identifier[dry_run] = identifier[dry_run] ,
)
keyword[return] identifier[archive_name] + identifier[compress_ext] [ identifier[compress] ]
keyword[else] :
keyword[return] identifier[archive_name] | def make_tarball(base_name, base_dir, compress='gzip', verbose=0, dry_run=0, owner=None, group=None):
"""Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the default)
'compress'
'bzip2'
None
For 'gzip' and 'bzip2' the internal tarfile module will be used.
For 'compress' the .tar will be created using tarfile, and then
we will spawn 'compress' afterwards.
The output tar file will be named 'base_name' + ".tar",
possibly plus the appropriate compression extension (".gz",
".bz2" or ".Z"). Return the output filename.
"""
# XXX GNU tar 1.13 has a nifty option to add a prefix directory.
# It's pretty new, though, so we certainly can't require it --
# but it would be nice to take advantage of it to skip the
# "create a tree of hardlinks" step! (Would also be nice to
# detect GNU tar to use its 'z' option and save a step.)
compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'}
# flags for compression program, each element of list will be an argument
tarfile_compress_flag = {'gzip': 'gz', 'bzip2': 'bz2'}
compress_flags = {'compress': ['-f']}
if compress is not None and compress not in compress_ext.keys():
raise ValueError("bad value for 'compress': must be None, 'gzip','bzip2' or 'compress'") # depends on [control=['if'], data=[]]
archive_name = base_name + '.tar'
if compress and compress in tarfile_compress_flag:
archive_name += compress_ext[compress] # depends on [control=['if'], data=[]]
mode = 'w:' + tarfile_compress_flag.get(compress, '')
mkpath(os.path.dirname(archive_name), dry_run=dry_run)
log.info('Creating tar file %s with mode %s' % (archive_name, mode))
uid = _get_uid(owner)
gid = _get_gid(group)
def _set_uid_gid(tarinfo):
if gid is not None:
tarinfo.gid = gid
tarinfo.gname = group # depends on [control=['if'], data=['gid']]
if uid is not None:
tarinfo.uid = uid
tarinfo.uname = owner # depends on [control=['if'], data=['uid']]
return tarinfo
if not dry_run:
tar = tarfile.open(archive_name, mode=mode)
# This recursively adds everything underneath base_dir
try:
try:
# Support for the `filter' parameter was added in Python 2.7,
# earlier versions will raise TypeError.
tar.add(base_dir, filter=_set_uid_gid) # depends on [control=['try'], data=[]]
except TypeError:
tar.add(base_dir) # depends on [control=['except'], data=[]] # depends on [control=['try'], data=[]]
finally:
tar.close() # depends on [control=['if'], data=[]]
if compress and compress not in tarfile_compress_flag:
spawn([compress] + compress_flags[compress] + [archive_name], dry_run=dry_run)
return archive_name + compress_ext[compress] # depends on [control=['if'], data=[]]
else:
return archive_name |
def _compute_resized_shape(from_shape, to_shape):
"""
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternatively an array with two or three dimensions.
to_shape : None or tuple of ints or tuple of floats or int or float or ndarray
New shape of the array.
* If None, then `from_shape` will be used as the new shape.
* If an int ``V``, then the new shape will be ``(V, V, [C])``, where ``C`` will be added if it
is part of `from_shape`.
* If a float ``V``, then the new shape will be ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old
height/width.
* If a tuple ``(H', W', [C'])`` of ints, then ``H'`` and ``W'`` will be used as the new height
and width.
* If a tuple ``(H', W', [C'])`` of floats (except ``C``), then ``H'`` and ``W'`` will
be used as the new height and width.
* If a numpy array, then the array's shape will be used.
Returns
-------
to_shape_computed : tuple of int
New shape.
"""
if is_np_array(from_shape):
from_shape = from_shape.shape
if is_np_array(to_shape):
to_shape = to_shape.shape
to_shape_computed = list(from_shape)
if to_shape is None:
pass
elif isinstance(to_shape, tuple):
do_assert(len(from_shape) in [2, 3])
do_assert(len(to_shape) in [2, 3])
if len(from_shape) == 3 and len(to_shape) == 3:
do_assert(from_shape[2] == to_shape[2])
elif len(to_shape) == 3:
to_shape_computed.append(to_shape[2])
do_assert(all([v is None or is_single_number(v) for v in to_shape[0:2]]),
"Expected the first two entries in to_shape to be None or numbers, "
+ "got types %s." % (str([type(v) for v in to_shape[0:2]]),))
for i, from_shape_i in enumerate(from_shape[0:2]):
if to_shape[i] is None:
to_shape_computed[i] = from_shape_i
elif is_single_integer(to_shape[i]):
to_shape_computed[i] = to_shape[i]
else: # float
to_shape_computed[i] = int(np.round(from_shape_i * to_shape[i]))
elif is_single_integer(to_shape) or is_single_float(to_shape):
to_shape_computed = _compute_resized_shape(from_shape, (to_shape, to_shape))
else:
raise Exception("Expected to_shape to be None or ndarray or tuple of floats or tuple of ints or single int "
+ "or single float, got %s." % (type(to_shape),))
return tuple(to_shape_computed) | def function[_compute_resized_shape, parameter[from_shape, to_shape]]:
constant[
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternatively an array with two or three dimensions.
to_shape : None or tuple of ints or tuple of floats or int or float or ndarray
New shape of the array.
* If None, then `from_shape` will be used as the new shape.
* If an int ``V``, then the new shape will be ``(V, V, [C])``, where ``C`` will be added if it
is part of `from_shape`.
* If a float ``V``, then the new shape will be ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old
height/width.
* If a tuple ``(H', W', [C'])`` of ints, then ``H'`` and ``W'`` will be used as the new height
and width.
* If a tuple ``(H', W', [C'])`` of floats (except ``C``), then ``H'`` and ``W'`` will
be used as the new height and width.
* If a numpy array, then the array's shape will be used.
Returns
-------
to_shape_computed : tuple of int
New shape.
]
if call[name[is_np_array], parameter[name[from_shape]]] begin[:]
variable[from_shape] assign[=] name[from_shape].shape
if call[name[is_np_array], parameter[name[to_shape]]] begin[:]
variable[to_shape] assign[=] name[to_shape].shape
variable[to_shape_computed] assign[=] call[name[list], parameter[name[from_shape]]]
if compare[name[to_shape] is constant[None]] begin[:]
pass
return[call[name[tuple], parameter[name[to_shape_computed]]]] | keyword[def] identifier[_compute_resized_shape] ( identifier[from_shape] , identifier[to_shape] ):
literal[string]
keyword[if] identifier[is_np_array] ( identifier[from_shape] ):
identifier[from_shape] = identifier[from_shape] . identifier[shape]
keyword[if] identifier[is_np_array] ( identifier[to_shape] ):
identifier[to_shape] = identifier[to_shape] . identifier[shape]
identifier[to_shape_computed] = identifier[list] ( identifier[from_shape] )
keyword[if] identifier[to_shape] keyword[is] keyword[None] :
keyword[pass]
keyword[elif] identifier[isinstance] ( identifier[to_shape] , identifier[tuple] ):
identifier[do_assert] ( identifier[len] ( identifier[from_shape] ) keyword[in] [ literal[int] , literal[int] ])
identifier[do_assert] ( identifier[len] ( identifier[to_shape] ) keyword[in] [ literal[int] , literal[int] ])
keyword[if] identifier[len] ( identifier[from_shape] )== literal[int] keyword[and] identifier[len] ( identifier[to_shape] )== literal[int] :
identifier[do_assert] ( identifier[from_shape] [ literal[int] ]== identifier[to_shape] [ literal[int] ])
keyword[elif] identifier[len] ( identifier[to_shape] )== literal[int] :
identifier[to_shape_computed] . identifier[append] ( identifier[to_shape] [ literal[int] ])
identifier[do_assert] ( identifier[all] ([ identifier[v] keyword[is] keyword[None] keyword[or] identifier[is_single_number] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[to_shape] [ literal[int] : literal[int] ]]),
literal[string]
+ literal[string] %( identifier[str] ([ identifier[type] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[to_shape] [ literal[int] : literal[int] ]]),))
keyword[for] identifier[i] , identifier[from_shape_i] keyword[in] identifier[enumerate] ( identifier[from_shape] [ literal[int] : literal[int] ]):
keyword[if] identifier[to_shape] [ identifier[i] ] keyword[is] keyword[None] :
identifier[to_shape_computed] [ identifier[i] ]= identifier[from_shape_i]
keyword[elif] identifier[is_single_integer] ( identifier[to_shape] [ identifier[i] ]):
identifier[to_shape_computed] [ identifier[i] ]= identifier[to_shape] [ identifier[i] ]
keyword[else] :
identifier[to_shape_computed] [ identifier[i] ]= identifier[int] ( identifier[np] . identifier[round] ( identifier[from_shape_i] * identifier[to_shape] [ identifier[i] ]))
keyword[elif] identifier[is_single_integer] ( identifier[to_shape] ) keyword[or] identifier[is_single_float] ( identifier[to_shape] ):
identifier[to_shape_computed] = identifier[_compute_resized_shape] ( identifier[from_shape] ,( identifier[to_shape] , identifier[to_shape] ))
keyword[else] :
keyword[raise] identifier[Exception] ( literal[string]
+ literal[string] %( identifier[type] ( identifier[to_shape] ),))
keyword[return] identifier[tuple] ( identifier[to_shape_computed] ) | def _compute_resized_shape(from_shape, to_shape):
"""
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternatively an array with two or three dimensions.
to_shape : None or tuple of ints or tuple of floats or int or float or ndarray
New shape of the array.
* If None, then `from_shape` will be used as the new shape.
* If an int ``V``, then the new shape will be ``(V, V, [C])``, where ``C`` will be added if it
is part of `from_shape`.
* If a float ``V``, then the new shape will be ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old
height/width.
* If a tuple ``(H', W', [C'])`` of ints, then ``H'`` and ``W'`` will be used as the new height
and width.
* If a tuple ``(H', W', [C'])`` of floats (except ``C``), then ``H'`` and ``W'`` will
be used as the new height and width.
* If a numpy array, then the array's shape will be used.
Returns
-------
to_shape_computed : tuple of int
New shape.
"""
if is_np_array(from_shape):
from_shape = from_shape.shape # depends on [control=['if'], data=[]]
if is_np_array(to_shape):
to_shape = to_shape.shape # depends on [control=['if'], data=[]]
to_shape_computed = list(from_shape)
if to_shape is None:
pass # depends on [control=['if'], data=[]]
elif isinstance(to_shape, tuple):
do_assert(len(from_shape) in [2, 3])
do_assert(len(to_shape) in [2, 3])
if len(from_shape) == 3 and len(to_shape) == 3:
do_assert(from_shape[2] == to_shape[2]) # depends on [control=['if'], data=[]]
elif len(to_shape) == 3:
to_shape_computed.append(to_shape[2]) # depends on [control=['if'], data=[]]
do_assert(all([v is None or is_single_number(v) for v in to_shape[0:2]]), 'Expected the first two entries in to_shape to be None or numbers, ' + 'got types %s.' % (str([type(v) for v in to_shape[0:2]]),))
for (i, from_shape_i) in enumerate(from_shape[0:2]):
if to_shape[i] is None:
to_shape_computed[i] = from_shape_i # depends on [control=['if'], data=[]]
elif is_single_integer(to_shape[i]):
to_shape_computed[i] = to_shape[i] # depends on [control=['if'], data=[]]
else: # float
to_shape_computed[i] = int(np.round(from_shape_i * to_shape[i])) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
elif is_single_integer(to_shape) or is_single_float(to_shape):
to_shape_computed = _compute_resized_shape(from_shape, (to_shape, to_shape)) # depends on [control=['if'], data=[]]
else:
raise Exception('Expected to_shape to be None or ndarray or tuple of floats or tuple of ints or single int ' + 'or single float, got %s.' % (type(to_shape),))
return tuple(to_shape_computed) |
def get_pyenv_paths(pyenv_root_func=None):
"""Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
"""
pyenv_root_func = pyenv_root_func or get_pyenv_root
pyenv_root = pyenv_root_func()
if pyenv_root is None:
return []
versions_dir = os.path.join(pyenv_root, 'versions')
paths = []
for version in sorted(os.listdir(versions_dir)):
path = os.path.join(versions_dir, version, 'bin')
if os.path.isdir(path):
paths.append(path)
return paths | def function[get_pyenv_paths, parameter[pyenv_root_func]]:
constant[Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
]
variable[pyenv_root_func] assign[=] <ast.BoolOp object at 0x7da1b1eef910>
variable[pyenv_root] assign[=] call[name[pyenv_root_func], parameter[]]
if compare[name[pyenv_root] is constant[None]] begin[:]
return[list[[]]]
variable[versions_dir] assign[=] call[name[os].path.join, parameter[name[pyenv_root], constant[versions]]]
variable[paths] assign[=] list[[]]
for taget[name[version]] in starred[call[name[sorted], parameter[call[name[os].listdir, parameter[name[versions_dir]]]]]] begin[:]
variable[path] assign[=] call[name[os].path.join, parameter[name[versions_dir], name[version], constant[bin]]]
if call[name[os].path.isdir, parameter[name[path]]] begin[:]
call[name[paths].append, parameter[name[path]]]
return[name[paths]] | keyword[def] identifier[get_pyenv_paths] ( identifier[pyenv_root_func] = keyword[None] ):
literal[string]
identifier[pyenv_root_func] = identifier[pyenv_root_func] keyword[or] identifier[get_pyenv_root]
identifier[pyenv_root] = identifier[pyenv_root_func] ()
keyword[if] identifier[pyenv_root] keyword[is] keyword[None] :
keyword[return] []
identifier[versions_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[pyenv_root] , literal[string] )
identifier[paths] =[]
keyword[for] identifier[version] keyword[in] identifier[sorted] ( identifier[os] . identifier[listdir] ( identifier[versions_dir] )):
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifier[versions_dir] , identifier[version] , literal[string] )
keyword[if] identifier[os] . identifier[path] . identifier[isdir] ( identifier[path] ):
identifier[paths] . identifier[append] ( identifier[path] )
keyword[return] identifier[paths] | def get_pyenv_paths(pyenv_root_func=None):
"""Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
"""
pyenv_root_func = pyenv_root_func or get_pyenv_root
pyenv_root = pyenv_root_func()
if pyenv_root is None:
return [] # depends on [control=['if'], data=[]]
versions_dir = os.path.join(pyenv_root, 'versions')
paths = []
for version in sorted(os.listdir(versions_dir)):
path = os.path.join(versions_dir, version, 'bin')
if os.path.isdir(path):
paths.append(path) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['version']]
return paths |
def render_user(self, *args, **kwargs):
'''
render, with userinfo
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, user_id = val2)
fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
'''
kind = kwargs.get('kind', args[0])
num = kwargs.get('num', args[1] if len(args) > 1 else 6)
with_tag = kwargs.get('with_tag', False)
user_id = kwargs.get('user_id', '')
glyph = kwargs.get('glyph', '')
logger.info(
'Infor user recent, username: {user_name}, kind: {kind}, num: {num}'.format(
user_name=user_id, kind=kind, num=num
)
)
all_cats = MUsage.query_recent(user_id, kind, num).objects()
kwd = {
'with_tag': with_tag,
'router': router_post[kind],
'glyph': glyph
}
return self.render_string('modules/info/list_user_equation.html',
recs=all_cats,
kwd=kwd) | def function[render_user, parameter[self]]:
constant[
render, with userinfo
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, user_id = val2)
fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
]
variable[kind] assign[=] call[name[kwargs].get, parameter[constant[kind], call[name[args]][constant[0]]]]
variable[num] assign[=] call[name[kwargs].get, parameter[constant[num], <ast.IfExp object at 0x7da1b04f8eb0>]]
variable[with_tag] assign[=] call[name[kwargs].get, parameter[constant[with_tag], constant[False]]]
variable[user_id] assign[=] call[name[kwargs].get, parameter[constant[user_id], constant[]]]
variable[glyph] assign[=] call[name[kwargs].get, parameter[constant[glyph], constant[]]]
call[name[logger].info, parameter[call[constant[Infor user recent, username: {user_name}, kind: {kind}, num: {num}].format, parameter[]]]]
variable[all_cats] assign[=] call[call[name[MUsage].query_recent, parameter[name[user_id], name[kind], name[num]]].objects, parameter[]]
variable[kwd] assign[=] dictionary[[<ast.Constant object at 0x7da1b04fa440>, <ast.Constant object at 0x7da1b04f9180>, <ast.Constant object at 0x7da1b04f8f70>], [<ast.Name object at 0x7da1b04fa2c0>, <ast.Subscript object at 0x7da1b04f9db0>, <ast.Name object at 0x7da1b04f9930>]]
return[call[name[self].render_string, parameter[constant[modules/info/list_user_equation.html]]]] | keyword[def] identifier[render_user] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kind] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[args] [ literal[int] ])
identifier[num] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[args] [ literal[int] ] keyword[if] identifier[len] ( identifier[args] )> literal[int] keyword[else] literal[int] )
identifier[with_tag] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] )
identifier[user_id] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] )
identifier[glyph] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] )
identifier[logger] . identifier[info] (
literal[string] . identifier[format] (
identifier[user_name] = identifier[user_id] , identifier[kind] = identifier[kind] , identifier[num] = identifier[num]
)
)
identifier[all_cats] = identifier[MUsage] . identifier[query_recent] ( identifier[user_id] , identifier[kind] , identifier[num] ). identifier[objects] ()
identifier[kwd] ={
literal[string] : identifier[with_tag] ,
literal[string] : identifier[router_post] [ identifier[kind] ],
literal[string] : identifier[glyph]
}
keyword[return] identifier[self] . identifier[render_string] ( literal[string] ,
identifier[recs] = identifier[all_cats] ,
identifier[kwd] = identifier[kwd] ) | def render_user(self, *args, **kwargs):
"""
render, with userinfo
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, user_id = val2)
fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
"""
kind = kwargs.get('kind', args[0])
num = kwargs.get('num', args[1] if len(args) > 1 else 6)
with_tag = kwargs.get('with_tag', False)
user_id = kwargs.get('user_id', '')
glyph = kwargs.get('glyph', '')
logger.info('Infor user recent, username: {user_name}, kind: {kind}, num: {num}'.format(user_name=user_id, kind=kind, num=num))
all_cats = MUsage.query_recent(user_id, kind, num).objects()
kwd = {'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph}
return self.render_string('modules/info/list_user_equation.html', recs=all_cats, kwd=kwd) |
def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name].append(ref.name)
for path in client.workflow_path.glob('*.cwl'):
click.echo(
'{path}: {names}'.format(
path=path.name,
names=', '.join(
click.style(_deref(name), fg='green')
for name in names[path.name]
),
)
) | def function[workflow, parameter[ctx, client]]:
constant[List or manage workflows with subcommands.]
if compare[name[ctx].invoked_subcommand is constant[None]] begin[:]
from relative_module[renku.models.refs] import module[LinkReference]
variable[names] assign[=] call[name[defaultdict], parameter[name[list]]]
for taget[name[ref]] in starred[call[name[LinkReference].iter_items, parameter[name[client]]]] begin[:]
call[call[name[names]][name[ref].reference.name].append, parameter[name[ref].name]]
for taget[name[path]] in starred[call[name[client].workflow_path.glob, parameter[constant[*.cwl]]]] begin[:]
call[name[click].echo, parameter[call[constant[{path}: {names}].format, parameter[]]]] | keyword[def] identifier[workflow] ( identifier[ctx] , identifier[client] ):
literal[string]
keyword[if] identifier[ctx] . identifier[invoked_subcommand] keyword[is] keyword[None] :
keyword[from] identifier[renku] . identifier[models] . identifier[refs] keyword[import] identifier[LinkReference]
identifier[names] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[ref] keyword[in] identifier[LinkReference] . identifier[iter_items] ( identifier[client] , identifier[common_path] = literal[string] ):
identifier[names] [ identifier[ref] . identifier[reference] . identifier[name] ]. identifier[append] ( identifier[ref] . identifier[name] )
keyword[for] identifier[path] keyword[in] identifier[client] . identifier[workflow_path] . identifier[glob] ( literal[string] ):
identifier[click] . identifier[echo] (
literal[string] . identifier[format] (
identifier[path] = identifier[path] . identifier[name] ,
identifier[names] = literal[string] . identifier[join] (
identifier[click] . identifier[style] ( identifier[_deref] ( identifier[name] ), identifier[fg] = literal[string] )
keyword[for] identifier[name] keyword[in] identifier[names] [ identifier[path] . identifier[name] ]
),
)
) | def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name].append(ref.name) # depends on [control=['for'], data=['ref']]
for path in client.workflow_path.glob('*.cwl'):
click.echo('{path}: {names}'.format(path=path.name, names=', '.join((click.style(_deref(name), fg='green') for name in names[path.name])))) # depends on [control=['for'], data=['path']] # depends on [control=['if'], data=[]] |
def import_entries(self, items):
"""
Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content.
"""
self.write_out(self.style.STEP('- Importing entries\n'))
for item_node in items:
title = (item_node.find('title').text or '')[:255]
post_type = item_node.find('{%s}post_type' % WP_NS).text
content = item_node.find(
'{http://purl.org/rss/1.0/modules/content/}encoded').text
if post_type == 'post' and content and title:
self.write_out('> %s... ' % title)
entry, created = self.import_entry(title, content, item_node)
if created:
self.write_out(self.style.ITEM('OK\n'))
image_id = self.find_image_id(
item_node.findall('{%s}postmeta' % WP_NS))
if image_id:
self.import_image(entry, items, image_id)
self.import_comments(entry, item_node.findall(
'{%s}comment' % WP_NS))
else:
self.write_out(self.style.NOTICE(
'SKIPPED (already imported)\n'))
else:
self.write_out('> %s... ' % title, 2)
self.write_out(self.style.NOTICE('SKIPPED (not a post)\n'), 2) | def function[import_entries, parameter[self, items]]:
constant[
Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content.
]
call[name[self].write_out, parameter[call[name[self].style.STEP, parameter[constant[- Importing entries
]]]]]
for taget[name[item_node]] in starred[name[items]] begin[:]
variable[title] assign[=] call[<ast.BoolOp object at 0x7da1b2412140>][<ast.Slice object at 0x7da1b2411e70>]
variable[post_type] assign[=] call[name[item_node].find, parameter[binary_operation[constant[{%s}post_type] <ast.Mod object at 0x7da2590d6920> name[WP_NS]]]].text
variable[content] assign[=] call[name[item_node].find, parameter[constant[{http://purl.org/rss/1.0/modules/content/}encoded]]].text
if <ast.BoolOp object at 0x7da1b2410ac0> begin[:]
call[name[self].write_out, parameter[binary_operation[constant[> %s... ] <ast.Mod object at 0x7da2590d6920> name[title]]]]
<ast.Tuple object at 0x7da1b2410f10> assign[=] call[name[self].import_entry, parameter[name[title], name[content], name[item_node]]]
if name[created] begin[:]
call[name[self].write_out, parameter[call[name[self].style.ITEM, parameter[constant[OK
]]]]]
variable[image_id] assign[=] call[name[self].find_image_id, parameter[call[name[item_node].findall, parameter[binary_operation[constant[{%s}postmeta] <ast.Mod object at 0x7da2590d6920> name[WP_NS]]]]]]
if name[image_id] begin[:]
call[name[self].import_image, parameter[name[entry], name[items], name[image_id]]]
call[name[self].import_comments, parameter[name[entry], call[name[item_node].findall, parameter[binary_operation[constant[{%s}comment] <ast.Mod object at 0x7da2590d6920> name[WP_NS]]]]]] | keyword[def] identifier[import_entries] ( identifier[self] , identifier[items] ):
literal[string]
identifier[self] . identifier[write_out] ( identifier[self] . identifier[style] . identifier[STEP] ( literal[string] ))
keyword[for] identifier[item_node] keyword[in] identifier[items] :
identifier[title] =( identifier[item_node] . identifier[find] ( literal[string] ). identifier[text] keyword[or] literal[string] )[: literal[int] ]
identifier[post_type] = identifier[item_node] . identifier[find] ( literal[string] % identifier[WP_NS] ). identifier[text]
identifier[content] = identifier[item_node] . identifier[find] (
literal[string] ). identifier[text]
keyword[if] identifier[post_type] == literal[string] keyword[and] identifier[content] keyword[and] identifier[title] :
identifier[self] . identifier[write_out] ( literal[string] % identifier[title] )
identifier[entry] , identifier[created] = identifier[self] . identifier[import_entry] ( identifier[title] , identifier[content] , identifier[item_node] )
keyword[if] identifier[created] :
identifier[self] . identifier[write_out] ( identifier[self] . identifier[style] . identifier[ITEM] ( literal[string] ))
identifier[image_id] = identifier[self] . identifier[find_image_id] (
identifier[item_node] . identifier[findall] ( literal[string] % identifier[WP_NS] ))
keyword[if] identifier[image_id] :
identifier[self] . identifier[import_image] ( identifier[entry] , identifier[items] , identifier[image_id] )
identifier[self] . identifier[import_comments] ( identifier[entry] , identifier[item_node] . identifier[findall] (
literal[string] % identifier[WP_NS] ))
keyword[else] :
identifier[self] . identifier[write_out] ( identifier[self] . identifier[style] . identifier[NOTICE] (
literal[string] ))
keyword[else] :
identifier[self] . identifier[write_out] ( literal[string] % identifier[title] , literal[int] )
identifier[self] . identifier[write_out] ( identifier[self] . identifier[style] . identifier[NOTICE] ( literal[string] ), literal[int] ) | def import_entries(self, items):
"""
Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content.
"""
self.write_out(self.style.STEP('- Importing entries\n'))
for item_node in items:
title = (item_node.find('title').text or '')[:255]
post_type = item_node.find('{%s}post_type' % WP_NS).text
content = item_node.find('{http://purl.org/rss/1.0/modules/content/}encoded').text
if post_type == 'post' and content and title:
self.write_out('> %s... ' % title)
(entry, created) = self.import_entry(title, content, item_node)
if created:
self.write_out(self.style.ITEM('OK\n'))
image_id = self.find_image_id(item_node.findall('{%s}postmeta' % WP_NS))
if image_id:
self.import_image(entry, items, image_id) # depends on [control=['if'], data=[]]
self.import_comments(entry, item_node.findall('{%s}comment' % WP_NS)) # depends on [control=['if'], data=[]]
else:
self.write_out(self.style.NOTICE('SKIPPED (already imported)\n')) # depends on [control=['if'], data=[]]
else:
self.write_out('> %s... ' % title, 2)
self.write_out(self.style.NOTICE('SKIPPED (not a post)\n'), 2) # depends on [control=['for'], data=['item_node']] |
def copy_mode(pymux, variables):
"""
Enter copy mode.
"""
go_up = variables['-u'] # Go in copy mode and page-up directly.
# TODO: handle '-u'
pane = pymux.arrangement.get_active_pane()
pane.enter_copy_mode() | def function[copy_mode, parameter[pymux, variables]]:
constant[
Enter copy mode.
]
variable[go_up] assign[=] call[name[variables]][constant[-u]]
variable[pane] assign[=] call[name[pymux].arrangement.get_active_pane, parameter[]]
call[name[pane].enter_copy_mode, parameter[]] | keyword[def] identifier[copy_mode] ( identifier[pymux] , identifier[variables] ):
literal[string]
identifier[go_up] = identifier[variables] [ literal[string] ]
identifier[pane] = identifier[pymux] . identifier[arrangement] . identifier[get_active_pane] ()
identifier[pane] . identifier[enter_copy_mode] () | def copy_mode(pymux, variables):
"""
Enter copy mode.
"""
go_up = variables['-u'] # Go in copy mode and page-up directly.
# TODO: handle '-u'
pane = pymux.arrangement.get_active_pane()
pane.enter_copy_mode() |
def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
candidate = self._next_of_kin(pos)
return candidate | def function[next_position, parameter[self, pos]]:
constant[returns the next position in depth-first order]
variable[candidate] assign[=] constant[None]
if compare[name[pos] is_not constant[None]] begin[:]
variable[candidate] assign[=] call[name[self].first_child_position, parameter[name[pos]]]
if compare[name[candidate] is constant[None]] begin[:]
variable[candidate] assign[=] call[name[self].next_sibling_position, parameter[name[pos]]]
if compare[name[candidate] is constant[None]] begin[:]
variable[candidate] assign[=] call[name[self]._next_of_kin, parameter[name[pos]]]
return[name[candidate]] | keyword[def] identifier[next_position] ( identifier[self] , identifier[pos] ):
literal[string]
identifier[candidate] = keyword[None]
keyword[if] identifier[pos] keyword[is] keyword[not] keyword[None] :
identifier[candidate] = identifier[self] . identifier[first_child_position] ( identifier[pos] )
keyword[if] identifier[candidate] keyword[is] keyword[None] :
identifier[candidate] = identifier[self] . identifier[next_sibling_position] ( identifier[pos] )
keyword[if] identifier[candidate] keyword[is] keyword[None] :
identifier[candidate] = identifier[self] . identifier[_next_of_kin] ( identifier[pos] )
keyword[return] identifier[candidate] | def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
candidate = self._next_of_kin(pos) # depends on [control=['if'], data=['candidate']] # depends on [control=['if'], data=['candidate']] # depends on [control=['if'], data=['pos']]
return candidate |
def intercept_callback_query_origin(fn=pair, origins='all'):
"""
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled for specified origin types.
"""
origin_map = helper.SafeDict()
# For key functions that returns a tuple as key (e.g. per_callback_query_origin()),
# wrap the key in another tuple to prevent router from mistaking it as
# a key followed by some arguments.
def tuplize(fn):
def tp(msg):
return (fn(msg),)
return tp
router = helper.Router(tuplize(per_callback_query_origin(origins=origins)),
origin_map)
def modify_origin_map(origin, dest, set):
if set:
origin_map[origin] = dest
else:
try:
del origin_map[origin]
except KeyError:
pass
if origins == 'all':
intercept = modify_origin_map
else:
intercept = (modify_origin_map if 'chat' in origins else False,
modify_origin_map if 'inline' in origins else False)
@_ensure_seeders_list
def p(seeders, delegator_factory, *args, **kwargs):
return fn(seeders + [_wrap_none(router.map)],
delegator_factory, *args, intercept_callback_query=intercept, **kwargs)
return p | def function[intercept_callback_query_origin, parameter[fn, origins]]:
constant[
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled for specified origin types.
]
variable[origin_map] assign[=] call[name[helper].SafeDict, parameter[]]
def function[tuplize, parameter[fn]]:
def function[tp, parameter[msg]]:
return[tuple[[<ast.Call object at 0x7da1b1b0c0d0>]]]
return[name[tp]]
variable[router] assign[=] call[name[helper].Router, parameter[call[name[tuplize], parameter[call[name[per_callback_query_origin], parameter[]]]], name[origin_map]]]
def function[modify_origin_map, parameter[origin, dest, set]]:
if name[set] begin[:]
call[name[origin_map]][name[origin]] assign[=] name[dest]
if compare[name[origins] equal[==] constant[all]] begin[:]
variable[intercept] assign[=] name[modify_origin_map]
def function[p, parameter[seeders, delegator_factory]]:
return[call[name[fn], parameter[binary_operation[name[seeders] + list[[<ast.Call object at 0x7da1b1c7ece0>]]], name[delegator_factory], <ast.Starred object at 0x7da1b1bac610>]]]
return[name[p]] | keyword[def] identifier[intercept_callback_query_origin] ( identifier[fn] = identifier[pair] , identifier[origins] = literal[string] ):
literal[string]
identifier[origin_map] = identifier[helper] . identifier[SafeDict] ()
keyword[def] identifier[tuplize] ( identifier[fn] ):
keyword[def] identifier[tp] ( identifier[msg] ):
keyword[return] ( identifier[fn] ( identifier[msg] ),)
keyword[return] identifier[tp]
identifier[router] = identifier[helper] . identifier[Router] ( identifier[tuplize] ( identifier[per_callback_query_origin] ( identifier[origins] = identifier[origins] )),
identifier[origin_map] )
keyword[def] identifier[modify_origin_map] ( identifier[origin] , identifier[dest] , identifier[set] ):
keyword[if] identifier[set] :
identifier[origin_map] [ identifier[origin] ]= identifier[dest]
keyword[else] :
keyword[try] :
keyword[del] identifier[origin_map] [ identifier[origin] ]
keyword[except] identifier[KeyError] :
keyword[pass]
keyword[if] identifier[origins] == literal[string] :
identifier[intercept] = identifier[modify_origin_map]
keyword[else] :
identifier[intercept] =( identifier[modify_origin_map] keyword[if] literal[string] keyword[in] identifier[origins] keyword[else] keyword[False] ,
identifier[modify_origin_map] keyword[if] literal[string] keyword[in] identifier[origins] keyword[else] keyword[False] )
@ identifier[_ensure_seeders_list]
keyword[def] identifier[p] ( identifier[seeders] , identifier[delegator_factory] ,* identifier[args] ,** identifier[kwargs] ):
keyword[return] identifier[fn] ( identifier[seeders] +[ identifier[_wrap_none] ( identifier[router] . identifier[map] )],
identifier[delegator_factory] ,* identifier[args] , identifier[intercept_callback_query] = identifier[intercept] ,** identifier[kwargs] )
keyword[return] identifier[p] | def intercept_callback_query_origin(fn=pair, origins='all'):
"""
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled for specified origin types.
"""
origin_map = helper.SafeDict()
# For key functions that returns a tuple as key (e.g. per_callback_query_origin()),
# wrap the key in another tuple to prevent router from mistaking it as
# a key followed by some arguments.
def tuplize(fn):
def tp(msg):
return (fn(msg),)
return tp
router = helper.Router(tuplize(per_callback_query_origin(origins=origins)), origin_map)
def modify_origin_map(origin, dest, set):
if set:
origin_map[origin] = dest # depends on [control=['if'], data=[]]
else:
try:
del origin_map[origin] # depends on [control=['try'], data=[]]
except KeyError:
pass # depends on [control=['except'], data=[]]
if origins == 'all':
intercept = modify_origin_map # depends on [control=['if'], data=[]]
else:
intercept = (modify_origin_map if 'chat' in origins else False, modify_origin_map if 'inline' in origins else False)
@_ensure_seeders_list
def p(seeders, delegator_factory, *args, **kwargs):
return fn(seeders + [_wrap_none(router.map)], delegator_factory, *args, intercept_callback_query=intercept, **kwargs)
return p |
def mute(returns_output=False):
"""
`returns_output` - Returns all print output in a list.
Capture or ignore all print output generated by a function.
Usage:
output = mute(returns_output=True)(module.my_func)(args)
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
saved_stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
out = func(*args, **kwargs)
if returns_output:
out = sys.stdout.getvalue().strip().split()
finally:
sys.stdout = saved_stdout
return out
return wrapper
return decorator | def function[mute, parameter[returns_output]]:
constant[
`returns_output` - Returns all print output in a list.
Capture or ignore all print output generated by a function.
Usage:
output = mute(returns_output=True)(module.my_func)(args)
]
def function[decorator, parameter[func]]:
def function[wrapper, parameter[]]:
variable[saved_stdout] assign[=] name[sys].stdout
name[sys].stdout assign[=] call[name[cStringIO].StringIO, parameter[]]
<ast.Try object at 0x7da207f983a0>
return[name[out]]
return[name[wrapper]]
return[name[decorator]] | keyword[def] identifier[mute] ( identifier[returns_output] = keyword[False] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[saved_stdout] = identifier[sys] . identifier[stdout]
identifier[sys] . identifier[stdout] = identifier[cStringIO] . identifier[StringIO] ()
keyword[try] :
identifier[out] = identifier[func] (* identifier[args] ,** identifier[kwargs] )
keyword[if] identifier[returns_output] :
identifier[out] = identifier[sys] . identifier[stdout] . identifier[getvalue] (). identifier[strip] (). identifier[split] ()
keyword[finally] :
identifier[sys] . identifier[stdout] = identifier[saved_stdout]
keyword[return] identifier[out]
keyword[return] identifier[wrapper]
keyword[return] identifier[decorator] | def mute(returns_output=False):
"""
`returns_output` - Returns all print output in a list.
Capture or ignore all print output generated by a function.
Usage:
output = mute(returns_output=True)(module.my_func)(args)
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
saved_stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
out = func(*args, **kwargs)
if returns_output:
out = sys.stdout.getvalue().strip().split() # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
finally:
sys.stdout = saved_stdout
return out
return wrapper
return decorator |
def from_config(cls, config, name, section_key="scoring_contexts"):
"""
Expects:
scoring_contexts:
enwiki:
scorer_models:
damaging: enwiki_damaging_2014
good-faith: enwiki_good-faith_2014
extractor: enwiki
ptwiki:
scorer_models:
damaging: ptwiki_damaging_2014
good-faith: ptwiki_good-faith_2014
extractor: ptwiki
extractors:
enwiki_api: ...
ptwiki_api: ...
scorer_models:
enwiki_damaging_2014: ...
enwiki_good-faith_2014: ...
"""
logger.info("Loading {0} '{1}' from config.".format(cls.__name__, name))
section = config[section_key][name]
model_map = {}
for model_name, key in section['scorer_models'].items():
scorer_model = Model.from_config(config, key)
model_map[model_name] = scorer_model
extractor = Extractor.from_config(config, section['extractor'])
return cls(name, model_map=model_map, extractor=extractor) | def function[from_config, parameter[cls, config, name, section_key]]:
constant[
Expects:
scoring_contexts:
enwiki:
scorer_models:
damaging: enwiki_damaging_2014
good-faith: enwiki_good-faith_2014
extractor: enwiki
ptwiki:
scorer_models:
damaging: ptwiki_damaging_2014
good-faith: ptwiki_good-faith_2014
extractor: ptwiki
extractors:
enwiki_api: ...
ptwiki_api: ...
scorer_models:
enwiki_damaging_2014: ...
enwiki_good-faith_2014: ...
]
call[name[logger].info, parameter[call[constant[Loading {0} '{1}' from config.].format, parameter[name[cls].__name__, name[name]]]]]
variable[section] assign[=] call[call[name[config]][name[section_key]]][name[name]]
variable[model_map] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da20c6ab820>, <ast.Name object at 0x7da20c6a9c60>]]] in starred[call[call[name[section]][constant[scorer_models]].items, parameter[]]] begin[:]
variable[scorer_model] assign[=] call[name[Model].from_config, parameter[name[config], name[key]]]
call[name[model_map]][name[model_name]] assign[=] name[scorer_model]
variable[extractor] assign[=] call[name[Extractor].from_config, parameter[name[config], call[name[section]][constant[extractor]]]]
return[call[name[cls], parameter[name[name]]]] | keyword[def] identifier[from_config] ( identifier[cls] , identifier[config] , identifier[name] , identifier[section_key] = literal[string] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[cls] . identifier[__name__] , identifier[name] ))
identifier[section] = identifier[config] [ identifier[section_key] ][ identifier[name] ]
identifier[model_map] ={}
keyword[for] identifier[model_name] , identifier[key] keyword[in] identifier[section] [ literal[string] ]. identifier[items] ():
identifier[scorer_model] = identifier[Model] . identifier[from_config] ( identifier[config] , identifier[key] )
identifier[model_map] [ identifier[model_name] ]= identifier[scorer_model]
identifier[extractor] = identifier[Extractor] . identifier[from_config] ( identifier[config] , identifier[section] [ literal[string] ])
keyword[return] identifier[cls] ( identifier[name] , identifier[model_map] = identifier[model_map] , identifier[extractor] = identifier[extractor] ) | def from_config(cls, config, name, section_key='scoring_contexts'):
"""
Expects:
scoring_contexts:
enwiki:
scorer_models:
damaging: enwiki_damaging_2014
good-faith: enwiki_good-faith_2014
extractor: enwiki
ptwiki:
scorer_models:
damaging: ptwiki_damaging_2014
good-faith: ptwiki_good-faith_2014
extractor: ptwiki
extractors:
enwiki_api: ...
ptwiki_api: ...
scorer_models:
enwiki_damaging_2014: ...
enwiki_good-faith_2014: ...
"""
logger.info("Loading {0} '{1}' from config.".format(cls.__name__, name))
section = config[section_key][name]
model_map = {}
for (model_name, key) in section['scorer_models'].items():
scorer_model = Model.from_config(config, key)
model_map[model_name] = scorer_model # depends on [control=['for'], data=[]]
extractor = Extractor.from_config(config, section['extractor'])
return cls(name, model_map=model_map, extractor=extractor) |
def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index(['a', 'b', 'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}
"""
categories = self.categories
r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),
categories.size)
counts = counts.cumsum()
result = (r[start:end] for start, end in zip(counts, counts[1:]))
result = dict(zip(categories, result))
return result | def function[_reverse_indexer, parameter[self]]:
constant[
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index(['a', 'b', 'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}
]
variable[categories] assign[=] name[self].categories
<ast.Tuple object at 0x7da20c6e4250> assign[=] call[name[libalgos].groupsort_indexer, parameter[call[name[self].codes.astype, parameter[constant[int64]]], name[categories].size]]
variable[counts] assign[=] call[name[counts].cumsum, parameter[]]
variable[result] assign[=] <ast.GeneratorExp object at 0x7da20c6e5ae0>
variable[result] assign[=] call[name[dict], parameter[call[name[zip], parameter[name[categories], name[result]]]]]
return[name[result]] | keyword[def] identifier[_reverse_indexer] ( identifier[self] ):
literal[string]
identifier[categories] = identifier[self] . identifier[categories]
identifier[r] , identifier[counts] = identifier[libalgos] . identifier[groupsort_indexer] ( identifier[self] . identifier[codes] . identifier[astype] ( literal[string] ),
identifier[categories] . identifier[size] )
identifier[counts] = identifier[counts] . identifier[cumsum] ()
identifier[result] =( identifier[r] [ identifier[start] : identifier[end] ] keyword[for] identifier[start] , identifier[end] keyword[in] identifier[zip] ( identifier[counts] , identifier[counts] [ literal[int] :]))
identifier[result] = identifier[dict] ( identifier[zip] ( identifier[categories] , identifier[result] ))
keyword[return] identifier[result] | def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index(['a', 'b', 'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}
"""
categories = self.categories
(r, counts) = libalgos.groupsort_indexer(self.codes.astype('int64'), categories.size)
counts = counts.cumsum()
result = (r[start:end] for (start, end) in zip(counts, counts[1:]))
result = dict(zip(categories, result))
return result |
def ice_days(tasmax, freq='YS'):
r"""Number of ice/freezing days
Number of days where daily maximum temperatures are below 0℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Number of ice/freezing days.
Notes
-----
Let :math:`TX_{ij}` be the daily maximum temperature at day :math:`i` of period :math:`j`. Then
counted is the number of days where:
.. math::
TX_{ij} < 0℃
"""
tu = units.parse_units(tasmax.attrs['units'].replace('-', '**-'))
fu = 'degC'
frz = 0
if fu != tu:
frz = units.convert(frz, fu, tu)
f = (tasmax < frz) * 1
return f.resample(time=freq).sum(dim='time') | def function[ice_days, parameter[tasmax, freq]]:
constant[Number of ice/freezing days
Number of days where daily maximum temperatures are below 0℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Number of ice/freezing days.
Notes
-----
Let :math:`TX_{ij}` be the daily maximum temperature at day :math:`i` of period :math:`j`. Then
counted is the number of days where:
.. math::
TX_{ij} < 0℃
]
variable[tu] assign[=] call[name[units].parse_units, parameter[call[call[name[tasmax].attrs][constant[units]].replace, parameter[constant[-], constant[**-]]]]]
variable[fu] assign[=] constant[degC]
variable[frz] assign[=] constant[0]
if compare[name[fu] not_equal[!=] name[tu]] begin[:]
variable[frz] assign[=] call[name[units].convert, parameter[name[frz], name[fu], name[tu]]]
variable[f] assign[=] binary_operation[compare[name[tasmax] less[<] name[frz]] * constant[1]]
return[call[call[name[f].resample, parameter[]].sum, parameter[]]] | keyword[def] identifier[ice_days] ( identifier[tasmax] , identifier[freq] = literal[string] ):
literal[string]
identifier[tu] = identifier[units] . identifier[parse_units] ( identifier[tasmax] . identifier[attrs] [ literal[string] ]. identifier[replace] ( literal[string] , literal[string] ))
identifier[fu] = literal[string]
identifier[frz] = literal[int]
keyword[if] identifier[fu] != identifier[tu] :
identifier[frz] = identifier[units] . identifier[convert] ( identifier[frz] , identifier[fu] , identifier[tu] )
identifier[f] =( identifier[tasmax] < identifier[frz] )* literal[int]
keyword[return] identifier[f] . identifier[resample] ( identifier[time] = identifier[freq] ). identifier[sum] ( identifier[dim] = literal[string] ) | def ice_days(tasmax, freq='YS'):
"""Number of ice/freezing days
Number of days where daily maximum temperatures are below 0℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
xarray.DataArray
Number of ice/freezing days.
Notes
-----
Let :math:`TX_{ij}` be the daily maximum temperature at day :math:`i` of period :math:`j`. Then
counted is the number of days where:
.. math::
TX_{ij} < 0℃
"""
tu = units.parse_units(tasmax.attrs['units'].replace('-', '**-'))
fu = 'degC'
frz = 0
if fu != tu:
frz = units.convert(frz, fu, tu) # depends on [control=['if'], data=['fu', 'tu']]
f = (tasmax < frz) * 1
return f.resample(time=freq).sum(dim='time') |
def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary,
oneblock):
'''
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var : int
The variable number
dataType : int
The CDF data type of this variable
numElems : str
The number of elements in each record
recVary : bool
True if the value varies across records
oneblock: list
A list of data in the form [startrec, endrec, [data]]
Returns:
recend : int
Just the "endrec" value input by the user in "oneblock"
'''
rec_start = oneblock[0]
rec_end = oneblock[1]
indata = oneblock[2]
numValues = self._num_values(zVar, var)
# Convert oneblock[2] into a byte stream
_, data = self._convert_data(dataType, numElems, numValues, indata)
# Gather dimension information
if zVar:
vdr_offset = self.zvarsinfo[var][1]
else:
vdr_offset = self.rvarsinfo[var][1]
# Write one VVR
offset = self._write_vvr(f, data)
f.seek(vdr_offset+28, 0)
# Get first VXR
vxrOne = int.from_bytes(f.read(8), 'big', signed=True)
foundSpot = 0
usedEntries = 0
currentVXR = 0
# Search through VXRs to find an open one
while foundSpot == 0 and vxrOne > 0:
# have a VXR
f.seek(vxrOne, 0)
currentVXR = f.tell()
f.seek(vxrOne+12, 0)
vxrNext = int.from_bytes(f.read(8), 'big', signed=True)
nEntries = int.from_bytes(f.read(4), 'big', signed=True)
usedEntries = int.from_bytes(f.read(4), 'big', signed=True)
if (usedEntries == nEntries):
# all entries are used -- check the next vxr in link
vxrOne = vxrNext
else:
# found a vxr with an vailable entry spot
foundSpot = 1
# vxrOne == 0 from vdr's vxrhead vxrOne == -1 from a vxr's vxrnext
if (vxrOne == 0 or vxrOne == -1):
# no available vxr... create a new one
currentVXR = self._create_vxr(f, rec_start, rec_end, vdr_offset,
currentVXR, offset)
else:
self._use_vxrentry(f, currentVXR, rec_start, rec_end, offset)
# Modify the VDR's MaxRec if needed
f.seek(vdr_offset+24, 0)
recNumc = int.from_bytes(f.read(4), 'big', signed=True)
if (rec_end > recNumc):
self._update_offset_value(f, vdr_offset+24, 4, rec_end)
return rec_end | def function[_write_var_data_sparse, parameter[self, f, zVar, var, dataType, numElems, recVary, oneblock]]:
constant[
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var : int
The variable number
dataType : int
The CDF data type of this variable
numElems : str
The number of elements in each record
recVary : bool
True if the value varies across records
oneblock: list
A list of data in the form [startrec, endrec, [data]]
Returns:
recend : int
Just the "endrec" value input by the user in "oneblock"
]
variable[rec_start] assign[=] call[name[oneblock]][constant[0]]
variable[rec_end] assign[=] call[name[oneblock]][constant[1]]
variable[indata] assign[=] call[name[oneblock]][constant[2]]
variable[numValues] assign[=] call[name[self]._num_values, parameter[name[zVar], name[var]]]
<ast.Tuple object at 0x7da1b06e38e0> assign[=] call[name[self]._convert_data, parameter[name[dataType], name[numElems], name[numValues], name[indata]]]
if name[zVar] begin[:]
variable[vdr_offset] assign[=] call[call[name[self].zvarsinfo][name[var]]][constant[1]]
variable[offset] assign[=] call[name[self]._write_vvr, parameter[name[f], name[data]]]
call[name[f].seek, parameter[binary_operation[name[vdr_offset] + constant[28]], constant[0]]]
variable[vxrOne] assign[=] call[name[int].from_bytes, parameter[call[name[f].read, parameter[constant[8]]], constant[big]]]
variable[foundSpot] assign[=] constant[0]
variable[usedEntries] assign[=] constant[0]
variable[currentVXR] assign[=] constant[0]
while <ast.BoolOp object at 0x7da1b06e28c0> begin[:]
call[name[f].seek, parameter[name[vxrOne], constant[0]]]
variable[currentVXR] assign[=] call[name[f].tell, parameter[]]
call[name[f].seek, parameter[binary_operation[name[vxrOne] + constant[12]], constant[0]]]
variable[vxrNext] assign[=] call[name[int].from_bytes, parameter[call[name[f].read, parameter[constant[8]]], constant[big]]]
variable[nEntries] assign[=] call[name[int].from_bytes, parameter[call[name[f].read, parameter[constant[4]]], constant[big]]]
variable[usedEntries] assign[=] call[name[int].from_bytes, parameter[call[name[f].read, parameter[constant[4]]], constant[big]]]
if compare[name[usedEntries] equal[==] name[nEntries]] begin[:]
variable[vxrOne] assign[=] name[vxrNext]
if <ast.BoolOp object at 0x7da1b06e2ef0> begin[:]
variable[currentVXR] assign[=] call[name[self]._create_vxr, parameter[name[f], name[rec_start], name[rec_end], name[vdr_offset], name[currentVXR], name[offset]]]
call[name[f].seek, parameter[binary_operation[name[vdr_offset] + constant[24]], constant[0]]]
variable[recNumc] assign[=] call[name[int].from_bytes, parameter[call[name[f].read, parameter[constant[4]]], constant[big]]]
if compare[name[rec_end] greater[>] name[recNumc]] begin[:]
call[name[self]._update_offset_value, parameter[name[f], binary_operation[name[vdr_offset] + constant[24]], constant[4], name[rec_end]]]
return[name[rec_end]] | keyword[def] identifier[_write_var_data_sparse] ( identifier[self] , identifier[f] , identifier[zVar] , identifier[var] , identifier[dataType] , identifier[numElems] , identifier[recVary] ,
identifier[oneblock] ):
literal[string]
identifier[rec_start] = identifier[oneblock] [ literal[int] ]
identifier[rec_end] = identifier[oneblock] [ literal[int] ]
identifier[indata] = identifier[oneblock] [ literal[int] ]
identifier[numValues] = identifier[self] . identifier[_num_values] ( identifier[zVar] , identifier[var] )
identifier[_] , identifier[data] = identifier[self] . identifier[_convert_data] ( identifier[dataType] , identifier[numElems] , identifier[numValues] , identifier[indata] )
keyword[if] identifier[zVar] :
identifier[vdr_offset] = identifier[self] . identifier[zvarsinfo] [ identifier[var] ][ literal[int] ]
keyword[else] :
identifier[vdr_offset] = identifier[self] . identifier[rvarsinfo] [ identifier[var] ][ literal[int] ]
identifier[offset] = identifier[self] . identifier[_write_vvr] ( identifier[f] , identifier[data] )
identifier[f] . identifier[seek] ( identifier[vdr_offset] + literal[int] , literal[int] )
identifier[vxrOne] = identifier[int] . identifier[from_bytes] ( identifier[f] . identifier[read] ( literal[int] ), literal[string] , identifier[signed] = keyword[True] )
identifier[foundSpot] = literal[int]
identifier[usedEntries] = literal[int]
identifier[currentVXR] = literal[int]
keyword[while] identifier[foundSpot] == literal[int] keyword[and] identifier[vxrOne] > literal[int] :
identifier[f] . identifier[seek] ( identifier[vxrOne] , literal[int] )
identifier[currentVXR] = identifier[f] . identifier[tell] ()
identifier[f] . identifier[seek] ( identifier[vxrOne] + literal[int] , literal[int] )
identifier[vxrNext] = identifier[int] . identifier[from_bytes] ( identifier[f] . identifier[read] ( literal[int] ), literal[string] , identifier[signed] = keyword[True] )
identifier[nEntries] = identifier[int] . identifier[from_bytes] ( identifier[f] . identifier[read] ( literal[int] ), literal[string] , identifier[signed] = keyword[True] )
identifier[usedEntries] = identifier[int] . identifier[from_bytes] ( identifier[f] . identifier[read] ( literal[int] ), literal[string] , identifier[signed] = keyword[True] )
keyword[if] ( identifier[usedEntries] == identifier[nEntries] ):
identifier[vxrOne] = identifier[vxrNext]
keyword[else] :
identifier[foundSpot] = literal[int]
keyword[if] ( identifier[vxrOne] == literal[int] keyword[or] identifier[vxrOne] ==- literal[int] ):
identifier[currentVXR] = identifier[self] . identifier[_create_vxr] ( identifier[f] , identifier[rec_start] , identifier[rec_end] , identifier[vdr_offset] ,
identifier[currentVXR] , identifier[offset] )
keyword[else] :
identifier[self] . identifier[_use_vxrentry] ( identifier[f] , identifier[currentVXR] , identifier[rec_start] , identifier[rec_end] , identifier[offset] )
identifier[f] . identifier[seek] ( identifier[vdr_offset] + literal[int] , literal[int] )
identifier[recNumc] = identifier[int] . identifier[from_bytes] ( identifier[f] . identifier[read] ( literal[int] ), literal[string] , identifier[signed] = keyword[True] )
keyword[if] ( identifier[rec_end] > identifier[recNumc] ):
identifier[self] . identifier[_update_offset_value] ( identifier[f] , identifier[vdr_offset] + literal[int] , literal[int] , identifier[rec_end] )
keyword[return] identifier[rec_end] | def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary, oneblock):
"""
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var : int
The variable number
dataType : int
The CDF data type of this variable
numElems : str
The number of elements in each record
recVary : bool
True if the value varies across records
oneblock: list
A list of data in the form [startrec, endrec, [data]]
Returns:
recend : int
Just the "endrec" value input by the user in "oneblock"
"""
rec_start = oneblock[0]
rec_end = oneblock[1]
indata = oneblock[2]
numValues = self._num_values(zVar, var)
# Convert oneblock[2] into a byte stream
(_, data) = self._convert_data(dataType, numElems, numValues, indata)
# Gather dimension information
if zVar:
vdr_offset = self.zvarsinfo[var][1] # depends on [control=['if'], data=[]]
else:
vdr_offset = self.rvarsinfo[var][1]
# Write one VVR
offset = self._write_vvr(f, data)
f.seek(vdr_offset + 28, 0)
# Get first VXR
vxrOne = int.from_bytes(f.read(8), 'big', signed=True)
foundSpot = 0
usedEntries = 0
currentVXR = 0
# Search through VXRs to find an open one
while foundSpot == 0 and vxrOne > 0:
# have a VXR
f.seek(vxrOne, 0)
currentVXR = f.tell()
f.seek(vxrOne + 12, 0)
vxrNext = int.from_bytes(f.read(8), 'big', signed=True)
nEntries = int.from_bytes(f.read(4), 'big', signed=True)
usedEntries = int.from_bytes(f.read(4), 'big', signed=True)
if usedEntries == nEntries:
# all entries are used -- check the next vxr in link
vxrOne = vxrNext # depends on [control=['if'], data=[]]
else:
# found a vxr with an vailable entry spot
foundSpot = 1 # depends on [control=['while'], data=[]]
# vxrOne == 0 from vdr's vxrhead vxrOne == -1 from a vxr's vxrnext
if vxrOne == 0 or vxrOne == -1:
# no available vxr... create a new one
currentVXR = self._create_vxr(f, rec_start, rec_end, vdr_offset, currentVXR, offset) # depends on [control=['if'], data=[]]
else:
self._use_vxrentry(f, currentVXR, rec_start, rec_end, offset)
# Modify the VDR's MaxRec if needed
f.seek(vdr_offset + 24, 0)
recNumc = int.from_bytes(f.read(4), 'big', signed=True)
if rec_end > recNumc:
self._update_offset_value(f, vdr_offset + 24, 4, rec_end) # depends on [control=['if'], data=['rec_end']]
return rec_end |
def signout(request, next_page=userena_settings.USERENA_REDIRECT_ON_SIGNOUT,
template_name='userena/signout.html', *args, **kwargs):
"""
Signs out the user and adds a success message ``You have been signed
out.`` If next_page is defined you will be redirected to the URI. If
not the template in template_name is used.
:param next_page:
A string which specifies the URI to redirect to.
:param template_name:
String defining the name of the template to use. Defaults to
``userena/signout.html``.
"""
if request.user.is_authenticated() and userena_settings.USERENA_USE_MESSAGES: # pragma: no cover
messages.success(request, _('You have been signed out.'), fail_silently=True)
userena_signals.account_signout.send(sender=None, user=request.user)
return Signout(request, next_page, template_name, *args, **kwargs) | def function[signout, parameter[request, next_page, template_name]]:
constant[
Signs out the user and adds a success message ``You have been signed
out.`` If next_page is defined you will be redirected to the URI. If
not the template in template_name is used.
:param next_page:
A string which specifies the URI to redirect to.
:param template_name:
String defining the name of the template to use. Defaults to
``userena/signout.html``.
]
if <ast.BoolOp object at 0x7da18fe93a30> begin[:]
call[name[messages].success, parameter[name[request], call[name[_], parameter[constant[You have been signed out.]]]]]
call[name[userena_signals].account_signout.send, parameter[]]
return[call[name[Signout], parameter[name[request], name[next_page], name[template_name], <ast.Starred object at 0x7da18dc07850>]]] | keyword[def] identifier[signout] ( identifier[request] , identifier[next_page] = identifier[userena_settings] . identifier[USERENA_REDIRECT_ON_SIGNOUT] ,
identifier[template_name] = literal[string] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[request] . identifier[user] . identifier[is_authenticated] () keyword[and] identifier[userena_settings] . identifier[USERENA_USE_MESSAGES] :
identifier[messages] . identifier[success] ( identifier[request] , identifier[_] ( literal[string] ), identifier[fail_silently] = keyword[True] )
identifier[userena_signals] . identifier[account_signout] . identifier[send] ( identifier[sender] = keyword[None] , identifier[user] = identifier[request] . identifier[user] )
keyword[return] identifier[Signout] ( identifier[request] , identifier[next_page] , identifier[template_name] ,* identifier[args] ,** identifier[kwargs] ) | def signout(request, next_page=userena_settings.USERENA_REDIRECT_ON_SIGNOUT, template_name='userena/signout.html', *args, **kwargs):
"""
Signs out the user and adds a success message ``You have been signed
out.`` If next_page is defined you will be redirected to the URI. If
not the template in template_name is used.
:param next_page:
A string which specifies the URI to redirect to.
:param template_name:
String defining the name of the template to use. Defaults to
``userena/signout.html``.
"""
if request.user.is_authenticated() and userena_settings.USERENA_USE_MESSAGES: # pragma: no cover
messages.success(request, _('You have been signed out.'), fail_silently=True) # depends on [control=['if'], data=[]]
userena_signals.account_signout.send(sender=None, user=request.user)
return Signout(request, next_page, template_name, *args, **kwargs) |
def BitmathType(bmstring):
"""An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argument and returns the converted value
I.e., ``type`` can be a function (such as this function) or a class
which implements the ``__call__`` method.
Example usage of the bitmath.BitmathType argparser type:
>>> import bitmath
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--file-size", type=bitmath.BitmathType)
>>> parser.parse_args("--file-size 1337MiB".split())
Namespace(file_size=MiB(1337.0))
Invalid usage includes any input that the bitmath.parse_string
function already rejects. Additionally, **UNQUOTED** arguments with
spaces in them are rejected (shlex.split used in the following
examples to conserve single quotes in the parse_args call):
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--file-size", type=bitmath.BitmathType)
>>> import shlex
>>> # The following is ACCEPTABLE USAGE:
...
>>> parser.parse_args(shlex.split("--file-size '1337 MiB'"))
Namespace(file_size=MiB(1337.0))
>>> # The following is INCORRECT USAGE because the string "1337 MiB" is not quoted!
...
>>> parser.parse_args(shlex.split("--file-size 1337 MiB"))
error: argument --file-size: 1337 can not be parsed into a valid bitmath object
"""
try:
argvalue = bitmath.parse_string(bmstring)
except ValueError:
raise argparse.ArgumentTypeError("'%s' can not be parsed into a valid bitmath object" %
bmstring)
else:
return argvalue | def function[BitmathType, parameter[bmstring]]:
constant[An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argument and returns the converted value
I.e., ``type`` can be a function (such as this function) or a class
which implements the ``__call__`` method.
Example usage of the bitmath.BitmathType argparser type:
>>> import bitmath
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--file-size", type=bitmath.BitmathType)
>>> parser.parse_args("--file-size 1337MiB".split())
Namespace(file_size=MiB(1337.0))
Invalid usage includes any input that the bitmath.parse_string
function already rejects. Additionally, **UNQUOTED** arguments with
spaces in them are rejected (shlex.split used in the following
examples to conserve single quotes in the parse_args call):
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--file-size", type=bitmath.BitmathType)
>>> import shlex
>>> # The following is ACCEPTABLE USAGE:
...
>>> parser.parse_args(shlex.split("--file-size '1337 MiB'"))
Namespace(file_size=MiB(1337.0))
>>> # The following is INCORRECT USAGE because the string "1337 MiB" is not quoted!
...
>>> parser.parse_args(shlex.split("--file-size 1337 MiB"))
error: argument --file-size: 1337 can not be parsed into a valid bitmath object
]
<ast.Try object at 0x7da207f02620> | keyword[def] identifier[BitmathType] ( identifier[bmstring] ):
literal[string]
keyword[try] :
identifier[argvalue] = identifier[bitmath] . identifier[parse_string] ( identifier[bmstring] )
keyword[except] identifier[ValueError] :
keyword[raise] identifier[argparse] . identifier[ArgumentTypeError] ( literal[string] %
identifier[bmstring] )
keyword[else] :
keyword[return] identifier[argvalue] | def BitmathType(bmstring):
"""An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argument and returns the converted value
I.e., ``type`` can be a function (such as this function) or a class
which implements the ``__call__`` method.
Example usage of the bitmath.BitmathType argparser type:
>>> import bitmath
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--file-size", type=bitmath.BitmathType)
>>> parser.parse_args("--file-size 1337MiB".split())
Namespace(file_size=MiB(1337.0))
Invalid usage includes any input that the bitmath.parse_string
function already rejects. Additionally, **UNQUOTED** arguments with
spaces in them are rejected (shlex.split used in the following
examples to conserve single quotes in the parse_args call):
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--file-size", type=bitmath.BitmathType)
>>> import shlex
>>> # The following is ACCEPTABLE USAGE:
...
>>> parser.parse_args(shlex.split("--file-size '1337 MiB'"))
Namespace(file_size=MiB(1337.0))
>>> # The following is INCORRECT USAGE because the string "1337 MiB" is not quoted!
...
>>> parser.parse_args(shlex.split("--file-size 1337 MiB"))
error: argument --file-size: 1337 can not be parsed into a valid bitmath object
"""
try:
argvalue = bitmath.parse_string(bmstring) # depends on [control=['try'], data=[]]
except ValueError:
raise argparse.ArgumentTypeError("'%s' can not be parsed into a valid bitmath object" % bmstring) # depends on [control=['except'], data=[]]
else:
return argvalue |
def context_list_users(zap_helper, context_name):
"""List the users available for a given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for the context {0}: {1}'.format(context_name, user_list))
else:
console.info('No users configured for the context {}'.format(context_name)) | def function[context_list_users, parameter[zap_helper, context_name]]:
constant[List the users available for a given context.]
with call[name[zap_error_handler], parameter[]] begin[:]
variable[info] assign[=] call[name[zap_helper].get_context_info, parameter[name[context_name]]]
variable[users] assign[=] call[name[zap_helper].zap.users.users_list, parameter[call[name[info]][constant[id]]]]
if call[name[len], parameter[name[users]]] begin[:]
variable[user_list] assign[=] call[constant[, ].join, parameter[<ast.ListComp object at 0x7da2054a6860>]]
call[name[console].info, parameter[call[constant[Available users for the context {0}: {1}].format, parameter[name[context_name], name[user_list]]]]] | keyword[def] identifier[context_list_users] ( identifier[zap_helper] , identifier[context_name] ):
literal[string]
keyword[with] identifier[zap_error_handler] ():
identifier[info] = identifier[zap_helper] . identifier[get_context_info] ( identifier[context_name] )
identifier[users] = identifier[zap_helper] . identifier[zap] . identifier[users] . identifier[users_list] ( identifier[info] [ literal[string] ])
keyword[if] identifier[len] ( identifier[users] ):
identifier[user_list] = literal[string] . identifier[join] ([ identifier[user] [ literal[string] ] keyword[for] identifier[user] keyword[in] identifier[users] ])
identifier[console] . identifier[info] ( literal[string] . identifier[format] ( identifier[context_name] , identifier[user_list] ))
keyword[else] :
identifier[console] . identifier[info] ( literal[string] . identifier[format] ( identifier[context_name] )) | def context_list_users(zap_helper, context_name):
"""List the users available for a given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name) # depends on [control=['with'], data=[]]
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for the context {0}: {1}'.format(context_name, user_list)) # depends on [control=['if'], data=[]]
else:
console.info('No users configured for the context {}'.format(context_name)) |
def _format_range_dt(self, d):
"""Format range filter datetime to the closest aggregation interval."""
if not isinstance(d, six.string_types):
d = d.isoformat()
return '{0}||/{1}'.format(
d, self.dt_rounding_map[self.aggregation_interval]) | def function[_format_range_dt, parameter[self, d]]:
constant[Format range filter datetime to the closest aggregation interval.]
if <ast.UnaryOp object at 0x7da1afe668c0> begin[:]
variable[d] assign[=] call[name[d].isoformat, parameter[]]
return[call[constant[{0}||/{1}].format, parameter[name[d], call[name[self].dt_rounding_map][name[self].aggregation_interval]]]] | keyword[def] identifier[_format_range_dt] ( identifier[self] , identifier[d] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[d] , identifier[six] . identifier[string_types] ):
identifier[d] = identifier[d] . identifier[isoformat] ()
keyword[return] literal[string] . identifier[format] (
identifier[d] , identifier[self] . identifier[dt_rounding_map] [ identifier[self] . identifier[aggregation_interval] ]) | def _format_range_dt(self, d):
"""Format range filter datetime to the closest aggregation interval."""
if not isinstance(d, six.string_types):
d = d.isoformat() # depends on [control=['if'], data=[]]
return '{0}||/{1}'.format(d, self.dt_rounding_map[self.aggregation_interval]) |
def cortex_plot_2D(the_map,
color=None, cmap=None, vmin=None, vmax=None, alpha=None,
underlay='curvature', mask=None, axes=None, triangulation=None):
'''
cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map.
The following options are accepted:
* color (default: None) specifies the color to plot for each vertex; this argument may take a
number of forms:
* None, do not plot a color over the underlay (the default)
* a matrix of RGB or RGBA values, one per vertex
* a property vector or a string naming a property, in which case the cmap, vmin, and vmax
arguments are used to generate colors
* a function that, when passed a single argument, a dict of the properties of a single
vertex, yields an RGB or RGBA list for that vertex.
* cmap (default: 'log_eccentricity') specifies the colormap to use in plotting if the color
argument provided is a property.
* vmin (default: None) specifies the minimum value for scaling the property when one is passed
as the color option. None means to use the min value of the property.
* vmax (default: None) specifies the maximum value for scaling the property when one is passed
as the color option. None means to use the max value of the property.
* underlay (default: 'curvature') specifies the default underlay color to plot for the
cortical surface; it may be None, 'curvature', or a color.
* alpha (default None) specifies the alpha values to use for the color plot. If None, then
leaves the alpha values from color unchanged. If a single number, then all alpha values in
color are multiplied by that value. If a list of values, one per vertex, then this vector
is multiplied by the alpha values. Finally, any negative value is set instead of multiplied.
So, for example, if there were 3 vertices with:
* color = ((0,0,0,1), (0,0,1,0.5), (0,0,0.75,0,8))
* alpha = (-0.5, 1, 0.5)
then the resulting colors plotted will be ((0,0,0,0.5), (0,0,1,0.5), (0,0,0.75,0,4)).
* mask (default: None) specifies a mask to use for the mesh; thi sis passed through map.mask()
to figure out the masking. Those vertices not in the mask are not plotted (but they will be
plotted in the underlay if it is not None).
* axes (default: None) specifies a particular set of matplotlib pyplot axes that should be
used. If axes is Ellipsis, then instead of attempting to render the plot, a tuple of
(tri, zs, cmap) is returned; in this case, tri is a matplotlib.tri.Triangulation
object for the given map and zs and cmap are an array and colormap (respectively) that
will produce the correct colors. Without axes equal to Ellipsis, these would instead
be rendered as axes.tripcolor(tri, zs, cmap, shading='gouraud'). If axes is None, then
uses the current axes.
* triangulation (default: None) specifies the matplotlib triangulation object to use, if one
already exists; otherwise a new one is made.
'''
# parse the axes
if axes is None: axes = matplotlib.pyplot.gca()
# process the colors
color = cortex_plot_colors(the_map, color=color, cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha,
underlay=underlay, mask=mask)
# finally, we can make the plot!
return cortex_rgba_plot_2D(the_map, color, axes=axes, triangulation=triangulation) | def function[cortex_plot_2D, parameter[the_map, color, cmap, vmin, vmax, alpha, underlay, mask, axes, triangulation]]:
constant[
cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map.
The following options are accepted:
* color (default: None) specifies the color to plot for each vertex; this argument may take a
number of forms:
* None, do not plot a color over the underlay (the default)
* a matrix of RGB or RGBA values, one per vertex
* a property vector or a string naming a property, in which case the cmap, vmin, and vmax
arguments are used to generate colors
* a function that, when passed a single argument, a dict of the properties of a single
vertex, yields an RGB or RGBA list for that vertex.
* cmap (default: 'log_eccentricity') specifies the colormap to use in plotting if the color
argument provided is a property.
* vmin (default: None) specifies the minimum value for scaling the property when one is passed
as the color option. None means to use the min value of the property.
* vmax (default: None) specifies the maximum value for scaling the property when one is passed
as the color option. None means to use the max value of the property.
* underlay (default: 'curvature') specifies the default underlay color to plot for the
cortical surface; it may be None, 'curvature', or a color.
* alpha (default None) specifies the alpha values to use for the color plot. If None, then
leaves the alpha values from color unchanged. If a single number, then all alpha values in
color are multiplied by that value. If a list of values, one per vertex, then this vector
is multiplied by the alpha values. Finally, any negative value is set instead of multiplied.
So, for example, if there were 3 vertices with:
* color = ((0,0,0,1), (0,0,1,0.5), (0,0,0.75,0,8))
* alpha = (-0.5, 1, 0.5)
then the resulting colors plotted will be ((0,0,0,0.5), (0,0,1,0.5), (0,0,0.75,0,4)).
* mask (default: None) specifies a mask to use for the mesh; thi sis passed through map.mask()
to figure out the masking. Those vertices not in the mask are not plotted (but they will be
plotted in the underlay if it is not None).
* axes (default: None) specifies a particular set of matplotlib pyplot axes that should be
used. If axes is Ellipsis, then instead of attempting to render the plot, a tuple of
(tri, zs, cmap) is returned; in this case, tri is a matplotlib.tri.Triangulation
object for the given map and zs and cmap are an array and colormap (respectively) that
will produce the correct colors. Without axes equal to Ellipsis, these would instead
be rendered as axes.tripcolor(tri, zs, cmap, shading='gouraud'). If axes is None, then
uses the current axes.
* triangulation (default: None) specifies the matplotlib triangulation object to use, if one
already exists; otherwise a new one is made.
]
if compare[name[axes] is constant[None]] begin[:]
variable[axes] assign[=] call[name[matplotlib].pyplot.gca, parameter[]]
variable[color] assign[=] call[name[cortex_plot_colors], parameter[name[the_map]]]
return[call[name[cortex_rgba_plot_2D], parameter[name[the_map], name[color]]]] | keyword[def] identifier[cortex_plot_2D] ( identifier[the_map] ,
identifier[color] = keyword[None] , identifier[cmap] = keyword[None] , identifier[vmin] = keyword[None] , identifier[vmax] = keyword[None] , identifier[alpha] = keyword[None] ,
identifier[underlay] = literal[string] , identifier[mask] = keyword[None] , identifier[axes] = keyword[None] , identifier[triangulation] = keyword[None] ):
literal[string]
keyword[if] identifier[axes] keyword[is] keyword[None] : identifier[axes] = identifier[matplotlib] . identifier[pyplot] . identifier[gca] ()
identifier[color] = identifier[cortex_plot_colors] ( identifier[the_map] , identifier[color] = identifier[color] , identifier[cmap] = identifier[cmap] , identifier[vmin] = identifier[vmin] , identifier[vmax] = identifier[vmax] , identifier[alpha] = identifier[alpha] ,
identifier[underlay] = identifier[underlay] , identifier[mask] = identifier[mask] )
keyword[return] identifier[cortex_rgba_plot_2D] ( identifier[the_map] , identifier[color] , identifier[axes] = identifier[axes] , identifier[triangulation] = identifier[triangulation] ) | def cortex_plot_2D(the_map, color=None, cmap=None, vmin=None, vmax=None, alpha=None, underlay='curvature', mask=None, axes=None, triangulation=None):
"""
cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map.
The following options are accepted:
* color (default: None) specifies the color to plot for each vertex; this argument may take a
number of forms:
* None, do not plot a color over the underlay (the default)
* a matrix of RGB or RGBA values, one per vertex
* a property vector or a string naming a property, in which case the cmap, vmin, and vmax
arguments are used to generate colors
* a function that, when passed a single argument, a dict of the properties of a single
vertex, yields an RGB or RGBA list for that vertex.
* cmap (default: 'log_eccentricity') specifies the colormap to use in plotting if the color
argument provided is a property.
* vmin (default: None) specifies the minimum value for scaling the property when one is passed
as the color option. None means to use the min value of the property.
* vmax (default: None) specifies the maximum value for scaling the property when one is passed
as the color option. None means to use the max value of the property.
* underlay (default: 'curvature') specifies the default underlay color to plot for the
cortical surface; it may be None, 'curvature', or a color.
* alpha (default None) specifies the alpha values to use for the color plot. If None, then
leaves the alpha values from color unchanged. If a single number, then all alpha values in
color are multiplied by that value. If a list of values, one per vertex, then this vector
is multiplied by the alpha values. Finally, any negative value is set instead of multiplied.
So, for example, if there were 3 vertices with:
* color = ((0,0,0,1), (0,0,1,0.5), (0,0,0.75,0,8))
* alpha = (-0.5, 1, 0.5)
then the resulting colors plotted will be ((0,0,0,0.5), (0,0,1,0.5), (0,0,0.75,0,4)).
* mask (default: None) specifies a mask to use for the mesh; thi sis passed through map.mask()
to figure out the masking. Those vertices not in the mask are not plotted (but they will be
plotted in the underlay if it is not None).
* axes (default: None) specifies a particular set of matplotlib pyplot axes that should be
used. If axes is Ellipsis, then instead of attempting to render the plot, a tuple of
(tri, zs, cmap) is returned; in this case, tri is a matplotlib.tri.Triangulation
object for the given map and zs and cmap are an array and colormap (respectively) that
will produce the correct colors. Without axes equal to Ellipsis, these would instead
be rendered as axes.tripcolor(tri, zs, cmap, shading='gouraud'). If axes is None, then
uses the current axes.
* triangulation (default: None) specifies the matplotlib triangulation object to use, if one
already exists; otherwise a new one is made.
"""
# parse the axes
if axes is None:
axes = matplotlib.pyplot.gca() # depends on [control=['if'], data=['axes']]
# process the colors
color = cortex_plot_colors(the_map, color=color, cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha, underlay=underlay, mask=mask)
# finally, we can make the plot!
return cortex_rgba_plot_2D(the_map, color, axes=axes, triangulation=triangulation) |
def closest_allzero_pixel(self, pixel, direction, w=13, t=0.5):
"""Starting at pixel, moves pixel by direction * t until all
zero pixels within a radius w of pixel. Then, returns pixel.
Parameters
----------
pixel : :obj:`numpy.ndarray` of float
The initial pixel location at which to start.
direction : :obj:`numpy.ndarray` of float
The 2D direction vector in which to move pixel.
w : int
A circular diameter in which to check for zero pixels.
As soon as the current pixel has all zero pixels with a diameter
w of it, this function returns the current pixel location.
t : float
The step size with which to move pixel along direction.
Returns
-------
:obj:`numpy.ndarray` of float
The first pixel location along the direction vector at which there
exists all zero pixels within a radius w.
"""
# create circular structure for checking clearance
y, x = np.meshgrid(np.arange(w) - w / 2, np.arange(w) - w / 2)
cur_px_y = np.ravel(y + pixel[0]).astype(np.uint16)
cur_px_x = np.ravel(x + pixel[1]).astype(np.uint16)
# Check if all pixels in radius are in bounds and zero-valued
empty = False
if np.all(
cur_px_y >= 0) and np.all(
cur_px_y < self.height) and np.all(
cur_px_x >= 0) and np.all(
cur_px_x < self.width):
empty = np.all(self[cur_px_y, cur_px_x] <= self._threshold)
else:
return None
# If some nonzero pixels, continue incrementing along direction
# and checking for empty space
while not empty:
pixel = pixel + t * direction
cur_px_y = np.ravel(y + pixel[0]).astype(np.uint16)
cur_px_x = np.ravel(x + pixel[1]).astype(np.uint16)
if np.all(
cur_px_y >= 0) and np.all(
cur_px_y < self.height) and np.all(
cur_px_x >= 0) and np.all(
cur_px_x < self.width):
empty = np.all(self[cur_px_y, cur_px_x] <= self._threshold)
else:
return None
return pixel | def function[closest_allzero_pixel, parameter[self, pixel, direction, w, t]]:
constant[Starting at pixel, moves pixel by direction * t until all
zero pixels within a radius w of pixel. Then, returns pixel.
Parameters
----------
pixel : :obj:`numpy.ndarray` of float
The initial pixel location at which to start.
direction : :obj:`numpy.ndarray` of float
The 2D direction vector in which to move pixel.
w : int
A circular diameter in which to check for zero pixels.
As soon as the current pixel has all zero pixels with a diameter
w of it, this function returns the current pixel location.
t : float
The step size with which to move pixel along direction.
Returns
-------
:obj:`numpy.ndarray` of float
The first pixel location along the direction vector at which there
exists all zero pixels within a radius w.
]
<ast.Tuple object at 0x7da1b0575f60> assign[=] call[name[np].meshgrid, parameter[binary_operation[call[name[np].arange, parameter[name[w]]] - binary_operation[name[w] / constant[2]]], binary_operation[call[name[np].arange, parameter[name[w]]] - binary_operation[name[w] / constant[2]]]]]
variable[cur_px_y] assign[=] call[call[name[np].ravel, parameter[binary_operation[name[y] + call[name[pixel]][constant[0]]]]].astype, parameter[name[np].uint16]]
variable[cur_px_x] assign[=] call[call[name[np].ravel, parameter[binary_operation[name[x] + call[name[pixel]][constant[1]]]]].astype, parameter[name[np].uint16]]
variable[empty] assign[=] constant[False]
if <ast.BoolOp object at 0x7da1b05771c0> begin[:]
variable[empty] assign[=] call[name[np].all, parameter[compare[call[name[self]][tuple[[<ast.Name object at 0x7da1b0577f10>, <ast.Name object at 0x7da1b0576ce0>]]] less_or_equal[<=] name[self]._threshold]]]
while <ast.UnaryOp object at 0x7da1b0576860> begin[:]
variable[pixel] assign[=] binary_operation[name[pixel] + binary_operation[name[t] * name[direction]]]
variable[cur_px_y] assign[=] call[call[name[np].ravel, parameter[binary_operation[name[y] + call[name[pixel]][constant[0]]]]].astype, parameter[name[np].uint16]]
variable[cur_px_x] assign[=] call[call[name[np].ravel, parameter[binary_operation[name[x] + call[name[pixel]][constant[1]]]]].astype, parameter[name[np].uint16]]
if <ast.BoolOp object at 0x7da18ede41c0> begin[:]
variable[empty] assign[=] call[name[np].all, parameter[compare[call[name[self]][tuple[[<ast.Name object at 0x7da18dc99210>, <ast.Name object at 0x7da18dc9a650>]]] less_or_equal[<=] name[self]._threshold]]]
return[name[pixel]] | keyword[def] identifier[closest_allzero_pixel] ( identifier[self] , identifier[pixel] , identifier[direction] , identifier[w] = literal[int] , identifier[t] = literal[int] ):
literal[string]
identifier[y] , identifier[x] = identifier[np] . identifier[meshgrid] ( identifier[np] . identifier[arange] ( identifier[w] )- identifier[w] / literal[int] , identifier[np] . identifier[arange] ( identifier[w] )- identifier[w] / literal[int] )
identifier[cur_px_y] = identifier[np] . identifier[ravel] ( identifier[y] + identifier[pixel] [ literal[int] ]). identifier[astype] ( identifier[np] . identifier[uint16] )
identifier[cur_px_x] = identifier[np] . identifier[ravel] ( identifier[x] + identifier[pixel] [ literal[int] ]). identifier[astype] ( identifier[np] . identifier[uint16] )
identifier[empty] = keyword[False]
keyword[if] identifier[np] . identifier[all] (
identifier[cur_px_y] >= literal[int] ) keyword[and] identifier[np] . identifier[all] (
identifier[cur_px_y] < identifier[self] . identifier[height] ) keyword[and] identifier[np] . identifier[all] (
identifier[cur_px_x] >= literal[int] ) keyword[and] identifier[np] . identifier[all] (
identifier[cur_px_x] < identifier[self] . identifier[width] ):
identifier[empty] = identifier[np] . identifier[all] ( identifier[self] [ identifier[cur_px_y] , identifier[cur_px_x] ]<= identifier[self] . identifier[_threshold] )
keyword[else] :
keyword[return] keyword[None]
keyword[while] keyword[not] identifier[empty] :
identifier[pixel] = identifier[pixel] + identifier[t] * identifier[direction]
identifier[cur_px_y] = identifier[np] . identifier[ravel] ( identifier[y] + identifier[pixel] [ literal[int] ]). identifier[astype] ( identifier[np] . identifier[uint16] )
identifier[cur_px_x] = identifier[np] . identifier[ravel] ( identifier[x] + identifier[pixel] [ literal[int] ]). identifier[astype] ( identifier[np] . identifier[uint16] )
keyword[if] identifier[np] . identifier[all] (
identifier[cur_px_y] >= literal[int] ) keyword[and] identifier[np] . identifier[all] (
identifier[cur_px_y] < identifier[self] . identifier[height] ) keyword[and] identifier[np] . identifier[all] (
identifier[cur_px_x] >= literal[int] ) keyword[and] identifier[np] . identifier[all] (
identifier[cur_px_x] < identifier[self] . identifier[width] ):
identifier[empty] = identifier[np] . identifier[all] ( identifier[self] [ identifier[cur_px_y] , identifier[cur_px_x] ]<= identifier[self] . identifier[_threshold] )
keyword[else] :
keyword[return] keyword[None]
keyword[return] identifier[pixel] | def closest_allzero_pixel(self, pixel, direction, w=13, t=0.5):
"""Starting at pixel, moves pixel by direction * t until all
zero pixels within a radius w of pixel. Then, returns pixel.
Parameters
----------
pixel : :obj:`numpy.ndarray` of float
The initial pixel location at which to start.
direction : :obj:`numpy.ndarray` of float
The 2D direction vector in which to move pixel.
w : int
A circular diameter in which to check for zero pixels.
As soon as the current pixel has all zero pixels with a diameter
w of it, this function returns the current pixel location.
t : float
The step size with which to move pixel along direction.
Returns
-------
:obj:`numpy.ndarray` of float
The first pixel location along the direction vector at which there
exists all zero pixels within a radius w.
"""
# create circular structure for checking clearance
(y, x) = np.meshgrid(np.arange(w) - w / 2, np.arange(w) - w / 2)
cur_px_y = np.ravel(y + pixel[0]).astype(np.uint16)
cur_px_x = np.ravel(x + pixel[1]).astype(np.uint16)
# Check if all pixels in radius are in bounds and zero-valued
empty = False
if np.all(cur_px_y >= 0) and np.all(cur_px_y < self.height) and np.all(cur_px_x >= 0) and np.all(cur_px_x < self.width):
empty = np.all(self[cur_px_y, cur_px_x] <= self._threshold) # depends on [control=['if'], data=[]]
else:
return None
# If some nonzero pixels, continue incrementing along direction
# and checking for empty space
while not empty:
pixel = pixel + t * direction
cur_px_y = np.ravel(y + pixel[0]).astype(np.uint16)
cur_px_x = np.ravel(x + pixel[1]).astype(np.uint16)
if np.all(cur_px_y >= 0) and np.all(cur_px_y < self.height) and np.all(cur_px_x >= 0) and np.all(cur_px_x < self.width):
empty = np.all(self[cur_px_y, cur_px_x] <= self._threshold) # depends on [control=['if'], data=[]]
else:
return None # depends on [control=['while'], data=[]]
return pixel |
def mirtrace_contamination_check(self):
""" Generate the miRTrace Contamination Check"""
# A library of 24 colors. Should be enough for this plot
color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', 'rgb(255,127,0)', 'rgb(202,178,214)', 'rgb(106,61,154)', 'rgb(255,255,153)', 'rgb(177,89,40)', 'rgb(141,211,199)', 'rgb(255,255,179)', 'rgb(190,186,218)', 'rgb(251,128,114)', 'rgb(128,177,211)', 'rgb(253,180,98)', 'rgb(179,222,105)', 'rgb(252,205,229)', 'rgb(217,217,217)', 'rgb(188,128,189)', 'rgb(204,235,197)', 'rgb(255,237,111)']
idx = 0
# Specify the order of the different possible categories
keys = OrderedDict()
for clade in self.contamination_data[list(self.contamination_data.keys())[0]]:
keys[clade] = { 'color': color_lib[idx], 'name': clade }
if idx < 23:
idx += 1
else:
idx = 0
# Config for the plot
config = {
'cpswitch_c_active': False,
'id': 'mirtrace_contamination_check_plot',
'title': 'miRTrace: Contamination Check',
'ylab': '# miRNA detected',
'cpswitch_counts_label': 'Number of detected miRNA'
}
return bargraph.plot(self.contamination_data, keys, config) | def function[mirtrace_contamination_check, parameter[self]]:
constant[ Generate the miRTrace Contamination Check]
variable[color_lib] assign[=] list[[<ast.Constant object at 0x7da20e9b23e0>, <ast.Constant object at 0x7da20e9b2ef0>, <ast.Constant object at 0x7da20e9b2c20>, <ast.Constant object at 0x7da20e9b0790>, <ast.Constant object at 0x7da20e9b3100>, <ast.Constant object at 0x7da20e9b1a20>, <ast.Constant object at 0x7da20e9b1840>, <ast.Constant object at 0x7da20e9b1180>, <ast.Constant object at 0x7da20e9b00a0>, <ast.Constant object at 0x7da20e9b14b0>, <ast.Constant object at 0x7da20e9b3be0>, <ast.Constant object at 0x7da20e9b02e0>, <ast.Constant object at 0x7da20e9b0580>, <ast.Constant object at 0x7da20e9b2a10>, <ast.Constant object at 0x7da20e9b3ca0>, <ast.Constant object at 0x7da20e9b1060>, <ast.Constant object at 0x7da20e9b1b40>, <ast.Constant object at 0x7da20e9b1c60>, <ast.Constant object at 0x7da20e9b2fb0>, <ast.Constant object at 0x7da20e9b0f40>, <ast.Constant object at 0x7da20e9b2770>, <ast.Constant object at 0x7da20e9b3ee0>, <ast.Constant object at 0x7da20e9b1120>, <ast.Constant object at 0x7da20e9b0dc0>]]
variable[idx] assign[=] constant[0]
variable[keys] assign[=] call[name[OrderedDict], parameter[]]
for taget[name[clade]] in starred[call[name[self].contamination_data][call[call[name[list], parameter[call[name[self].contamination_data.keys, parameter[]]]]][constant[0]]]] begin[:]
call[name[keys]][name[clade]] assign[=] dictionary[[<ast.Constant object at 0x7da20e9b2980>, <ast.Constant object at 0x7da20e9b1ea0>], [<ast.Subscript object at 0x7da20e9b07c0>, <ast.Name object at 0x7da20e9b20b0>]]
if compare[name[idx] less[<] constant[23]] begin[:]
<ast.AugAssign object at 0x7da20e9b3f10>
variable[config] assign[=] dictionary[[<ast.Constant object at 0x7da20e9b17e0>, <ast.Constant object at 0x7da20e9b2590>, <ast.Constant object at 0x7da20e9b1bd0>, <ast.Constant object at 0x7da20e9b0400>, <ast.Constant object at 0x7da20e9b1870>], [<ast.Constant object at 0x7da20e9b0220>, <ast.Constant object at 0x7da20e9b38e0>, <ast.Constant object at 0x7da20e9b0df0>, <ast.Constant object at 0x7da20e9b1ae0>, <ast.Constant object at 0x7da20e9b3b50>]]
return[call[name[bargraph].plot, parameter[name[self].contamination_data, name[keys], name[config]]]] | keyword[def] identifier[mirtrace_contamination_check] ( identifier[self] ):
literal[string]
identifier[color_lib] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[idx] = literal[int]
identifier[keys] = identifier[OrderedDict] ()
keyword[for] identifier[clade] keyword[in] identifier[self] . identifier[contamination_data] [ identifier[list] ( identifier[self] . identifier[contamination_data] . identifier[keys] ())[ literal[int] ]]:
identifier[keys] [ identifier[clade] ]={ literal[string] : identifier[color_lib] [ identifier[idx] ], literal[string] : identifier[clade] }
keyword[if] identifier[idx] < literal[int] :
identifier[idx] += literal[int]
keyword[else] :
identifier[idx] = literal[int]
identifier[config] ={
literal[string] : keyword[False] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string]
}
keyword[return] identifier[bargraph] . identifier[plot] ( identifier[self] . identifier[contamination_data] , identifier[keys] , identifier[config] ) | def mirtrace_contamination_check(self):
""" Generate the miRTrace Contamination Check"""
# A library of 24 colors. Should be enough for this plot
color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', 'rgb(255,127,0)', 'rgb(202,178,214)', 'rgb(106,61,154)', 'rgb(255,255,153)', 'rgb(177,89,40)', 'rgb(141,211,199)', 'rgb(255,255,179)', 'rgb(190,186,218)', 'rgb(251,128,114)', 'rgb(128,177,211)', 'rgb(253,180,98)', 'rgb(179,222,105)', 'rgb(252,205,229)', 'rgb(217,217,217)', 'rgb(188,128,189)', 'rgb(204,235,197)', 'rgb(255,237,111)']
idx = 0
# Specify the order of the different possible categories
keys = OrderedDict()
for clade in self.contamination_data[list(self.contamination_data.keys())[0]]:
keys[clade] = {'color': color_lib[idx], 'name': clade}
if idx < 23:
idx += 1 # depends on [control=['if'], data=['idx']]
else:
idx = 0 # depends on [control=['for'], data=['clade']]
# Config for the plot
config = {'cpswitch_c_active': False, 'id': 'mirtrace_contamination_check_plot', 'title': 'miRTrace: Contamination Check', 'ylab': '# miRNA detected', 'cpswitch_counts_label': 'Number of detected miRNA'}
return bargraph.plot(self.contamination_data, keys, config) |
def aes_encrypt(mode, aes_key, aes_iv, *data):
"""Encrypt data with AES in specified mode."""
encryptor = Cipher(
algorithms.AES(aes_key),
mode(aes_iv),
backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value)
encryptor.finalize()
return result, None if not hasattr(encryptor, 'tag') else encryptor.tag | def function[aes_encrypt, parameter[mode, aes_key, aes_iv]]:
constant[Encrypt data with AES in specified mode.]
variable[encryptor] assign[=] call[call[name[Cipher], parameter[call[name[algorithms].AES, parameter[name[aes_key]]], call[name[mode], parameter[name[aes_iv]]]]].encryptor, parameter[]]
variable[result] assign[=] constant[None]
for taget[name[value]] in starred[name[data]] begin[:]
variable[result] assign[=] call[name[encryptor].update, parameter[name[value]]]
call[name[encryptor].finalize, parameter[]]
return[tuple[[<ast.Name object at 0x7da2054a5150>, <ast.IfExp object at 0x7da2054a48e0>]]] | keyword[def] identifier[aes_encrypt] ( identifier[mode] , identifier[aes_key] , identifier[aes_iv] ,* identifier[data] ):
literal[string]
identifier[encryptor] = identifier[Cipher] (
identifier[algorithms] . identifier[AES] ( identifier[aes_key] ),
identifier[mode] ( identifier[aes_iv] ),
identifier[backend] = identifier[default_backend] ()). identifier[encryptor] ()
identifier[result] = keyword[None]
keyword[for] identifier[value] keyword[in] identifier[data] :
identifier[result] = identifier[encryptor] . identifier[update] ( identifier[value] )
identifier[encryptor] . identifier[finalize] ()
keyword[return] identifier[result] , keyword[None] keyword[if] keyword[not] identifier[hasattr] ( identifier[encryptor] , literal[string] ) keyword[else] identifier[encryptor] . identifier[tag] | def aes_encrypt(mode, aes_key, aes_iv, *data):
"""Encrypt data with AES in specified mode."""
encryptor = Cipher(algorithms.AES(aes_key), mode(aes_iv), backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value) # depends on [control=['for'], data=['value']]
encryptor.finalize()
return (result, None if not hasattr(encryptor, 'tag') else encryptor.tag) |
def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False):
"""Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
"""
parent = target_path.parent
target_path_tmp = Path(parent, target_path.stem + ".tmp")
lock = Path(parent, target_path.stem + ".lock")
# If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir
if not parent.exists():
parent.mkdir(parents=True, exist_ok=True)
with FileLock(lock):
# we acquired a lock, it's possible that prior invocation was holding the lock and has
# completed bootstrapping, so let's check (again) if we need to do any work
if not target_path.exists() or force:
# extract our site-packages
for filename in archive.namelist():
if filename.startswith("site-packages"):
archive.extract(filename, target_path_tmp)
if compile_pyc:
compileall.compile_dir(target_path_tmp, quiet=2, workers=compile_workers)
# if using `force` we will need to delete our target path
if target_path.exists():
shutil.rmtree(str(target_path))
# atomic move
shutil.move(str(target_path_tmp), str(target_path)) | def function[extract_site_packages, parameter[archive, target_path, compile_pyc, compile_workers, force]]:
constant[Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
]
variable[parent] assign[=] name[target_path].parent
variable[target_path_tmp] assign[=] call[name[Path], parameter[name[parent], binary_operation[name[target_path].stem + constant[.tmp]]]]
variable[lock] assign[=] call[name[Path], parameter[name[parent], binary_operation[name[target_path].stem + constant[.lock]]]]
if <ast.UnaryOp object at 0x7da20c76e710> begin[:]
call[name[parent].mkdir, parameter[]]
with call[name[FileLock], parameter[name[lock]]] begin[:]
if <ast.BoolOp object at 0x7da1b11f7b80> begin[:]
for taget[name[filename]] in starred[call[name[archive].namelist, parameter[]]] begin[:]
if call[name[filename].startswith, parameter[constant[site-packages]]] begin[:]
call[name[archive].extract, parameter[name[filename], name[target_path_tmp]]]
if name[compile_pyc] begin[:]
call[name[compileall].compile_dir, parameter[name[target_path_tmp]]]
if call[name[target_path].exists, parameter[]] begin[:]
call[name[shutil].rmtree, parameter[call[name[str], parameter[name[target_path]]]]]
call[name[shutil].move, parameter[call[name[str], parameter[name[target_path_tmp]]], call[name[str], parameter[name[target_path]]]]] | keyword[def] identifier[extract_site_packages] ( identifier[archive] , identifier[target_path] , identifier[compile_pyc] , identifier[compile_workers] = literal[int] , identifier[force] = keyword[False] ):
literal[string]
identifier[parent] = identifier[target_path] . identifier[parent]
identifier[target_path_tmp] = identifier[Path] ( identifier[parent] , identifier[target_path] . identifier[stem] + literal[string] )
identifier[lock] = identifier[Path] ( identifier[parent] , identifier[target_path] . identifier[stem] + literal[string] )
keyword[if] keyword[not] identifier[parent] . identifier[exists] ():
identifier[parent] . identifier[mkdir] ( identifier[parents] = keyword[True] , identifier[exist_ok] = keyword[True] )
keyword[with] identifier[FileLock] ( identifier[lock] ):
keyword[if] keyword[not] identifier[target_path] . identifier[exists] () keyword[or] identifier[force] :
keyword[for] identifier[filename] keyword[in] identifier[archive] . identifier[namelist] ():
keyword[if] identifier[filename] . identifier[startswith] ( literal[string] ):
identifier[archive] . identifier[extract] ( identifier[filename] , identifier[target_path_tmp] )
keyword[if] identifier[compile_pyc] :
identifier[compileall] . identifier[compile_dir] ( identifier[target_path_tmp] , identifier[quiet] = literal[int] , identifier[workers] = identifier[compile_workers] )
keyword[if] identifier[target_path] . identifier[exists] ():
identifier[shutil] . identifier[rmtree] ( identifier[str] ( identifier[target_path] ))
identifier[shutil] . identifier[move] ( identifier[str] ( identifier[target_path_tmp] ), identifier[str] ( identifier[target_path] )) | def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False):
"""Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
"""
parent = target_path.parent
target_path_tmp = Path(parent, target_path.stem + '.tmp')
lock = Path(parent, target_path.stem + '.lock')
# If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir
if not parent.exists():
parent.mkdir(parents=True, exist_ok=True) # depends on [control=['if'], data=[]]
with FileLock(lock):
# we acquired a lock, it's possible that prior invocation was holding the lock and has
# completed bootstrapping, so let's check (again) if we need to do any work
if not target_path.exists() or force:
# extract our site-packages
for filename in archive.namelist():
if filename.startswith('site-packages'):
archive.extract(filename, target_path_tmp) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['filename']]
if compile_pyc:
compileall.compile_dir(target_path_tmp, quiet=2, workers=compile_workers) # depends on [control=['if'], data=[]]
# if using `force` we will need to delete our target path
if target_path.exists():
shutil.rmtree(str(target_path)) # depends on [control=['if'], data=[]]
# atomic move
shutil.move(str(target_path_tmp), str(target_path)) # depends on [control=['if'], data=[]] # depends on [control=['with'], data=[]] |
def from_json(json_str, allow_pickle=False):
"""
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache import * # NOQA
>>> import utool as ut
>>> json_str = 'just a normal string'
>>> json_str = '["just a normal string"]'
>>> allow_pickle = False
>>> val = from_json(json_str, allow_pickle)
>>> result = ('val = %s' % (ut.repr2(val),))
>>> print(result)
"""
if six.PY3:
if isinstance(json_str, bytes):
json_str = json_str.decode('utf-8')
UtoolJSONEncoder = make_utool_json_encoder(allow_pickle)
object_hook = UtoolJSONEncoder._json_object_hook
val = json.loads(json_str, object_hook=object_hook)
return val | def function[from_json, parameter[json_str, allow_pickle]]:
constant[
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache import * # NOQA
>>> import utool as ut
>>> json_str = 'just a normal string'
>>> json_str = '["just a normal string"]'
>>> allow_pickle = False
>>> val = from_json(json_str, allow_pickle)
>>> result = ('val = %s' % (ut.repr2(val),))
>>> print(result)
]
if name[six].PY3 begin[:]
if call[name[isinstance], parameter[name[json_str], name[bytes]]] begin[:]
variable[json_str] assign[=] call[name[json_str].decode, parameter[constant[utf-8]]]
variable[UtoolJSONEncoder] assign[=] call[name[make_utool_json_encoder], parameter[name[allow_pickle]]]
variable[object_hook] assign[=] name[UtoolJSONEncoder]._json_object_hook
variable[val] assign[=] call[name[json].loads, parameter[name[json_str]]]
return[name[val]] | keyword[def] identifier[from_json] ( identifier[json_str] , identifier[allow_pickle] = keyword[False] ):
literal[string]
keyword[if] identifier[six] . identifier[PY3] :
keyword[if] identifier[isinstance] ( identifier[json_str] , identifier[bytes] ):
identifier[json_str] = identifier[json_str] . identifier[decode] ( literal[string] )
identifier[UtoolJSONEncoder] = identifier[make_utool_json_encoder] ( identifier[allow_pickle] )
identifier[object_hook] = identifier[UtoolJSONEncoder] . identifier[_json_object_hook]
identifier[val] = identifier[json] . identifier[loads] ( identifier[json_str] , identifier[object_hook] = identifier[object_hook] )
keyword[return] identifier[val] | def from_json(json_str, allow_pickle=False):
"""
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache import * # NOQA
>>> import utool as ut
>>> json_str = 'just a normal string'
>>> json_str = '["just a normal string"]'
>>> allow_pickle = False
>>> val = from_json(json_str, allow_pickle)
>>> result = ('val = %s' % (ut.repr2(val),))
>>> print(result)
"""
if six.PY3:
if isinstance(json_str, bytes):
json_str = json_str.decode('utf-8') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
UtoolJSONEncoder = make_utool_json_encoder(allow_pickle)
object_hook = UtoolJSONEncoder._json_object_hook
val = json.loads(json_str, object_hook=object_hook)
return val |
def delete(self, id):
"""delete."""
project = db.session.query(Project).filter_by(id=id).first()
if project is None:
response = jsonify({
'projects': None,
'message': 'No interface defined for URL.'
})
return response, 404
db.session.delete(project)
db.session.commit()
return jsonify({
'project': project.serialize
}) | def function[delete, parameter[self, id]]:
constant[delete.]
variable[project] assign[=] call[call[call[name[db].session.query, parameter[name[Project]]].filter_by, parameter[]].first, parameter[]]
if compare[name[project] is constant[None]] begin[:]
variable[response] assign[=] call[name[jsonify], parameter[dictionary[[<ast.Constant object at 0x7da1b0f59390>, <ast.Constant object at 0x7da1b0f5a5f0>], [<ast.Constant object at 0x7da1b0f5abc0>, <ast.Constant object at 0x7da1b0f5bfa0>]]]]
return[tuple[[<ast.Name object at 0x7da1b0f5b1f0>, <ast.Constant object at 0x7da1b0f581c0>]]]
call[name[db].session.delete, parameter[name[project]]]
call[name[db].session.commit, parameter[]]
return[call[name[jsonify], parameter[dictionary[[<ast.Constant object at 0x7da1b0f0d9f0>], [<ast.Attribute object at 0x7da1b0f0cc10>]]]]] | keyword[def] identifier[delete] ( identifier[self] , identifier[id] ):
literal[string]
identifier[project] = identifier[db] . identifier[session] . identifier[query] ( identifier[Project] ). identifier[filter_by] ( identifier[id] = identifier[id] ). identifier[first] ()
keyword[if] identifier[project] keyword[is] keyword[None] :
identifier[response] = identifier[jsonify] ({
literal[string] : keyword[None] ,
literal[string] : literal[string]
})
keyword[return] identifier[response] , literal[int]
identifier[db] . identifier[session] . identifier[delete] ( identifier[project] )
identifier[db] . identifier[session] . identifier[commit] ()
keyword[return] identifier[jsonify] ({
literal[string] : identifier[project] . identifier[serialize]
}) | def delete(self, id):
"""delete."""
project = db.session.query(Project).filter_by(id=id).first()
if project is None:
response = jsonify({'projects': None, 'message': 'No interface defined for URL.'})
return (response, 404) # depends on [control=['if'], data=[]]
db.session.delete(project)
db.session.commit()
return jsonify({'project': project.serialize}) |
def format_timestamp(
ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
"""
if isinstance(ts, (int, float)):
time_num = ts
elif isinstance(ts, (tuple, time.struct_time)):
time_num = calendar.timegm(ts)
elif isinstance(ts, datetime.datetime):
time_num = calendar.timegm(ts.utctimetuple())
else:
raise TypeError("unknown timestamp type: %r" % ts)
return email.utils.formatdate(time_num, usegmt=True) | def function[format_timestamp, parameter[ts]]:
constant[Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
]
if call[name[isinstance], parameter[name[ts], tuple[[<ast.Name object at 0x7da1b20c9e70>, <ast.Name object at 0x7da1b20c8670>]]]] begin[:]
variable[time_num] assign[=] name[ts]
return[call[name[email].utils.formatdate, parameter[name[time_num]]]] | keyword[def] identifier[format_timestamp] (
identifier[ts] : identifier[Union] [ identifier[int] , identifier[float] , identifier[tuple] , identifier[time] . identifier[struct_time] , identifier[datetime] . identifier[datetime] ]
)-> identifier[str] :
literal[string]
keyword[if] identifier[isinstance] ( identifier[ts] ,( identifier[int] , identifier[float] )):
identifier[time_num] = identifier[ts]
keyword[elif] identifier[isinstance] ( identifier[ts] ,( identifier[tuple] , identifier[time] . identifier[struct_time] )):
identifier[time_num] = identifier[calendar] . identifier[timegm] ( identifier[ts] )
keyword[elif] identifier[isinstance] ( identifier[ts] , identifier[datetime] . identifier[datetime] ):
identifier[time_num] = identifier[calendar] . identifier[timegm] ( identifier[ts] . identifier[utctimetuple] ())
keyword[else] :
keyword[raise] identifier[TypeError] ( literal[string] % identifier[ts] )
keyword[return] identifier[email] . identifier[utils] . identifier[formatdate] ( identifier[time_num] , identifier[usegmt] = keyword[True] ) | def format_timestamp(ts: Union[int, float, tuple, time.struct_time, datetime.datetime]) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
"""
if isinstance(ts, (int, float)):
time_num = ts # depends on [control=['if'], data=[]]
elif isinstance(ts, (tuple, time.struct_time)):
time_num = calendar.timegm(ts) # depends on [control=['if'], data=[]]
elif isinstance(ts, datetime.datetime):
time_num = calendar.timegm(ts.utctimetuple()) # depends on [control=['if'], data=[]]
else:
raise TypeError('unknown timestamp type: %r' % ts)
return email.utils.formatdate(time_num, usegmt=True) |
def fetch_items(self, category, **kwargs):
"""Fetch the contents
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching historical contents of '%s' from %s",
self.url, str(from_date))
nhcs = 0
contents = self.__fetch_contents_summary(from_date)
contents = [content for content in contents]
for content in contents:
cid = content['id']
content_url = urijoin(self.origin, content['_links']['webui'])
hcs = self.__fetch_historical_contents(cid, from_date)
for hc in hcs:
hc['content_url'] = content_url
hc['ancestors'] = content.get('ancestors', [])
yield hc
nhcs += 1
logger.info("Fetch process completed: %s historical contents fetched",
nhcs) | def function[fetch_items, parameter[self, category]]:
constant[Fetch the contents
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
]
variable[from_date] assign[=] call[name[kwargs]][constant[from_date]]
call[name[logger].info, parameter[constant[Fetching historical contents of '%s' from %s], name[self].url, call[name[str], parameter[name[from_date]]]]]
variable[nhcs] assign[=] constant[0]
variable[contents] assign[=] call[name[self].__fetch_contents_summary, parameter[name[from_date]]]
variable[contents] assign[=] <ast.ListComp object at 0x7da1b0350940>
for taget[name[content]] in starred[name[contents]] begin[:]
variable[cid] assign[=] call[name[content]][constant[id]]
variable[content_url] assign[=] call[name[urijoin], parameter[name[self].origin, call[call[name[content]][constant[_links]]][constant[webui]]]]
variable[hcs] assign[=] call[name[self].__fetch_historical_contents, parameter[name[cid], name[from_date]]]
for taget[name[hc]] in starred[name[hcs]] begin[:]
call[name[hc]][constant[content_url]] assign[=] name[content_url]
call[name[hc]][constant[ancestors]] assign[=] call[name[content].get, parameter[constant[ancestors], list[[]]]]
<ast.Yield object at 0x7da1b0351690>
<ast.AugAssign object at 0x7da1b0351150>
call[name[logger].info, parameter[constant[Fetch process completed: %s historical contents fetched], name[nhcs]]] | keyword[def] identifier[fetch_items] ( identifier[self] , identifier[category] ,** identifier[kwargs] ):
literal[string]
identifier[from_date] = identifier[kwargs] [ literal[string] ]
identifier[logger] . identifier[info] ( literal[string] ,
identifier[self] . identifier[url] , identifier[str] ( identifier[from_date] ))
identifier[nhcs] = literal[int]
identifier[contents] = identifier[self] . identifier[__fetch_contents_summary] ( identifier[from_date] )
identifier[contents] =[ identifier[content] keyword[for] identifier[content] keyword[in] identifier[contents] ]
keyword[for] identifier[content] keyword[in] identifier[contents] :
identifier[cid] = identifier[content] [ literal[string] ]
identifier[content_url] = identifier[urijoin] ( identifier[self] . identifier[origin] , identifier[content] [ literal[string] ][ literal[string] ])
identifier[hcs] = identifier[self] . identifier[__fetch_historical_contents] ( identifier[cid] , identifier[from_date] )
keyword[for] identifier[hc] keyword[in] identifier[hcs] :
identifier[hc] [ literal[string] ]= identifier[content_url]
identifier[hc] [ literal[string] ]= identifier[content] . identifier[get] ( literal[string] ,[])
keyword[yield] identifier[hc]
identifier[nhcs] += literal[int]
identifier[logger] . identifier[info] ( literal[string] ,
identifier[nhcs] ) | def fetch_items(self, category, **kwargs):
"""Fetch the contents
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching historical contents of '%s' from %s", self.url, str(from_date))
nhcs = 0
contents = self.__fetch_contents_summary(from_date)
contents = [content for content in contents]
for content in contents:
cid = content['id']
content_url = urijoin(self.origin, content['_links']['webui'])
hcs = self.__fetch_historical_contents(cid, from_date)
for hc in hcs:
hc['content_url'] = content_url
hc['ancestors'] = content.get('ancestors', [])
yield hc
nhcs += 1 # depends on [control=['for'], data=['hc']] # depends on [control=['for'], data=['content']]
logger.info('Fetch process completed: %s historical contents fetched', nhcs) |
def login(self, login, password):
"""
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
"""
self.client.read_until('Username: ')
self.client.write(login + '\r\n')
self.client.read_until('Password: ')
self.client.write(password + '\r\n')
current_data = self.client.read_until('$ ', 10)
if not current_data.endswith('$ '):
raise InvalidLogin | def function[login, parameter[self, login, password]]:
constant[
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
]
call[name[self].client.read_until, parameter[constant[Username: ]]]
call[name[self].client.write, parameter[binary_operation[name[login] + constant[
]]]]
call[name[self].client.read_until, parameter[constant[Password: ]]]
call[name[self].client.write, parameter[binary_operation[name[password] + constant[
]]]]
variable[current_data] assign[=] call[name[self].client.read_until, parameter[constant[$ ], constant[10]]]
if <ast.UnaryOp object at 0x7da1b11ee020> begin[:]
<ast.Raise object at 0x7da1b11ee050> | keyword[def] identifier[login] ( identifier[self] , identifier[login] , identifier[password] ):
literal[string]
identifier[self] . identifier[client] . identifier[read_until] ( literal[string] )
identifier[self] . identifier[client] . identifier[write] ( identifier[login] + literal[string] )
identifier[self] . identifier[client] . identifier[read_until] ( literal[string] )
identifier[self] . identifier[client] . identifier[write] ( identifier[password] + literal[string] )
identifier[current_data] = identifier[self] . identifier[client] . identifier[read_until] ( literal[string] , literal[int] )
keyword[if] keyword[not] identifier[current_data] . identifier[endswith] ( literal[string] ):
keyword[raise] identifier[InvalidLogin] | def login(self, login, password):
"""
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
"""
self.client.read_until('Username: ')
self.client.write(login + '\r\n')
self.client.read_until('Password: ')
self.client.write(password + '\r\n')
current_data = self.client.read_until('$ ', 10)
if not current_data.endswith('$ '):
raise InvalidLogin # depends on [control=['if'], data=[]] |
def get_relations(self, rel_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Relation
:param rel_id: Id of the relation
:type rel_id: Integer
:return: List of elements
"""
return self.get_elements(Relation, elem_id=rel_id, **kwargs) | def function[get_relations, parameter[self, rel_id]]:
constant[
Alias for get_elements() but filter the result by Relation
:param rel_id: Id of the relation
:type rel_id: Integer
:return: List of elements
]
return[call[name[self].get_elements, parameter[name[Relation]]]] | keyword[def] identifier[get_relations] ( identifier[self] , identifier[rel_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[get_elements] ( identifier[Relation] , identifier[elem_id] = identifier[rel_id] ,** identifier[kwargs] ) | def get_relations(self, rel_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Relation
:param rel_id: Id of the relation
:type rel_id: Integer
:return: List of elements
"""
return self.get_elements(Relation, elem_id=rel_id, **kwargs) |
def get_required_fields(self):
"""Return the names of fields that are required according to the schema."""
return [m.name for m in self._ast_node.members if m.member_schema.required] | def function[get_required_fields, parameter[self]]:
constant[Return the names of fields that are required according to the schema.]
return[<ast.ListComp object at 0x7da20c76d750>] | keyword[def] identifier[get_required_fields] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[m] . identifier[name] keyword[for] identifier[m] keyword[in] identifier[self] . identifier[_ast_node] . identifier[members] keyword[if] identifier[m] . identifier[member_schema] . identifier[required] ] | def get_required_fields(self):
"""Return the names of fields that are required according to the schema."""
return [m.name for m in self._ast_node.members if m.member_schema.required] |
def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (
cmd, VALID_COMMANDS, STOMP_VERSION)
)
else:
self._cmd = cmd | def function[setCmd, parameter[self, cmd]]:
constant[Check the cmd is valid, FrameError will be raised if its not.]
variable[cmd] assign[=] call[name[cmd].upper, parameter[]]
if compare[name[cmd] <ast.NotIn object at 0x7da2590d7190> name[VALID_COMMANDS]] begin[:]
<ast.Raise object at 0x7da204566590> | keyword[def] identifier[setCmd] ( identifier[self] , identifier[cmd] ):
literal[string]
identifier[cmd] = identifier[cmd] . identifier[upper] ()
keyword[if] identifier[cmd] keyword[not] keyword[in] identifier[VALID_COMMANDS] :
keyword[raise] identifier[FrameError] ( literal[string] %(
identifier[cmd] , identifier[VALID_COMMANDS] , identifier[STOMP_VERSION] )
)
keyword[else] :
identifier[self] . identifier[_cmd] = identifier[cmd] | def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (cmd, VALID_COMMANDS, STOMP_VERSION)) # depends on [control=['if'], data=['cmd', 'VALID_COMMANDS']]
else:
self._cmd = cmd |
def validateDeviceTypeConfiguration(self, typeId):
"""
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure.
"""
req = ApiClient.draftDeviceTypeUrl % (self.host, typeId)
body = {"operation" : "validate-configuration"}
resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body),
verify=self.verify)
if resp.status_code == 200:
self.logger.debug("Validation for device type configuration succeeded")
else:
raise ibmiotf.APIException(resp.status_code, "Validation for device type configuration failed", resp)
return resp.json() | def function[validateDeviceTypeConfiguration, parameter[self, typeId]]:
constant[
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure.
]
variable[req] assign[=] binary_operation[name[ApiClient].draftDeviceTypeUrl <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18fe931f0>, <ast.Name object at 0x7da18fe903a0>]]]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da18fe90760>], [<ast.Constant object at 0x7da18fe937f0>]]
variable[resp] assign[=] call[name[requests].patch, parameter[name[req]]]
if compare[name[resp].status_code equal[==] constant[200]] begin[:]
call[name[self].logger.debug, parameter[constant[Validation for device type configuration succeeded]]]
return[call[name[resp].json, parameter[]]] | keyword[def] identifier[validateDeviceTypeConfiguration] ( identifier[self] , identifier[typeId] ):
literal[string]
identifier[req] = identifier[ApiClient] . identifier[draftDeviceTypeUrl] %( identifier[self] . identifier[host] , identifier[typeId] )
identifier[body] ={ literal[string] : literal[string] }
identifier[resp] = identifier[requests] . identifier[patch] ( identifier[req] , identifier[auth] = identifier[self] . identifier[credentials] , identifier[headers] ={ literal[string] : literal[string] }, identifier[data] = identifier[json] . identifier[dumps] ( identifier[body] ),
identifier[verify] = identifier[self] . identifier[verify] )
keyword[if] identifier[resp] . identifier[status_code] == literal[int] :
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
keyword[else] :
keyword[raise] identifier[ibmiotf] . identifier[APIException] ( identifier[resp] . identifier[status_code] , literal[string] , identifier[resp] )
keyword[return] identifier[resp] . identifier[json] () | def validateDeviceTypeConfiguration(self, typeId):
"""
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure.
"""
req = ApiClient.draftDeviceTypeUrl % (self.host, typeId)
body = {'operation': 'validate-configuration'}
resp = requests.patch(req, auth=self.credentials, headers={'Content-Type': 'application/json'}, data=json.dumps(body), verify=self.verify)
if resp.status_code == 200:
self.logger.debug('Validation for device type configuration succeeded') # depends on [control=['if'], data=[]]
else:
raise ibmiotf.APIException(resp.status_code, 'Validation for device type configuration failed', resp)
return resp.json() |
def _check_1st_line(line, **kwargs):
"""First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:param max_first_line: maximum length of the first line
:type max_first_line: int
:return: errors as in (code, line number, *args)
:rtype: list
"""
components = kwargs.get("components", ())
max_first_line = kwargs.get("max_first_line", 50)
errors = []
lineno = 1
if len(line) > max_first_line:
errors.append(("M190", lineno, max_first_line, len(line)))
if line.endswith("."):
errors.append(("M191", lineno))
if ':' not in line:
errors.append(("M110", lineno))
else:
component, msg = line.split(':', 1)
if component not in components:
errors.append(("M111", lineno, component))
return errors | def function[_check_1st_line, parameter[line]]:
constant[First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:param max_first_line: maximum length of the first line
:type max_first_line: int
:return: errors as in (code, line number, *args)
:rtype: list
]
variable[components] assign[=] call[name[kwargs].get, parameter[constant[components], tuple[[]]]]
variable[max_first_line] assign[=] call[name[kwargs].get, parameter[constant[max_first_line], constant[50]]]
variable[errors] assign[=] list[[]]
variable[lineno] assign[=] constant[1]
if compare[call[name[len], parameter[name[line]]] greater[>] name[max_first_line]] begin[:]
call[name[errors].append, parameter[tuple[[<ast.Constant object at 0x7da18f00d270>, <ast.Name object at 0x7da18f00e980>, <ast.Name object at 0x7da18f00c970>, <ast.Call object at 0x7da18f00fdc0>]]]]
if call[name[line].endswith, parameter[constant[.]]] begin[:]
call[name[errors].append, parameter[tuple[[<ast.Constant object at 0x7da18f00ece0>, <ast.Name object at 0x7da18f00e410>]]]]
if compare[constant[:] <ast.NotIn object at 0x7da2590d7190> name[line]] begin[:]
call[name[errors].append, parameter[tuple[[<ast.Constant object at 0x7da18f00c0d0>, <ast.Name object at 0x7da18f00f370>]]]]
return[name[errors]] | keyword[def] identifier[_check_1st_line] ( identifier[line] ,** identifier[kwargs] ):
literal[string]
identifier[components] = identifier[kwargs] . identifier[get] ( literal[string] ,())
identifier[max_first_line] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] )
identifier[errors] =[]
identifier[lineno] = literal[int]
keyword[if] identifier[len] ( identifier[line] )> identifier[max_first_line] :
identifier[errors] . identifier[append] (( literal[string] , identifier[lineno] , identifier[max_first_line] , identifier[len] ( identifier[line] )))
keyword[if] identifier[line] . identifier[endswith] ( literal[string] ):
identifier[errors] . identifier[append] (( literal[string] , identifier[lineno] ))
keyword[if] literal[string] keyword[not] keyword[in] identifier[line] :
identifier[errors] . identifier[append] (( literal[string] , identifier[lineno] ))
keyword[else] :
identifier[component] , identifier[msg] = identifier[line] . identifier[split] ( literal[string] , literal[int] )
keyword[if] identifier[component] keyword[not] keyword[in] identifier[components] :
identifier[errors] . identifier[append] (( literal[string] , identifier[lineno] , identifier[component] ))
keyword[return] identifier[errors] | def _check_1st_line(line, **kwargs):
"""First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:param max_first_line: maximum length of the first line
:type max_first_line: int
:return: errors as in (code, line number, *args)
:rtype: list
"""
components = kwargs.get('components', ())
max_first_line = kwargs.get('max_first_line', 50)
errors = []
lineno = 1
if len(line) > max_first_line:
errors.append(('M190', lineno, max_first_line, len(line))) # depends on [control=['if'], data=['max_first_line']]
if line.endswith('.'):
errors.append(('M191', lineno)) # depends on [control=['if'], data=[]]
if ':' not in line:
errors.append(('M110', lineno)) # depends on [control=['if'], data=[]]
else:
(component, msg) = line.split(':', 1)
if component not in components:
errors.append(('M111', lineno, component)) # depends on [control=['if'], data=['component']]
return errors |
def __extractOntologies(self, exclude_BNodes = False, return_string=False):
"""
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
"""
out = []
qres = self.queryHelper.getOntology()
if qres:
# NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..)
for candidate in qres:
if isBlankNode(candidate[0]):
if exclude_BNodes:
continue
else:
checkDC_ID = [x for x in self.rdfgraph.objects(candidate[0], rdflib.namespace.DC.identifier)]
if checkDC_ID:
out += [Ontology(checkDC_ID[0], namespaces=self.namespaces),]
else:
vannprop = rdflib.URIRef("http://purl.org/vocab/vann/preferredNamespaceUri")
vannpref = rdflib.URIRef("http://purl.org/vocab/vann/preferredNamespacePrefix")
checkDC_ID = [x for x in self.rdfgraph.objects(candidate[0], vannprop)]
if checkDC_ID:
checkDC_prefix = [x for x in self.rdfgraph.objects(candidate[0], vannpref)]
if checkDC_prefix:
out += [Ontology(checkDC_ID[0],
namespaces=self.namespaces,
prefPrefix=checkDC_prefix[0])]
else:
out += [Ontology(checkDC_ID[0], namespaces=self.namespaces)]
else:
out += [Ontology(candidate[0], namespaces=self.namespaces)]
else:
pass
# printDebug("No owl:Ontologies found")
#finally... add all annotations/triples
self.ontologies = out
for onto in self.ontologies:
onto.triples = self.queryHelper.entityTriples(onto.uri)
onto._buildGraph() | def function[__extractOntologies, parameter[self, exclude_BNodes, return_string]]:
constant[
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
]
variable[out] assign[=] list[[]]
variable[qres] assign[=] call[name[self].queryHelper.getOntology, parameter[]]
if name[qres] begin[:]
for taget[name[candidate]] in starred[name[qres]] begin[:]
if call[name[isBlankNode], parameter[call[name[candidate]][constant[0]]]] begin[:]
if name[exclude_BNodes] begin[:]
continue
name[self].ontologies assign[=] name[out]
for taget[name[onto]] in starred[name[self].ontologies] begin[:]
name[onto].triples assign[=] call[name[self].queryHelper.entityTriples, parameter[name[onto].uri]]
call[name[onto]._buildGraph, parameter[]] | keyword[def] identifier[__extractOntologies] ( identifier[self] , identifier[exclude_BNodes] = keyword[False] , identifier[return_string] = keyword[False] ):
literal[string]
identifier[out] =[]
identifier[qres] = identifier[self] . identifier[queryHelper] . identifier[getOntology] ()
keyword[if] identifier[qres] :
keyword[for] identifier[candidate] keyword[in] identifier[qres] :
keyword[if] identifier[isBlankNode] ( identifier[candidate] [ literal[int] ]):
keyword[if] identifier[exclude_BNodes] :
keyword[continue]
keyword[else] :
identifier[checkDC_ID] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[self] . identifier[rdfgraph] . identifier[objects] ( identifier[candidate] [ literal[int] ], identifier[rdflib] . identifier[namespace] . identifier[DC] . identifier[identifier] )]
keyword[if] identifier[checkDC_ID] :
identifier[out] +=[ identifier[Ontology] ( identifier[checkDC_ID] [ literal[int] ], identifier[namespaces] = identifier[self] . identifier[namespaces] ),]
keyword[else] :
identifier[vannprop] = identifier[rdflib] . identifier[URIRef] ( literal[string] )
identifier[vannpref] = identifier[rdflib] . identifier[URIRef] ( literal[string] )
identifier[checkDC_ID] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[self] . identifier[rdfgraph] . identifier[objects] ( identifier[candidate] [ literal[int] ], identifier[vannprop] )]
keyword[if] identifier[checkDC_ID] :
identifier[checkDC_prefix] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[self] . identifier[rdfgraph] . identifier[objects] ( identifier[candidate] [ literal[int] ], identifier[vannpref] )]
keyword[if] identifier[checkDC_prefix] :
identifier[out] +=[ identifier[Ontology] ( identifier[checkDC_ID] [ literal[int] ],
identifier[namespaces] = identifier[self] . identifier[namespaces] ,
identifier[prefPrefix] = identifier[checkDC_prefix] [ literal[int] ])]
keyword[else] :
identifier[out] +=[ identifier[Ontology] ( identifier[checkDC_ID] [ literal[int] ], identifier[namespaces] = identifier[self] . identifier[namespaces] )]
keyword[else] :
identifier[out] +=[ identifier[Ontology] ( identifier[candidate] [ literal[int] ], identifier[namespaces] = identifier[self] . identifier[namespaces] )]
keyword[else] :
keyword[pass]
identifier[self] . identifier[ontologies] = identifier[out]
keyword[for] identifier[onto] keyword[in] identifier[self] . identifier[ontologies] :
identifier[onto] . identifier[triples] = identifier[self] . identifier[queryHelper] . identifier[entityTriples] ( identifier[onto] . identifier[uri] )
identifier[onto] . identifier[_buildGraph] () | def __extractOntologies(self, exclude_BNodes=False, return_string=False):
"""
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
"""
out = []
qres = self.queryHelper.getOntology()
if qres:
# NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..)
for candidate in qres:
if isBlankNode(candidate[0]):
if exclude_BNodes:
continue # depends on [control=['if'], data=[]]
else:
checkDC_ID = [x for x in self.rdfgraph.objects(candidate[0], rdflib.namespace.DC.identifier)]
if checkDC_ID:
out += [Ontology(checkDC_ID[0], namespaces=self.namespaces)] # depends on [control=['if'], data=[]]
else:
vannprop = rdflib.URIRef('http://purl.org/vocab/vann/preferredNamespaceUri')
vannpref = rdflib.URIRef('http://purl.org/vocab/vann/preferredNamespacePrefix')
checkDC_ID = [x for x in self.rdfgraph.objects(candidate[0], vannprop)]
if checkDC_ID:
checkDC_prefix = [x for x in self.rdfgraph.objects(candidate[0], vannpref)]
if checkDC_prefix:
out += [Ontology(checkDC_ID[0], namespaces=self.namespaces, prefPrefix=checkDC_prefix[0])] # depends on [control=['if'], data=[]]
else:
out += [Ontology(checkDC_ID[0], namespaces=self.namespaces)] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
else:
out += [Ontology(candidate[0], namespaces=self.namespaces)] # depends on [control=['for'], data=['candidate']] # depends on [control=['if'], data=[]]
else:
pass
# printDebug("No owl:Ontologies found")
#finally... add all annotations/triples
self.ontologies = out
for onto in self.ontologies:
onto.triples = self.queryHelper.entityTriples(onto.uri)
onto._buildGraph() # depends on [control=['for'], data=['onto']] |
def sg_transpose(tensor, opt):
r"""Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`.
"""
assert opt.perm is not None, 'perm is mandatory'
return tf.transpose(tensor, opt.perm, name=opt.name) | def function[sg_transpose, parameter[tensor, opt]]:
constant[Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`.
]
assert[compare[name[opt].perm is_not constant[None]]]
return[call[name[tf].transpose, parameter[name[tensor], name[opt].perm]]] | keyword[def] identifier[sg_transpose] ( identifier[tensor] , identifier[opt] ):
literal[string]
keyword[assert] identifier[opt] . identifier[perm] keyword[is] keyword[not] keyword[None] , literal[string]
keyword[return] identifier[tf] . identifier[transpose] ( identifier[tensor] , identifier[opt] . identifier[perm] , identifier[name] = identifier[opt] . identifier[name] ) | def sg_transpose(tensor, opt):
"""Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`.
"""
assert opt.perm is not None, 'perm is mandatory'
return tf.transpose(tensor, opt.perm, name=opt.name) |
def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.__lookup_prefix(prefix)
except PrefixNotFoundError:
return None
else:
return ni.uri | def function[namespace_for_prefix, parameter[self, prefix]]:
constant[Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
]
<ast.Try object at 0x7da2054a7610> | keyword[def] identifier[namespace_for_prefix] ( identifier[self] , identifier[prefix] ):
literal[string]
keyword[try] :
identifier[ni] = identifier[self] . identifier[__lookup_prefix] ( identifier[prefix] )
keyword[except] identifier[PrefixNotFoundError] :
keyword[return] keyword[None]
keyword[else] :
keyword[return] identifier[ni] . identifier[uri] | def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.__lookup_prefix(prefix) # depends on [control=['try'], data=[]]
except PrefixNotFoundError:
return None # depends on [control=['except'], data=[]]
else:
return ni.uri |
def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]]
"""
import unicodedata
precision = kwargs.get('precision', None)
sep = kwargs.get('sep', '')
if len(args) == 1 and not isinstance(args[0], six.string_types):
val_list = args[0]
else:
val_list = args
val_list = [unicodedata.normalize('NFC', ensure_unicode(val))
for val in val_list]
all_lines = []
hpos = 0
# for each value in the list or args
for sx in range(len(val_list)):
# Ensure value is a string
val = val_list[sx]
str_ = None
if precision is not None:
# Hack in numpy precision
if util_type.HAVE_NUMPY:
try:
if isinstance(val, np.ndarray):
str_ = np.array_str(val, precision=precision,
suppress_small=True)
except ImportError:
pass
if str_ is None:
str_ = six.text_type(val_list[sx])
# continue with formating
lines = str_.split('\n')
line_diff = len(lines) - len(all_lines)
# Vertical padding
if line_diff > 0:
all_lines += [' ' * hpos] * line_diff
# Add strings
for lx, line in enumerate(lines):
all_lines[lx] += line
hpos = max(hpos, len(all_lines[lx]))
# Horizontal padding
for lx in range(len(all_lines)):
hpos_diff = hpos - len(all_lines[lx])
all_lines[lx] += ' ' * hpos_diff + sep
all_lines = [line.rstrip(' ') for line in all_lines]
ret = '\n'.join(all_lines)
return ret | def function[horiz_string, parameter[]]:
constant[
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]]
]
import module[unicodedata]
variable[precision] assign[=] call[name[kwargs].get, parameter[constant[precision], constant[None]]]
variable[sep] assign[=] call[name[kwargs].get, parameter[constant[sep], constant[]]]
if <ast.BoolOp object at 0x7da1b24b7af0> begin[:]
variable[val_list] assign[=] call[name[args]][constant[0]]
variable[val_list] assign[=] <ast.ListComp object at 0x7da1b24b7700>
variable[all_lines] assign[=] list[[]]
variable[hpos] assign[=] constant[0]
for taget[name[sx]] in starred[call[name[range], parameter[call[name[len], parameter[name[val_list]]]]]] begin[:]
variable[val] assign[=] call[name[val_list]][name[sx]]
variable[str_] assign[=] constant[None]
if compare[name[precision] is_not constant[None]] begin[:]
if name[util_type].HAVE_NUMPY begin[:]
<ast.Try object at 0x7da1b24b7c10>
if compare[name[str_] is constant[None]] begin[:]
variable[str_] assign[=] call[name[six].text_type, parameter[call[name[val_list]][name[sx]]]]
variable[lines] assign[=] call[name[str_].split, parameter[constant[
]]]
variable[line_diff] assign[=] binary_operation[call[name[len], parameter[name[lines]]] - call[name[len], parameter[name[all_lines]]]]
if compare[name[line_diff] greater[>] constant[0]] begin[:]
<ast.AugAssign object at 0x7da1b24c72b0>
for taget[tuple[[<ast.Name object at 0x7da1b24c4af0>, <ast.Name object at 0x7da1b24c4bb0>]]] in starred[call[name[enumerate], parameter[name[lines]]]] begin[:]
<ast.AugAssign object at 0x7da1b24c41f0>
variable[hpos] assign[=] call[name[max], parameter[name[hpos], call[name[len], parameter[call[name[all_lines]][name[lx]]]]]]
for taget[name[lx]] in starred[call[name[range], parameter[call[name[len], parameter[name[all_lines]]]]]] begin[:]
variable[hpos_diff] assign[=] binary_operation[name[hpos] - call[name[len], parameter[call[name[all_lines]][name[lx]]]]]
<ast.AugAssign object at 0x7da1b24c4df0>
variable[all_lines] assign[=] <ast.ListComp object at 0x7da1b24c4700>
variable[ret] assign[=] call[constant[
].join, parameter[name[all_lines]]]
return[name[ret]] | keyword[def] identifier[horiz_string] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[unicodedata]
identifier[precision] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
identifier[sep] = identifier[kwargs] . identifier[get] ( literal[string] , literal[string] )
keyword[if] identifier[len] ( identifier[args] )== literal[int] keyword[and] keyword[not] identifier[isinstance] ( identifier[args] [ literal[int] ], identifier[six] . identifier[string_types] ):
identifier[val_list] = identifier[args] [ literal[int] ]
keyword[else] :
identifier[val_list] = identifier[args]
identifier[val_list] =[ identifier[unicodedata] . identifier[normalize] ( literal[string] , identifier[ensure_unicode] ( identifier[val] ))
keyword[for] identifier[val] keyword[in] identifier[val_list] ]
identifier[all_lines] =[]
identifier[hpos] = literal[int]
keyword[for] identifier[sx] keyword[in] identifier[range] ( identifier[len] ( identifier[val_list] )):
identifier[val] = identifier[val_list] [ identifier[sx] ]
identifier[str_] = keyword[None]
keyword[if] identifier[precision] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[util_type] . identifier[HAVE_NUMPY] :
keyword[try] :
keyword[if] identifier[isinstance] ( identifier[val] , identifier[np] . identifier[ndarray] ):
identifier[str_] = identifier[np] . identifier[array_str] ( identifier[val] , identifier[precision] = identifier[precision] ,
identifier[suppress_small] = keyword[True] )
keyword[except] identifier[ImportError] :
keyword[pass]
keyword[if] identifier[str_] keyword[is] keyword[None] :
identifier[str_] = identifier[six] . identifier[text_type] ( identifier[val_list] [ identifier[sx] ])
identifier[lines] = identifier[str_] . identifier[split] ( literal[string] )
identifier[line_diff] = identifier[len] ( identifier[lines] )- identifier[len] ( identifier[all_lines] )
keyword[if] identifier[line_diff] > literal[int] :
identifier[all_lines] +=[ literal[string] * identifier[hpos] ]* identifier[line_diff]
keyword[for] identifier[lx] , identifier[line] keyword[in] identifier[enumerate] ( identifier[lines] ):
identifier[all_lines] [ identifier[lx] ]+= identifier[line]
identifier[hpos] = identifier[max] ( identifier[hpos] , identifier[len] ( identifier[all_lines] [ identifier[lx] ]))
keyword[for] identifier[lx] keyword[in] identifier[range] ( identifier[len] ( identifier[all_lines] )):
identifier[hpos_diff] = identifier[hpos] - identifier[len] ( identifier[all_lines] [ identifier[lx] ])
identifier[all_lines] [ identifier[lx] ]+= literal[string] * identifier[hpos_diff] + identifier[sep]
identifier[all_lines] =[ identifier[line] . identifier[rstrip] ( literal[string] ) keyword[for] identifier[line] keyword[in] identifier[all_lines] ]
identifier[ret] = literal[string] . identifier[join] ( identifier[all_lines] )
keyword[return] identifier[ret] | def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]]
"""
import unicodedata
precision = kwargs.get('precision', None)
sep = kwargs.get('sep', '')
if len(args) == 1 and (not isinstance(args[0], six.string_types)):
val_list = args[0] # depends on [control=['if'], data=[]]
else:
val_list = args
val_list = [unicodedata.normalize('NFC', ensure_unicode(val)) for val in val_list]
all_lines = []
hpos = 0
# for each value in the list or args
for sx in range(len(val_list)):
# Ensure value is a string
val = val_list[sx]
str_ = None
if precision is not None:
# Hack in numpy precision
if util_type.HAVE_NUMPY:
try:
if isinstance(val, np.ndarray):
str_ = np.array_str(val, precision=precision, suppress_small=True) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
except ImportError:
pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['precision']]
if str_ is None:
str_ = six.text_type(val_list[sx]) # depends on [control=['if'], data=['str_']]
# continue with formating
lines = str_.split('\n')
line_diff = len(lines) - len(all_lines)
# Vertical padding
if line_diff > 0:
all_lines += [' ' * hpos] * line_diff # depends on [control=['if'], data=['line_diff']]
# Add strings
for (lx, line) in enumerate(lines):
all_lines[lx] += line
hpos = max(hpos, len(all_lines[lx])) # depends on [control=['for'], data=[]]
# Horizontal padding
for lx in range(len(all_lines)):
hpos_diff = hpos - len(all_lines[lx])
all_lines[lx] += ' ' * hpos_diff + sep # depends on [control=['for'], data=['lx']] # depends on [control=['for'], data=['sx']]
all_lines = [line.rstrip(' ') for line in all_lines]
ret = '\n'.join(all_lines)
return ret |
def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_words = not args.analogy_dont_exclude_question_words
for analogy_function in args.analogy_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy(
idx_to_vec=token_embedding.idx_to_vec,
exclude_question_words=exclude_question_words,
analogy_function=analogy_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridize:
evaluator.hybridize()
for (dataset_name, dataset_kwargs,
dataset) in iterate_analogy_datasets(args):
initial_length = len(dataset)
dataset_coded = [[
token_embedding.token_to_idx[d[0]],
token_embedding.token_to_idx[d[1]],
token_embedding.token_to_idx[d[2]],
token_embedding.token_to_idx[d[3]]
] for d in dataset if d[0] in token_embedding.token_to_idx
and d[1] in token_embedding.token_to_idx
and d[2] in token_embedding.token_to_idx
and d[3] in token_embedding.token_to_idx]
num_dropped = initial_length - len(dataset_coded)
dataset_coded_batched = mx.gluon.data.DataLoader(
dataset_coded, batch_size=args.eval_batch_size)
acc = mx.metric.Accuracy()
for batch in dataset_coded_batched:
batch = batch.as_in_context(ctx)
words1, words2, words3, words4 = (batch[:, 0], batch[:, 1],
batch[:, 2], batch[:, 3])
pred_idxs = evaluator(words1, words2, words3)
acc.update(pred_idxs[:, 0], words4.astype(np.float32))
logging.info('Accuracy on %s (%s quadruples) %s with %s:\t%s',
dataset.__class__.__name__, len(dataset_coded),
str(dataset_kwargs), analogy_function,
acc.get()[1])
result = dict(
task='analogy',
dataset_name=dataset_name,
dataset_kwargs=dataset_kwargs,
analogy_function=analogy_function,
accuracy=acc.get()[1],
num_dropped=num_dropped,
global_step=global_step,
)
log_analogy_result(logfile, result)
results.append(result)
return results | def function[evaluate_analogy, parameter[args, token_embedding, ctx, logfile, global_step]]:
constant[Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
]
variable[results] assign[=] list[[]]
variable[exclude_question_words] assign[=] <ast.UnaryOp object at 0x7da18eb55e40>
for taget[name[analogy_function]] in starred[name[args].analogy_functions] begin[:]
variable[evaluator] assign[=] call[name[nlp].embedding.evaluation.WordEmbeddingAnalogy, parameter[]]
call[name[evaluator].initialize, parameter[]]
if <ast.UnaryOp object at 0x7da18eb55ea0> begin[:]
call[name[evaluator].hybridize, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da18eb56770>, <ast.Name object at 0x7da18eb56620>, <ast.Name object at 0x7da18eb54610>]]] in starred[call[name[iterate_analogy_datasets], parameter[name[args]]]] begin[:]
variable[initial_length] assign[=] call[name[len], parameter[name[dataset]]]
variable[dataset_coded] assign[=] <ast.ListComp object at 0x7da18f7229e0>
variable[num_dropped] assign[=] binary_operation[name[initial_length] - call[name[len], parameter[name[dataset_coded]]]]
variable[dataset_coded_batched] assign[=] call[name[mx].gluon.data.DataLoader, parameter[name[dataset_coded]]]
variable[acc] assign[=] call[name[mx].metric.Accuracy, parameter[]]
for taget[name[batch]] in starred[name[dataset_coded_batched]] begin[:]
variable[batch] assign[=] call[name[batch].as_in_context, parameter[name[ctx]]]
<ast.Tuple object at 0x7da18f720130> assign[=] tuple[[<ast.Subscript object at 0x7da18f723f10>, <ast.Subscript object at 0x7da18f723310>, <ast.Subscript object at 0x7da18f722b30>, <ast.Subscript object at 0x7da18f720520>]]
variable[pred_idxs] assign[=] call[name[evaluator], parameter[name[words1], name[words2], name[words3]]]
call[name[acc].update, parameter[call[name[pred_idxs]][tuple[[<ast.Slice object at 0x7da18f722c50>, <ast.Constant object at 0x7da18f722b00>]]], call[name[words4].astype, parameter[name[np].float32]]]]
call[name[logging].info, parameter[constant[Accuracy on %s (%s quadruples) %s with %s: %s], name[dataset].__class__.__name__, call[name[len], parameter[name[dataset_coded]]], call[name[str], parameter[name[dataset_kwargs]]], name[analogy_function], call[call[name[acc].get, parameter[]]][constant[1]]]]
variable[result] assign[=] call[name[dict], parameter[]]
call[name[log_analogy_result], parameter[name[logfile], name[result]]]
call[name[results].append, parameter[name[result]]]
return[name[results]] | keyword[def] identifier[evaluate_analogy] ( identifier[args] , identifier[token_embedding] , identifier[ctx] , identifier[logfile] = keyword[None] , identifier[global_step] = literal[int] ):
literal[string]
identifier[results] =[]
identifier[exclude_question_words] = keyword[not] identifier[args] . identifier[analogy_dont_exclude_question_words]
keyword[for] identifier[analogy_function] keyword[in] identifier[args] . identifier[analogy_functions] :
identifier[evaluator] = identifier[nlp] . identifier[embedding] . identifier[evaluation] . identifier[WordEmbeddingAnalogy] (
identifier[idx_to_vec] = identifier[token_embedding] . identifier[idx_to_vec] ,
identifier[exclude_question_words] = identifier[exclude_question_words] ,
identifier[analogy_function] = identifier[analogy_function] )
identifier[evaluator] . identifier[initialize] ( identifier[ctx] = identifier[ctx] )
keyword[if] keyword[not] identifier[args] . identifier[no_hybridize] :
identifier[evaluator] . identifier[hybridize] ()
keyword[for] ( identifier[dataset_name] , identifier[dataset_kwargs] ,
identifier[dataset] ) keyword[in] identifier[iterate_analogy_datasets] ( identifier[args] ):
identifier[initial_length] = identifier[len] ( identifier[dataset] )
identifier[dataset_coded] =[[
identifier[token_embedding] . identifier[token_to_idx] [ identifier[d] [ literal[int] ]],
identifier[token_embedding] . identifier[token_to_idx] [ identifier[d] [ literal[int] ]],
identifier[token_embedding] . identifier[token_to_idx] [ identifier[d] [ literal[int] ]],
identifier[token_embedding] . identifier[token_to_idx] [ identifier[d] [ literal[int] ]]
] keyword[for] identifier[d] keyword[in] identifier[dataset] keyword[if] identifier[d] [ literal[int] ] keyword[in] identifier[token_embedding] . identifier[token_to_idx]
keyword[and] identifier[d] [ literal[int] ] keyword[in] identifier[token_embedding] . identifier[token_to_idx]
keyword[and] identifier[d] [ literal[int] ] keyword[in] identifier[token_embedding] . identifier[token_to_idx]
keyword[and] identifier[d] [ literal[int] ] keyword[in] identifier[token_embedding] . identifier[token_to_idx] ]
identifier[num_dropped] = identifier[initial_length] - identifier[len] ( identifier[dataset_coded] )
identifier[dataset_coded_batched] = identifier[mx] . identifier[gluon] . identifier[data] . identifier[DataLoader] (
identifier[dataset_coded] , identifier[batch_size] = identifier[args] . identifier[eval_batch_size] )
identifier[acc] = identifier[mx] . identifier[metric] . identifier[Accuracy] ()
keyword[for] identifier[batch] keyword[in] identifier[dataset_coded_batched] :
identifier[batch] = identifier[batch] . identifier[as_in_context] ( identifier[ctx] )
identifier[words1] , identifier[words2] , identifier[words3] , identifier[words4] =( identifier[batch] [:, literal[int] ], identifier[batch] [:, literal[int] ],
identifier[batch] [:, literal[int] ], identifier[batch] [:, literal[int] ])
identifier[pred_idxs] = identifier[evaluator] ( identifier[words1] , identifier[words2] , identifier[words3] )
identifier[acc] . identifier[update] ( identifier[pred_idxs] [:, literal[int] ], identifier[words4] . identifier[astype] ( identifier[np] . identifier[float32] ))
identifier[logging] . identifier[info] ( literal[string] ,
identifier[dataset] . identifier[__class__] . identifier[__name__] , identifier[len] ( identifier[dataset_coded] ),
identifier[str] ( identifier[dataset_kwargs] ), identifier[analogy_function] ,
identifier[acc] . identifier[get] ()[ literal[int] ])
identifier[result] = identifier[dict] (
identifier[task] = literal[string] ,
identifier[dataset_name] = identifier[dataset_name] ,
identifier[dataset_kwargs] = identifier[dataset_kwargs] ,
identifier[analogy_function] = identifier[analogy_function] ,
identifier[accuracy] = identifier[acc] . identifier[get] ()[ literal[int] ],
identifier[num_dropped] = identifier[num_dropped] ,
identifier[global_step] = identifier[global_step] ,
)
identifier[log_analogy_result] ( identifier[logfile] , identifier[result] )
identifier[results] . identifier[append] ( identifier[result] )
keyword[return] identifier[results] | def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_words = not args.analogy_dont_exclude_question_words
for analogy_function in args.analogy_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy(idx_to_vec=token_embedding.idx_to_vec, exclude_question_words=exclude_question_words, analogy_function=analogy_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridize:
evaluator.hybridize() # depends on [control=['if'], data=[]]
for (dataset_name, dataset_kwargs, dataset) in iterate_analogy_datasets(args):
initial_length = len(dataset)
dataset_coded = [[token_embedding.token_to_idx[d[0]], token_embedding.token_to_idx[d[1]], token_embedding.token_to_idx[d[2]], token_embedding.token_to_idx[d[3]]] for d in dataset if d[0] in token_embedding.token_to_idx and d[1] in token_embedding.token_to_idx and (d[2] in token_embedding.token_to_idx) and (d[3] in token_embedding.token_to_idx)]
num_dropped = initial_length - len(dataset_coded)
dataset_coded_batched = mx.gluon.data.DataLoader(dataset_coded, batch_size=args.eval_batch_size)
acc = mx.metric.Accuracy()
for batch in dataset_coded_batched:
batch = batch.as_in_context(ctx)
(words1, words2, words3, words4) = (batch[:, 0], batch[:, 1], batch[:, 2], batch[:, 3])
pred_idxs = evaluator(words1, words2, words3)
acc.update(pred_idxs[:, 0], words4.astype(np.float32)) # depends on [control=['for'], data=['batch']]
logging.info('Accuracy on %s (%s quadruples) %s with %s:\t%s', dataset.__class__.__name__, len(dataset_coded), str(dataset_kwargs), analogy_function, acc.get()[1])
result = dict(task='analogy', dataset_name=dataset_name, dataset_kwargs=dataset_kwargs, analogy_function=analogy_function, accuracy=acc.get()[1], num_dropped=num_dropped, global_step=global_step)
log_analogy_result(logfile, result)
results.append(result) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['analogy_function']]
return results |
def text_result(text: str,
extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
filename: str = None) -> WSGI_TUPLE_TYPE:
"""
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
"""
extraheaders = extraheaders or []
if filename:
extraheaders.append(
('content-disposition', 'inline; filename="{}"'.format(filename))
)
contenttype = 'text/plain; charset=utf-8'
if filename:
contenttype += '; filename="{}"'.format(filename)
return contenttype, extraheaders, text.encode("utf-8") | def function[text_result, parameter[text, extraheaders, filename]]:
constant[
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
]
variable[extraheaders] assign[=] <ast.BoolOp object at 0x7da18c4cfa60>
if name[filename] begin[:]
call[name[extraheaders].append, parameter[tuple[[<ast.Constant object at 0x7da2041db520>, <ast.Call object at 0x7da2041d8790>]]]]
variable[contenttype] assign[=] constant[text/plain; charset=utf-8]
if name[filename] begin[:]
<ast.AugAssign object at 0x7da2041d9c00>
return[tuple[[<ast.Name object at 0x7da20c7c8250>, <ast.Name object at 0x7da20c7c8d60>, <ast.Call object at 0x7da20c7cb130>]]] | keyword[def] identifier[text_result] ( identifier[text] : identifier[str] ,
identifier[extraheaders] : identifier[TYPE_WSGI_RESPONSE_HEADERS] = keyword[None] ,
identifier[filename] : identifier[str] = keyword[None] )-> identifier[WSGI_TUPLE_TYPE] :
literal[string]
identifier[extraheaders] = identifier[extraheaders] keyword[or] []
keyword[if] identifier[filename] :
identifier[extraheaders] . identifier[append] (
( literal[string] , literal[string] . identifier[format] ( identifier[filename] ))
)
identifier[contenttype] = literal[string]
keyword[if] identifier[filename] :
identifier[contenttype] += literal[string] . identifier[format] ( identifier[filename] )
keyword[return] identifier[contenttype] , identifier[extraheaders] , identifier[text] . identifier[encode] ( literal[string] ) | def text_result(text: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS=None, filename: str=None) -> WSGI_TUPLE_TYPE:
"""
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
"""
extraheaders = extraheaders or []
if filename:
extraheaders.append(('content-disposition', 'inline; filename="{}"'.format(filename))) # depends on [control=['if'], data=[]]
contenttype = 'text/plain; charset=utf-8'
if filename:
contenttype += '; filename="{}"'.format(filename) # depends on [control=['if'], data=[]]
return (contenttype, extraheaders, text.encode('utf-8')) |
def discretizer(reader,
transform=None,
cluster=None,
run=True,
stride=1,
chunksize=None):
r""" Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (mandatory)
2. a transformer stage (optional)
3. a clustering stage (mandatory)
This function is identical to calling :func:`pipeline` with the three
stages, it is only meant as a guidance for the (probably) most common
usage cases of a pipeline.
Parameters
----------
reader : instance of :class:`pyemma.coordinates.data.reader.ChunkedReader`
The reader instance provides access to the data. If you are working
with MD data, you most likely want to use a FeatureReader.
transform : instance of :class: `pyemma.coordinates.Transformer`
an optional transform like PCA/TICA etc.
cluster : instance of :class: `pyemma.coordinates.AbstractClustering`
clustering Transformer (optional) a cluster algorithm to assign
transformed data to discrete states.
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline
to parametrize its stages. Note that this could cause the
parametrization step to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales,
it is often sufficient to parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : a :class:`Pipeline <pyemma.coordinates.pipelines.Discretizer>` object
A pipeline object that is able to streamline data analysis of large
amounts of input data with limited memory in streaming mode.
Examples
--------
Construct a discretizer pipeline processing all data
with a PCA transformation and cluster the principal components
with uniform time clustering:
>>> from pyemma.coordinates import source, pca, cluster_regspace, discretizer
>>> from pyemma.datasets import get_bpti_test_data
>>> from pyemma.util.contexts import settings
>>> reader = source(get_bpti_test_data()['trajs'], top=get_bpti_test_data()['top'])
>>> transform = pca(dim=2)
>>> cluster = cluster_regspace(dmin=0.1)
Create the discretizer, access the the discrete trajectories and save them to files:
>>> with settings(show_progress_bars=False):
... disc = discretizer(reader, transform, cluster)
... disc.dtrajs # doctest: +ELLIPSIS
[array([...
This will store the discrete trajectory to "traj01.dtraj":
>>> from pyemma.util.files import TemporaryDirectory
>>> import os
>>> with TemporaryDirectory('dtrajs') as tmpdir:
... disc.save_dtrajs(output_dir=tmpdir)
... sorted(os.listdir(tmpdir))
['bpti_001-033.dtraj', 'bpti_034-066.dtraj', 'bpti_067-100.dtraj']
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
"""
from pyemma.coordinates.clustering.kmeans import KmeansClustering
from pyemma.coordinates.pipelines import Discretizer
if cluster is None:
_logger.warning('You did not specify a cluster algorithm.'
' Defaulting to kmeans(k=100)')
cluster = KmeansClustering(n_clusters=100)
disc = Discretizer(reader, transform, cluster, param_stride=stride, chunksize=chunksize)
if run:
disc.parametrize()
return disc | def function[discretizer, parameter[reader, transform, cluster, run, stride, chunksize]]:
constant[ Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (mandatory)
2. a transformer stage (optional)
3. a clustering stage (mandatory)
This function is identical to calling :func:`pipeline` with the three
stages, it is only meant as a guidance for the (probably) most common
usage cases of a pipeline.
Parameters
----------
reader : instance of :class:`pyemma.coordinates.data.reader.ChunkedReader`
The reader instance provides access to the data. If you are working
with MD data, you most likely want to use a FeatureReader.
transform : instance of :class: `pyemma.coordinates.Transformer`
an optional transform like PCA/TICA etc.
cluster : instance of :class: `pyemma.coordinates.AbstractClustering`
clustering Transformer (optional) a cluster algorithm to assign
transformed data to discrete states.
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline
to parametrize its stages. Note that this could cause the
parametrization step to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales,
it is often sufficient to parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : a :class:`Pipeline <pyemma.coordinates.pipelines.Discretizer>` object
A pipeline object that is able to streamline data analysis of large
amounts of input data with limited memory in streaming mode.
Examples
--------
Construct a discretizer pipeline processing all data
with a PCA transformation and cluster the principal components
with uniform time clustering:
>>> from pyemma.coordinates import source, pca, cluster_regspace, discretizer
>>> from pyemma.datasets import get_bpti_test_data
>>> from pyemma.util.contexts import settings
>>> reader = source(get_bpti_test_data()['trajs'], top=get_bpti_test_data()['top'])
>>> transform = pca(dim=2)
>>> cluster = cluster_regspace(dmin=0.1)
Create the discretizer, access the the discrete trajectories and save them to files:
>>> with settings(show_progress_bars=False):
... disc = discretizer(reader, transform, cluster)
... disc.dtrajs # doctest: +ELLIPSIS
[array([...
This will store the discrete trajectory to "traj01.dtraj":
>>> from pyemma.util.files import TemporaryDirectory
>>> import os
>>> with TemporaryDirectory('dtrajs') as tmpdir:
... disc.save_dtrajs(output_dir=tmpdir)
... sorted(os.listdir(tmpdir))
['bpti_001-033.dtraj', 'bpti_034-066.dtraj', 'bpti_067-100.dtraj']
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
]
from relative_module[pyemma.coordinates.clustering.kmeans] import module[KmeansClustering]
from relative_module[pyemma.coordinates.pipelines] import module[Discretizer]
if compare[name[cluster] is constant[None]] begin[:]
call[name[_logger].warning, parameter[constant[You did not specify a cluster algorithm. Defaulting to kmeans(k=100)]]]
variable[cluster] assign[=] call[name[KmeansClustering], parameter[]]
variable[disc] assign[=] call[name[Discretizer], parameter[name[reader], name[transform], name[cluster]]]
if name[run] begin[:]
call[name[disc].parametrize, parameter[]]
return[name[disc]] | keyword[def] identifier[discretizer] ( identifier[reader] ,
identifier[transform] = keyword[None] ,
identifier[cluster] = keyword[None] ,
identifier[run] = keyword[True] ,
identifier[stride] = literal[int] ,
identifier[chunksize] = keyword[None] ):
literal[string]
keyword[from] identifier[pyemma] . identifier[coordinates] . identifier[clustering] . identifier[kmeans] keyword[import] identifier[KmeansClustering]
keyword[from] identifier[pyemma] . identifier[coordinates] . identifier[pipelines] keyword[import] identifier[Discretizer]
keyword[if] identifier[cluster] keyword[is] keyword[None] :
identifier[_logger] . identifier[warning] ( literal[string]
literal[string] )
identifier[cluster] = identifier[KmeansClustering] ( identifier[n_clusters] = literal[int] )
identifier[disc] = identifier[Discretizer] ( identifier[reader] , identifier[transform] , identifier[cluster] , identifier[param_stride] = identifier[stride] , identifier[chunksize] = identifier[chunksize] )
keyword[if] identifier[run] :
identifier[disc] . identifier[parametrize] ()
keyword[return] identifier[disc] | def discretizer(reader, transform=None, cluster=None, run=True, stride=1, chunksize=None):
""" Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (mandatory)
2. a transformer stage (optional)
3. a clustering stage (mandatory)
This function is identical to calling :func:`pipeline` with the three
stages, it is only meant as a guidance for the (probably) most common
usage cases of a pipeline.
Parameters
----------
reader : instance of :class:`pyemma.coordinates.data.reader.ChunkedReader`
The reader instance provides access to the data. If you are working
with MD data, you most likely want to use a FeatureReader.
transform : instance of :class: `pyemma.coordinates.Transformer`
an optional transform like PCA/TICA etc.
cluster : instance of :class: `pyemma.coordinates.AbstractClustering`
clustering Transformer (optional) a cluster algorithm to assign
transformed data to discrete states.
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline
to parametrize its stages. Note that this could cause the
parametrization step to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales,
it is often sufficient to parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : a :class:`Pipeline <pyemma.coordinates.pipelines.Discretizer>` object
A pipeline object that is able to streamline data analysis of large
amounts of input data with limited memory in streaming mode.
Examples
--------
Construct a discretizer pipeline processing all data
with a PCA transformation and cluster the principal components
with uniform time clustering:
>>> from pyemma.coordinates import source, pca, cluster_regspace, discretizer
>>> from pyemma.datasets import get_bpti_test_data
>>> from pyemma.util.contexts import settings
>>> reader = source(get_bpti_test_data()['trajs'], top=get_bpti_test_data()['top'])
>>> transform = pca(dim=2)
>>> cluster = cluster_regspace(dmin=0.1)
Create the discretizer, access the the discrete trajectories and save them to files:
>>> with settings(show_progress_bars=False):
... disc = discretizer(reader, transform, cluster)
... disc.dtrajs # doctest: +ELLIPSIS
[array([...
This will store the discrete trajectory to "traj01.dtraj":
>>> from pyemma.util.files import TemporaryDirectory
>>> import os
>>> with TemporaryDirectory('dtrajs') as tmpdir:
... disc.save_dtrajs(output_dir=tmpdir)
... sorted(os.listdir(tmpdir))
['bpti_001-033.dtraj', 'bpti_034-066.dtraj', 'bpti_067-100.dtraj']
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
"""
from pyemma.coordinates.clustering.kmeans import KmeansClustering
from pyemma.coordinates.pipelines import Discretizer
if cluster is None:
_logger.warning('You did not specify a cluster algorithm. Defaulting to kmeans(k=100)')
cluster = KmeansClustering(n_clusters=100) # depends on [control=['if'], data=['cluster']]
disc = Discretizer(reader, transform, cluster, param_stride=stride, chunksize=chunksize)
if run:
disc.parametrize() # depends on [control=['if'], data=[]]
return disc |
def insert(self, fields, values):
'''
insert new db entry
:param fields: list of fields to insert
:param values: list of values to insert
:return: row id of the new row
'''
if fields:
_fields = ' (%s) ' % ','.join(fields)
else:
_fields = ''
_values = ','.join('?' * len(values))
query = '''
INSERT INTO %s %s VALUES (%s)
''' % (self._name, _fields, _values)
self._cursor.execute(query, tuple(values))
self._connection.commit()
return self._cursor.lastrowid | def function[insert, parameter[self, fields, values]]:
constant[
insert new db entry
:param fields: list of fields to insert
:param values: list of values to insert
:return: row id of the new row
]
if name[fields] begin[:]
variable[_fields] assign[=] binary_operation[constant[ (%s) ] <ast.Mod object at 0x7da2590d6920> call[constant[,].join, parameter[name[fields]]]]
variable[_values] assign[=] call[constant[,].join, parameter[binary_operation[constant[?] * call[name[len], parameter[name[values]]]]]]
variable[query] assign[=] binary_operation[constant[
INSERT INTO %s %s VALUES (%s)
] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da20e956e00>, <ast.Name object at 0x7da20e955a80>, <ast.Name object at 0x7da20e9558a0>]]]
call[name[self]._cursor.execute, parameter[name[query], call[name[tuple], parameter[name[values]]]]]
call[name[self]._connection.commit, parameter[]]
return[name[self]._cursor.lastrowid] | keyword[def] identifier[insert] ( identifier[self] , identifier[fields] , identifier[values] ):
literal[string]
keyword[if] identifier[fields] :
identifier[_fields] = literal[string] % literal[string] . identifier[join] ( identifier[fields] )
keyword[else] :
identifier[_fields] = literal[string]
identifier[_values] = literal[string] . identifier[join] ( literal[string] * identifier[len] ( identifier[values] ))
identifier[query] = literal[string] %( identifier[self] . identifier[_name] , identifier[_fields] , identifier[_values] )
identifier[self] . identifier[_cursor] . identifier[execute] ( identifier[query] , identifier[tuple] ( identifier[values] ))
identifier[self] . identifier[_connection] . identifier[commit] ()
keyword[return] identifier[self] . identifier[_cursor] . identifier[lastrowid] | def insert(self, fields, values):
"""
insert new db entry
:param fields: list of fields to insert
:param values: list of values to insert
:return: row id of the new row
"""
if fields:
_fields = ' (%s) ' % ','.join(fields) # depends on [control=['if'], data=[]]
else:
_fields = ''
_values = ','.join('?' * len(values))
query = '\n INSERT INTO %s %s VALUES (%s)\n ' % (self._name, _fields, _values)
self._cursor.execute(query, tuple(values))
self._connection.commit()
return self._cursor.lastrowid |
def register_manifest(app, filename='manifest.json'):
'''Register an assets json manifest'''
if current_app.config.get('TESTING'):
return # Do not spend time here when testing
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.format(**locals())
raise ValueError(msg)
manifest = _manifests.get(app, {})
manifest.update(load_manifest(app, filename))
_manifests[app] = manifest | def function[register_manifest, parameter[app, filename]]:
constant[Register an assets json manifest]
if call[name[current_app].config.get, parameter[constant[TESTING]]] begin[:]
return[None]
if <ast.UnaryOp object at 0x7da1b11919c0> begin[:]
variable[msg] assign[=] call[constant[{filename} not found for {app}].format, parameter[]]
<ast.Raise object at 0x7da1b1191060>
variable[manifest] assign[=] call[name[_manifests].get, parameter[name[app], dictionary[[], []]]]
call[name[manifest].update, parameter[call[name[load_manifest], parameter[name[app], name[filename]]]]]
call[name[_manifests]][name[app]] assign[=] name[manifest] | keyword[def] identifier[register_manifest] ( identifier[app] , identifier[filename] = literal[string] ):
literal[string]
keyword[if] identifier[current_app] . identifier[config] . identifier[get] ( literal[string] ):
keyword[return]
keyword[if] keyword[not] identifier[has_manifest] ( identifier[app] , identifier[filename] ):
identifier[msg] = literal[string] . identifier[format] (** identifier[locals] ())
keyword[raise] identifier[ValueError] ( identifier[msg] )
identifier[manifest] = identifier[_manifests] . identifier[get] ( identifier[app] ,{})
identifier[manifest] . identifier[update] ( identifier[load_manifest] ( identifier[app] , identifier[filename] ))
identifier[_manifests] [ identifier[app] ]= identifier[manifest] | def register_manifest(app, filename='manifest.json'):
"""Register an assets json manifest"""
if current_app.config.get('TESTING'):
return # Do not spend time here when testing # depends on [control=['if'], data=[]]
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.format(**locals())
raise ValueError(msg) # depends on [control=['if'], data=[]]
manifest = _manifests.get(app, {})
manifest.update(load_manifest(app, filename))
_manifests[app] = manifest |
def _ensure_file_path(self):
"""
Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions.
"""
storage_root = os.path.dirname(self.file_path)
needs_storage_root = storage_root and not os.path.isdir(storage_root)
if needs_storage_root: # pragma: no cover
os.makedirs(storage_root)
if not os.path.isfile(self.file_path):
# create the file without group/world permissions
with open(self.file_path, 'w'):
pass
user_read_write = 0o600
os.chmod(self.file_path, user_read_write) | def function[_ensure_file_path, parameter[self]]:
constant[
Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions.
]
variable[storage_root] assign[=] call[name[os].path.dirname, parameter[name[self].file_path]]
variable[needs_storage_root] assign[=] <ast.BoolOp object at 0x7da1b0facf70>
if name[needs_storage_root] begin[:]
call[name[os].makedirs, parameter[name[storage_root]]]
if <ast.UnaryOp object at 0x7da1b0fadd20> begin[:]
with call[name[open], parameter[name[self].file_path, constant[w]]] begin[:]
pass
variable[user_read_write] assign[=] constant[384]
call[name[os].chmod, parameter[name[self].file_path, name[user_read_write]]] | keyword[def] identifier[_ensure_file_path] ( identifier[self] ):
literal[string]
identifier[storage_root] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[self] . identifier[file_path] )
identifier[needs_storage_root] = identifier[storage_root] keyword[and] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[storage_root] )
keyword[if] identifier[needs_storage_root] :
identifier[os] . identifier[makedirs] ( identifier[storage_root] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[self] . identifier[file_path] ):
keyword[with] identifier[open] ( identifier[self] . identifier[file_path] , literal[string] ):
keyword[pass]
identifier[user_read_write] = literal[int]
identifier[os] . identifier[chmod] ( identifier[self] . identifier[file_path] , identifier[user_read_write] ) | def _ensure_file_path(self):
"""
Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions.
"""
storage_root = os.path.dirname(self.file_path)
needs_storage_root = storage_root and (not os.path.isdir(storage_root))
if needs_storage_root: # pragma: no cover
os.makedirs(storage_root) # depends on [control=['if'], data=[]]
if not os.path.isfile(self.file_path):
# create the file without group/world permissions
with open(self.file_path, 'w'):
pass # depends on [control=['with'], data=[]]
user_read_write = 384
os.chmod(self.file_path, user_read_write) # depends on [control=['if'], data=[]] |
def __iter_read_spectrum_meta(self):
"""
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty.
Supported accession values for the number formats: "MS:1000521", "MS:1000523", "IMS:1000141" or
"IMS:1000142". The string values are "32-bit float", "64-bit float", "32-bit integer", "64-bit integer".
"""
mz_group = int_group = None
slist = None
elem_iterator = self.iterparse(self.filename, events=("start", "end"))
if sys.version_info > (3,):
_, self.root = next(elem_iterator)
else:
_, self.root = elem_iterator.next()
for event, elem in elem_iterator:
if elem.tag == self.sl + "spectrumList" and event == "start":
slist = elem
elif elem.tag == self.sl + "spectrum" and event == "end":
self.__process_spectrum(elem)
slist.remove(elem)
elif elem.tag == self.sl + "referenceableParamGroup" and event == "end":
for param in elem:
if param.attrib["name"] == "m/z array":
self.mzGroupId = elem.attrib['id']
mz_group = elem
elif param.attrib["name"] == "intensity array":
self.intGroupId = elem.attrib['id']
int_group = elem
self.__assign_precision(int_group, mz_group)
self.__fix_offsets() | def function[__iter_read_spectrum_meta, parameter[self]]:
constant[
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty.
Supported accession values for the number formats: "MS:1000521", "MS:1000523", "IMS:1000141" or
"IMS:1000142". The string values are "32-bit float", "64-bit float", "32-bit integer", "64-bit integer".
]
variable[mz_group] assign[=] constant[None]
variable[slist] assign[=] constant[None]
variable[elem_iterator] assign[=] call[name[self].iterparse, parameter[name[self].filename]]
if compare[name[sys].version_info greater[>] tuple[[<ast.Constant object at 0x7da1b050d360>]]] begin[:]
<ast.Tuple object at 0x7da1b050dc30> assign[=] call[name[next], parameter[name[elem_iterator]]]
for taget[tuple[[<ast.Name object at 0x7da1b050fcd0>, <ast.Name object at 0x7da1b050d6f0>]]] in starred[name[elem_iterator]] begin[:]
if <ast.BoolOp object at 0x7da1b050c700> begin[:]
variable[slist] assign[=] name[elem]
call[name[self].__assign_precision, parameter[name[int_group], name[mz_group]]]
call[name[self].__fix_offsets, parameter[]] | keyword[def] identifier[__iter_read_spectrum_meta] ( identifier[self] ):
literal[string]
identifier[mz_group] = identifier[int_group] = keyword[None]
identifier[slist] = keyword[None]
identifier[elem_iterator] = identifier[self] . identifier[iterparse] ( identifier[self] . identifier[filename] , identifier[events] =( literal[string] , literal[string] ))
keyword[if] identifier[sys] . identifier[version_info] >( literal[int] ,):
identifier[_] , identifier[self] . identifier[root] = identifier[next] ( identifier[elem_iterator] )
keyword[else] :
identifier[_] , identifier[self] . identifier[root] = identifier[elem_iterator] . identifier[next] ()
keyword[for] identifier[event] , identifier[elem] keyword[in] identifier[elem_iterator] :
keyword[if] identifier[elem] . identifier[tag] == identifier[self] . identifier[sl] + literal[string] keyword[and] identifier[event] == literal[string] :
identifier[slist] = identifier[elem]
keyword[elif] identifier[elem] . identifier[tag] == identifier[self] . identifier[sl] + literal[string] keyword[and] identifier[event] == literal[string] :
identifier[self] . identifier[__process_spectrum] ( identifier[elem] )
identifier[slist] . identifier[remove] ( identifier[elem] )
keyword[elif] identifier[elem] . identifier[tag] == identifier[self] . identifier[sl] + literal[string] keyword[and] identifier[event] == literal[string] :
keyword[for] identifier[param] keyword[in] identifier[elem] :
keyword[if] identifier[param] . identifier[attrib] [ literal[string] ]== literal[string] :
identifier[self] . identifier[mzGroupId] = identifier[elem] . identifier[attrib] [ literal[string] ]
identifier[mz_group] = identifier[elem]
keyword[elif] identifier[param] . identifier[attrib] [ literal[string] ]== literal[string] :
identifier[self] . identifier[intGroupId] = identifier[elem] . identifier[attrib] [ literal[string] ]
identifier[int_group] = identifier[elem]
identifier[self] . identifier[__assign_precision] ( identifier[int_group] , identifier[mz_group] )
identifier[self] . identifier[__fix_offsets] () | def __iter_read_spectrum_meta(self):
"""
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty.
Supported accession values for the number formats: "MS:1000521", "MS:1000523", "IMS:1000141" or
"IMS:1000142". The string values are "32-bit float", "64-bit float", "32-bit integer", "64-bit integer".
"""
mz_group = int_group = None
slist = None
elem_iterator = self.iterparse(self.filename, events=('start', 'end'))
if sys.version_info > (3,):
(_, self.root) = next(elem_iterator) # depends on [control=['if'], data=[]]
else:
(_, self.root) = elem_iterator.next()
for (event, elem) in elem_iterator:
if elem.tag == self.sl + 'spectrumList' and event == 'start':
slist = elem # depends on [control=['if'], data=[]]
elif elem.tag == self.sl + 'spectrum' and event == 'end':
self.__process_spectrum(elem)
slist.remove(elem) # depends on [control=['if'], data=[]]
elif elem.tag == self.sl + 'referenceableParamGroup' and event == 'end':
for param in elem:
if param.attrib['name'] == 'm/z array':
self.mzGroupId = elem.attrib['id']
mz_group = elem # depends on [control=['if'], data=[]]
elif param.attrib['name'] == 'intensity array':
self.intGroupId = elem.attrib['id']
int_group = elem # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['param']] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
self.__assign_precision(int_group, mz_group)
self.__fix_offsets() |
def contains_c_extension(module: ModuleType,
import_all_submodules: bool = True,
include_external_imports: bool = False,
seen: List[ModuleType] = None) -> bool:
"""
Extends :func:`is_c_extension` by asking: is this module, or any of its
submodules, a C extension?
Args:
module: Previously imported module object to be tested.
import_all_submodules: explicitly import all submodules of this module?
include_external_imports: check modules in other packages that this
module imports?
seen: used internally for recursion (to deal with recursive modules);
should be ``None`` when called by users
Returns:
bool: ``True`` only if this module or one of its submodules is a C
extension.
Examples:
.. code-block:: python
import logging
from cardinal_pythonlib.modules import contains_c_extension
from cardinal_pythonlib.logs import main_only_quicksetup_rootlogger
import _elementtree as et
import os
import arrow
import alembic
import django
import numpy
import numpy.core.multiarray as numpy_multiarray
log = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG) # be verbose
main_only_quicksetup_rootlogger(level=logging.DEBUG)
contains_c_extension(os) # False
contains_c_extension(et) # False
contains_c_extension(numpy) # True -- different from is_c_extension()
contains_c_extension(numpy_multiarray) # True
contains_c_extension(arrow) # False
contains_c_extension(alembic) # False
contains_c_extension(alembic, include_external_imports=True) # True
# ... this example shows that Alembic imports hashlib, which can import
# _hashlib, which is a C extension; however, that doesn't stop us (for
# example) installing Alembic on a machine with no C compiler
contains_c_extension(django)
""" # noqa
assert inspect.ismodule(module), '"{}" not a module.'.format(module)
if seen is None: # only true for the top-level call
seen = [] # type: List[ModuleType]
if module in seen: # modules can "contain" themselves
# already inspected; avoid infinite loops
return False
seen.append(module)
# Check the thing we were asked about
is_c_ext = is_c_extension(module)
log.info("Is module {!r} a C extension? {}", module, is_c_ext)
if is_c_ext:
return True
if is_builtin_module(module):
# built-in, therefore we stop searching it
return False
# Now check any children, in a couple of ways
top_level_module = seen[0]
top_path = os.path.dirname(top_level_module.__file__)
# Recurse using dir(). This picks up modules that are automatically
# imported by our top-level model. But it won't pick up all submodules;
# try e.g. for django.
for candidate_name in dir(module):
candidate = getattr(module, candidate_name)
# noinspection PyBroadException
try:
if not inspect.ismodule(candidate):
# not a module
continue
except Exception:
# e.g. a Django module that won't import until we configure its
# settings
log.error("Failed to test ismodule() status of {!r}", candidate)
continue
if is_builtin_module(candidate):
# built-in, therefore we stop searching it
continue
candidate_fname = getattr(candidate, "__file__")
if not include_external_imports:
if os.path.commonpath([top_path, candidate_fname]) != top_path:
log.debug("Skipping, not within the top-level module's "
"directory: {!r}", candidate)
continue
# Recurse:
if contains_c_extension(
module=candidate,
import_all_submodules=False, # only done at the top level, below # noqa
include_external_imports=include_external_imports,
seen=seen):
return True
if import_all_submodules:
if not is_module_a_package(module):
log.debug("Top-level module is not a package: {!r}", module)
return False
# Otherwise, for things like Django, we need to recurse in a different
# way to scan everything.
# See https://stackoverflow.com/questions/3365740/how-to-import-all-submodules. # noqa
log.debug("Walking path: {!r}", top_path)
# noinspection PyBroadException
try:
for loader, module_name, is_pkg in pkgutil.walk_packages([top_path]): # noqa
if not is_pkg:
log.debug("Skipping, not a package: {!r}", module_name)
continue
log.debug("Manually importing: {!r}", module_name)
# noinspection PyBroadException
try:
candidate = loader.find_module(module_name)\
.load_module(module_name) # noqa
except Exception:
# e.g. Alembic "autogenerate" gives: "ValueError: attempted
# relative import beyond top-level package"; or Django
# "django.core.exceptions.ImproperlyConfigured"
log.error("Package failed to import: {!r}", module_name)
continue
if contains_c_extension(
module=candidate,
import_all_submodules=False, # only done at the top level # noqa
include_external_imports=include_external_imports,
seen=seen):
return True
except Exception:
log.error("Unable to walk packages further; no C extensions "
"detected so far!")
raise
return False | def function[contains_c_extension, parameter[module, import_all_submodules, include_external_imports, seen]]:
constant[
Extends :func:`is_c_extension` by asking: is this module, or any of its
submodules, a C extension?
Args:
module: Previously imported module object to be tested.
import_all_submodules: explicitly import all submodules of this module?
include_external_imports: check modules in other packages that this
module imports?
seen: used internally for recursion (to deal with recursive modules);
should be ``None`` when called by users
Returns:
bool: ``True`` only if this module or one of its submodules is a C
extension.
Examples:
.. code-block:: python
import logging
from cardinal_pythonlib.modules import contains_c_extension
from cardinal_pythonlib.logs import main_only_quicksetup_rootlogger
import _elementtree as et
import os
import arrow
import alembic
import django
import numpy
import numpy.core.multiarray as numpy_multiarray
log = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG) # be verbose
main_only_quicksetup_rootlogger(level=logging.DEBUG)
contains_c_extension(os) # False
contains_c_extension(et) # False
contains_c_extension(numpy) # True -- different from is_c_extension()
contains_c_extension(numpy_multiarray) # True
contains_c_extension(arrow) # False
contains_c_extension(alembic) # False
contains_c_extension(alembic, include_external_imports=True) # True
# ... this example shows that Alembic imports hashlib, which can import
# _hashlib, which is a C extension; however, that doesn't stop us (for
# example) installing Alembic on a machine with no C compiler
contains_c_extension(django)
]
assert[call[name[inspect].ismodule, parameter[name[module]]]]
if compare[name[seen] is constant[None]] begin[:]
variable[seen] assign[=] list[[]]
if compare[name[module] in name[seen]] begin[:]
return[constant[False]]
call[name[seen].append, parameter[name[module]]]
variable[is_c_ext] assign[=] call[name[is_c_extension], parameter[name[module]]]
call[name[log].info, parameter[constant[Is module {!r} a C extension? {}], name[module], name[is_c_ext]]]
if name[is_c_ext] begin[:]
return[constant[True]]
if call[name[is_builtin_module], parameter[name[module]]] begin[:]
return[constant[False]]
variable[top_level_module] assign[=] call[name[seen]][constant[0]]
variable[top_path] assign[=] call[name[os].path.dirname, parameter[name[top_level_module].__file__]]
for taget[name[candidate_name]] in starred[call[name[dir], parameter[name[module]]]] begin[:]
variable[candidate] assign[=] call[name[getattr], parameter[name[module], name[candidate_name]]]
<ast.Try object at 0x7da1b184b970>
if call[name[is_builtin_module], parameter[name[candidate]]] begin[:]
continue
variable[candidate_fname] assign[=] call[name[getattr], parameter[name[candidate], constant[__file__]]]
if <ast.UnaryOp object at 0x7da1b1848bb0> begin[:]
if compare[call[name[os].path.commonpath, parameter[list[[<ast.Name object at 0x7da1b1848b80>, <ast.Name object at 0x7da1b184a890>]]]] not_equal[!=] name[top_path]] begin[:]
call[name[log].debug, parameter[constant[Skipping, not within the top-level module's directory: {!r}], name[candidate]]]
continue
if call[name[contains_c_extension], parameter[]] begin[:]
return[constant[True]]
if name[import_all_submodules] begin[:]
if <ast.UnaryOp object at 0x7da1b1848970> begin[:]
call[name[log].debug, parameter[constant[Top-level module is not a package: {!r}], name[module]]]
return[constant[False]]
call[name[log].debug, parameter[constant[Walking path: {!r}], name[top_path]]]
<ast.Try object at 0x7da1b184b730>
return[constant[False]] | keyword[def] identifier[contains_c_extension] ( identifier[module] : identifier[ModuleType] ,
identifier[import_all_submodules] : identifier[bool] = keyword[True] ,
identifier[include_external_imports] : identifier[bool] = keyword[False] ,
identifier[seen] : identifier[List] [ identifier[ModuleType] ]= keyword[None] )-> identifier[bool] :
literal[string]
keyword[assert] identifier[inspect] . identifier[ismodule] ( identifier[module] ), literal[string] . identifier[format] ( identifier[module] )
keyword[if] identifier[seen] keyword[is] keyword[None] :
identifier[seen] =[]
keyword[if] identifier[module] keyword[in] identifier[seen] :
keyword[return] keyword[False]
identifier[seen] . identifier[append] ( identifier[module] )
identifier[is_c_ext] = identifier[is_c_extension] ( identifier[module] )
identifier[log] . identifier[info] ( literal[string] , identifier[module] , identifier[is_c_ext] )
keyword[if] identifier[is_c_ext] :
keyword[return] keyword[True]
keyword[if] identifier[is_builtin_module] ( identifier[module] ):
keyword[return] keyword[False]
identifier[top_level_module] = identifier[seen] [ literal[int] ]
identifier[top_path] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[top_level_module] . identifier[__file__] )
keyword[for] identifier[candidate_name] keyword[in] identifier[dir] ( identifier[module] ):
identifier[candidate] = identifier[getattr] ( identifier[module] , identifier[candidate_name] )
keyword[try] :
keyword[if] keyword[not] identifier[inspect] . identifier[ismodule] ( identifier[candidate] ):
keyword[continue]
keyword[except] identifier[Exception] :
identifier[log] . identifier[error] ( literal[string] , identifier[candidate] )
keyword[continue]
keyword[if] identifier[is_builtin_module] ( identifier[candidate] ):
keyword[continue]
identifier[candidate_fname] = identifier[getattr] ( identifier[candidate] , literal[string] )
keyword[if] keyword[not] identifier[include_external_imports] :
keyword[if] identifier[os] . identifier[path] . identifier[commonpath] ([ identifier[top_path] , identifier[candidate_fname] ])!= identifier[top_path] :
identifier[log] . identifier[debug] ( literal[string]
literal[string] , identifier[candidate] )
keyword[continue]
keyword[if] identifier[contains_c_extension] (
identifier[module] = identifier[candidate] ,
identifier[import_all_submodules] = keyword[False] ,
identifier[include_external_imports] = identifier[include_external_imports] ,
identifier[seen] = identifier[seen] ):
keyword[return] keyword[True]
keyword[if] identifier[import_all_submodules] :
keyword[if] keyword[not] identifier[is_module_a_package] ( identifier[module] ):
identifier[log] . identifier[debug] ( literal[string] , identifier[module] )
keyword[return] keyword[False]
identifier[log] . identifier[debug] ( literal[string] , identifier[top_path] )
keyword[try] :
keyword[for] identifier[loader] , identifier[module_name] , identifier[is_pkg] keyword[in] identifier[pkgutil] . identifier[walk_packages] ([ identifier[top_path] ]):
keyword[if] keyword[not] identifier[is_pkg] :
identifier[log] . identifier[debug] ( literal[string] , identifier[module_name] )
keyword[continue]
identifier[log] . identifier[debug] ( literal[string] , identifier[module_name] )
keyword[try] :
identifier[candidate] = identifier[loader] . identifier[find_module] ( identifier[module_name] ). identifier[load_module] ( identifier[module_name] )
keyword[except] identifier[Exception] :
identifier[log] . identifier[error] ( literal[string] , identifier[module_name] )
keyword[continue]
keyword[if] identifier[contains_c_extension] (
identifier[module] = identifier[candidate] ,
identifier[import_all_submodules] = keyword[False] ,
identifier[include_external_imports] = identifier[include_external_imports] ,
identifier[seen] = identifier[seen] ):
keyword[return] keyword[True]
keyword[except] identifier[Exception] :
identifier[log] . identifier[error] ( literal[string]
literal[string] )
keyword[raise]
keyword[return] keyword[False] | def contains_c_extension(module: ModuleType, import_all_submodules: bool=True, include_external_imports: bool=False, seen: List[ModuleType]=None) -> bool:
"""
Extends :func:`is_c_extension` by asking: is this module, or any of its
submodules, a C extension?
Args:
module: Previously imported module object to be tested.
import_all_submodules: explicitly import all submodules of this module?
include_external_imports: check modules in other packages that this
module imports?
seen: used internally for recursion (to deal with recursive modules);
should be ``None`` when called by users
Returns:
bool: ``True`` only if this module or one of its submodules is a C
extension.
Examples:
.. code-block:: python
import logging
from cardinal_pythonlib.modules import contains_c_extension
from cardinal_pythonlib.logs import main_only_quicksetup_rootlogger
import _elementtree as et
import os
import arrow
import alembic
import django
import numpy
import numpy.core.multiarray as numpy_multiarray
log = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG) # be verbose
main_only_quicksetup_rootlogger(level=logging.DEBUG)
contains_c_extension(os) # False
contains_c_extension(et) # False
contains_c_extension(numpy) # True -- different from is_c_extension()
contains_c_extension(numpy_multiarray) # True
contains_c_extension(arrow) # False
contains_c_extension(alembic) # False
contains_c_extension(alembic, include_external_imports=True) # True
# ... this example shows that Alembic imports hashlib, which can import
# _hashlib, which is a C extension; however, that doesn't stop us (for
# example) installing Alembic on a machine with no C compiler
contains_c_extension(django)
""" # noqa
assert inspect.ismodule(module), '"{}" not a module.'.format(module)
if seen is None: # only true for the top-level call
seen = [] # type: List[ModuleType] # depends on [control=['if'], data=['seen']]
if module in seen: # modules can "contain" themselves
# already inspected; avoid infinite loops
return False # depends on [control=['if'], data=[]]
seen.append(module)
# Check the thing we were asked about
is_c_ext = is_c_extension(module)
log.info('Is module {!r} a C extension? {}', module, is_c_ext)
if is_c_ext:
return True # depends on [control=['if'], data=[]]
if is_builtin_module(module):
# built-in, therefore we stop searching it
return False # depends on [control=['if'], data=[]]
# Now check any children, in a couple of ways
top_level_module = seen[0]
top_path = os.path.dirname(top_level_module.__file__)
# Recurse using dir(). This picks up modules that are automatically
# imported by our top-level model. But it won't pick up all submodules;
# try e.g. for django.
for candidate_name in dir(module):
candidate = getattr(module, candidate_name)
# noinspection PyBroadException
try:
if not inspect.ismodule(candidate):
# not a module
continue # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
except Exception:
# e.g. a Django module that won't import until we configure its
# settings
log.error('Failed to test ismodule() status of {!r}', candidate)
continue # depends on [control=['except'], data=[]]
if is_builtin_module(candidate):
# built-in, therefore we stop searching it
continue # depends on [control=['if'], data=[]]
candidate_fname = getattr(candidate, '__file__')
if not include_external_imports:
if os.path.commonpath([top_path, candidate_fname]) != top_path:
log.debug("Skipping, not within the top-level module's directory: {!r}", candidate)
continue # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
# Recurse:
if contains_c_extension(module=candidate, import_all_submodules=False, include_external_imports=include_external_imports, seen=seen): # only done at the top level, below # noqa
return True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['candidate_name']]
if import_all_submodules:
if not is_module_a_package(module):
log.debug('Top-level module is not a package: {!r}', module)
return False # depends on [control=['if'], data=[]]
# Otherwise, for things like Django, we need to recurse in a different
# way to scan everything.
# See https://stackoverflow.com/questions/3365740/how-to-import-all-submodules. # noqa
log.debug('Walking path: {!r}', top_path)
# noinspection PyBroadException
try:
for (loader, module_name, is_pkg) in pkgutil.walk_packages([top_path]): # noqa
if not is_pkg:
log.debug('Skipping, not a package: {!r}', module_name)
continue # depends on [control=['if'], data=[]]
log.debug('Manually importing: {!r}', module_name)
# noinspection PyBroadException
try:
candidate = loader.find_module(module_name).load_module(module_name) # noqa # depends on [control=['try'], data=[]]
except Exception:
# e.g. Alembic "autogenerate" gives: "ValueError: attempted
# relative import beyond top-level package"; or Django
# "django.core.exceptions.ImproperlyConfigured"
log.error('Package failed to import: {!r}', module_name)
continue # depends on [control=['except'], data=[]]
if contains_c_extension(module=candidate, import_all_submodules=False, include_external_imports=include_external_imports, seen=seen): # only done at the top level # noqa
return True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['try'], data=[]]
except Exception:
log.error('Unable to walk packages further; no C extensions detected so far!')
raise # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]]
return False |
def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n' \
' sample_num={sample_num}, batch_num={batch_num}\n' \
' key={bucket_keys}\n' \
' cnt={bucket_counts}\n' \
' batch_size={bucket_batch_sizes}'\
.format(name=self.__class__.__name__,
sample_num=len(self._lengths),
batch_num=len(self._batch_infos),
bucket_keys=self._bucket_keys,
bucket_counts=[len(sample_ids) for sample_ids in self._bucket_sample_ids],
bucket_batch_sizes=self._bucket_batch_sizes)
return ret | def function[stats, parameter[self]]:
constant[Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
]
variable[ret] assign[=] call[constant[{name}:
sample_num={sample_num}, batch_num={batch_num}
key={bucket_keys}
cnt={bucket_counts}
batch_size={bucket_batch_sizes}].format, parameter[]]
return[name[ret]] | keyword[def] identifier[stats] ( identifier[self] ):
literal[string]
identifier[ret] = literal[string] literal[string] literal[string] literal[string] literal[string] . identifier[format] ( identifier[name] = identifier[self] . identifier[__class__] . identifier[__name__] ,
identifier[sample_num] = identifier[len] ( identifier[self] . identifier[_lengths] ),
identifier[batch_num] = identifier[len] ( identifier[self] . identifier[_batch_infos] ),
identifier[bucket_keys] = identifier[self] . identifier[_bucket_keys] ,
identifier[bucket_counts] =[ identifier[len] ( identifier[sample_ids] ) keyword[for] identifier[sample_ids] keyword[in] identifier[self] . identifier[_bucket_sample_ids] ],
identifier[bucket_batch_sizes] = identifier[self] . identifier[_bucket_batch_sizes] )
keyword[return] identifier[ret] | def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n sample_num={sample_num}, batch_num={batch_num}\n key={bucket_keys}\n cnt={bucket_counts}\n batch_size={bucket_batch_sizes}'.format(name=self.__class__.__name__, sample_num=len(self._lengths), batch_num=len(self._batch_infos), bucket_keys=self._bucket_keys, bucket_counts=[len(sample_ids) for sample_ids in self._bucket_sample_ids], bucket_batch_sizes=self._bucket_batch_sizes)
return ret |
def write_bytes(self, data):
"""
Open the file in bytes mode, write to it, and close the file.
"""
if not isinstance(data, six.binary_type):
raise TypeError(
'data must be %s, not %s' %
(six.binary_type.__class__.__name__, data.__class__.__name__))
with self.open(mode='wb') as f:
return f.write(data) | def function[write_bytes, parameter[self, data]]:
constant[
Open the file in bytes mode, write to it, and close the file.
]
if <ast.UnaryOp object at 0x7da20c6e7400> begin[:]
<ast.Raise object at 0x7da20c6e6590>
with call[name[self].open, parameter[]] begin[:]
return[call[name[f].write, parameter[name[data]]]] | keyword[def] identifier[write_bytes] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[data] , identifier[six] . identifier[binary_type] ):
keyword[raise] identifier[TypeError] (
literal[string] %
( identifier[six] . identifier[binary_type] . identifier[__class__] . identifier[__name__] , identifier[data] . identifier[__class__] . identifier[__name__] ))
keyword[with] identifier[self] . identifier[open] ( identifier[mode] = literal[string] ) keyword[as] identifier[f] :
keyword[return] identifier[f] . identifier[write] ( identifier[data] ) | def write_bytes(self, data):
"""
Open the file in bytes mode, write to it, and close the file.
"""
if not isinstance(data, six.binary_type):
raise TypeError('data must be %s, not %s' % (six.binary_type.__class__.__name__, data.__class__.__name__)) # depends on [control=['if'], data=[]]
with self.open(mode='wb') as f:
return f.write(data) # depends on [control=['with'], data=['f']] |
def from_lal(cls, lalfs, copy=True):
"""Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type
"""
from ..utils.lal import from_lal_unit
try:
unit = from_lal_unit(lalfs.sampleUnits)
except TypeError:
unit = None
channel = Channel(lalfs.name, unit=unit,
dtype=lalfs.data.data.dtype)
return cls(lalfs.data.data, channel=channel, f0=lalfs.f0,
df=lalfs.deltaF, epoch=float(lalfs.epoch),
dtype=lalfs.data.data.dtype, copy=copy) | def function[from_lal, parameter[cls, lalfs, copy]]:
constant[Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type
]
from relative_module[utils.lal] import module[from_lal_unit]
<ast.Try object at 0x7da20e9b3b80>
variable[channel] assign[=] call[name[Channel], parameter[name[lalfs].name]]
return[call[name[cls], parameter[name[lalfs].data.data]]] | keyword[def] identifier[from_lal] ( identifier[cls] , identifier[lalfs] , identifier[copy] = keyword[True] ):
literal[string]
keyword[from] .. identifier[utils] . identifier[lal] keyword[import] identifier[from_lal_unit]
keyword[try] :
identifier[unit] = identifier[from_lal_unit] ( identifier[lalfs] . identifier[sampleUnits] )
keyword[except] identifier[TypeError] :
identifier[unit] = keyword[None]
identifier[channel] = identifier[Channel] ( identifier[lalfs] . identifier[name] , identifier[unit] = identifier[unit] ,
identifier[dtype] = identifier[lalfs] . identifier[data] . identifier[data] . identifier[dtype] )
keyword[return] identifier[cls] ( identifier[lalfs] . identifier[data] . identifier[data] , identifier[channel] = identifier[channel] , identifier[f0] = identifier[lalfs] . identifier[f0] ,
identifier[df] = identifier[lalfs] . identifier[deltaF] , identifier[epoch] = identifier[float] ( identifier[lalfs] . identifier[epoch] ),
identifier[dtype] = identifier[lalfs] . identifier[data] . identifier[data] . identifier[dtype] , identifier[copy] = identifier[copy] ) | def from_lal(cls, lalfs, copy=True):
"""Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type
"""
from ..utils.lal import from_lal_unit
try:
unit = from_lal_unit(lalfs.sampleUnits) # depends on [control=['try'], data=[]]
except TypeError:
unit = None # depends on [control=['except'], data=[]]
channel = Channel(lalfs.name, unit=unit, dtype=lalfs.data.data.dtype)
return cls(lalfs.data.data, channel=channel, f0=lalfs.f0, df=lalfs.deltaF, epoch=float(lalfs.epoch), dtype=lalfs.data.data.dtype, copy=copy) |
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title | def function[clean_title, parameter[title]]:
constant[
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
]
variable[date_pattern] assign[=] call[name[re].compile, parameter[constant[\W*\d{1,2}[/\-.]\d{1,2}[/\-.](?=\d*)(?:.{4}|.{2})\W*]]]
variable[title] assign[=] call[name[date_pattern].sub, parameter[constant[ ], name[title]]]
variable[title] assign[=] call[name[re].sub, parameter[constant[\s{2,}], constant[ ], name[title]]]
variable[title] assign[=] call[name[title].strip, parameter[]]
return[name[title]] | keyword[def] identifier[clean_title] ( identifier[title] ):
literal[string]
identifier[date_pattern] = identifier[re] . identifier[compile] ( literal[string]
literal[string]
literal[string]
literal[string]
literal[string]
literal[string]
literal[string] )
identifier[title] = identifier[date_pattern] . identifier[sub] ( literal[string] , identifier[title] )
identifier[title] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[title] )
identifier[title] = identifier[title] . identifier[strip] ()
keyword[return] identifier[title] | def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile('\\W*\\d{1,2}[/\\-.]\\d{1,2}[/\\-.](?=\\d*)(?:.{4}|.{2})\\W*')
title = date_pattern.sub(' ', title)
title = re.sub('\\s{2,}', ' ', title)
title = title.strip()
return title |
def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear(
'(ba{sv})',
value,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | def function[set_autoclear, parameter[self, value, auth_no_user_interaction]]:
constant[Set autoclear flag for loop partition.]
return[call[name[self]._M.Loop.SetAutoclear, parameter[constant[(ba{sv})], name[value], call[name[filter_opt], parameter[dictionary[[<ast.Constant object at 0x7da18c4cfb80>], [<ast.Tuple object at 0x7da18c4ce830>]]]]]]] | keyword[def] identifier[set_autoclear] ( identifier[self] , identifier[value] , identifier[auth_no_user_interaction] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_M] . identifier[Loop] . identifier[SetAutoclear] (
literal[string] ,
identifier[value] ,
identifier[filter_opt] ({
literal[string] :( literal[string] , identifier[auth_no_user_interaction] ),
})
) | def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear('(ba{sv})', value, filter_opt({'auth.no_user_interaction': ('b', auth_no_user_interaction)})) |
def encode(self):
"""Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
"""
blob = bytearray()
for record in self.records:
blob += record.encode()
header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH)
blob = header + blob
sha = hashlib.sha256()
sha.update(blob)
hash_value = sha.digest()[:16]
return bytearray(hash_value) + blob | def function[encode, parameter[self]]:
constant[Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
]
variable[blob] assign[=] call[name[bytearray], parameter[]]
for taget[name[record]] in starred[name[self].records] begin[:]
<ast.AugAssign object at 0x7da20e9543a0>
variable[header] assign[=] call[name[struct].pack, parameter[constant[<LL], name[self].SCRIPT_MAGIC, binary_operation[call[name[len], parameter[name[blob]]] + name[self].SCRIPT_HEADER_LENGTH]]]
variable[blob] assign[=] binary_operation[name[header] + name[blob]]
variable[sha] assign[=] call[name[hashlib].sha256, parameter[]]
call[name[sha].update, parameter[name[blob]]]
variable[hash_value] assign[=] call[call[name[sha].digest, parameter[]]][<ast.Slice object at 0x7da204622b30>]
return[binary_operation[call[name[bytearray], parameter[name[hash_value]]] + name[blob]]] | keyword[def] identifier[encode] ( identifier[self] ):
literal[string]
identifier[blob] = identifier[bytearray] ()
keyword[for] identifier[record] keyword[in] identifier[self] . identifier[records] :
identifier[blob] += identifier[record] . identifier[encode] ()
identifier[header] = identifier[struct] . identifier[pack] ( literal[string] , identifier[self] . identifier[SCRIPT_MAGIC] , identifier[len] ( identifier[blob] )+ identifier[self] . identifier[SCRIPT_HEADER_LENGTH] )
identifier[blob] = identifier[header] + identifier[blob]
identifier[sha] = identifier[hashlib] . identifier[sha256] ()
identifier[sha] . identifier[update] ( identifier[blob] )
identifier[hash_value] = identifier[sha] . identifier[digest] ()[: literal[int] ]
keyword[return] identifier[bytearray] ( identifier[hash_value] )+ identifier[blob] | def encode(self):
"""Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
"""
blob = bytearray()
for record in self.records:
blob += record.encode() # depends on [control=['for'], data=['record']]
header = struct.pack('<LL', self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH)
blob = header + blob
sha = hashlib.sha256()
sha.update(blob)
hash_value = sha.digest()[:16]
return bytearray(hash_value) + blob |
def _create_fw(self, tenant_id, data):
"""Internal routine that gets called when a FW is created. """
LOG.debug("In creating Native FW data is %s", data)
# TODO(padkrish):
# Check if router is already added and only then add, needed for
# restart cases since native doesn't have a special DB
ret, in_sub, out_sub = self.attach_intf_router(tenant_id,
data.get('tenant_name'),
data.get('router_id'))
if not ret:
LOG.error("Native FW: Attach intf router failed for tenant "
"%s", tenant_id)
return False
self.create_tenant_dict(tenant_id, data.get('router_id'))
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub)
# Program DCNM to update profile's static IP address on OUT part
ret = self.update_dcnm_partition_static_route(tenant_id, arg_dict)
if not ret:
return False
# Program the default GW in router namespace
ret = self.program_default_gw(tenant_id, arg_dict)
if not ret:
return False
# Program router namespace to have all tenant networks to be routed
# to IN service network
ret = self.program_next_hop(tenant_id, arg_dict)
if not ret:
return False
# Send message for router port auto config for in service nwk
ret = self.send_in_router_port_msg(tenant_id, arg_dict, 'up')
if not ret:
return False
# Send message for router port auto config for out service nwk
return self.send_out_router_port_msg(tenant_id, arg_dict, 'up') | def function[_create_fw, parameter[self, tenant_id, data]]:
constant[Internal routine that gets called when a FW is created. ]
call[name[LOG].debug, parameter[constant[In creating Native FW data is %s], name[data]]]
<ast.Tuple object at 0x7da1b1b7f010> assign[=] call[name[self].attach_intf_router, parameter[name[tenant_id], call[name[data].get, parameter[constant[tenant_name]]], call[name[data].get, parameter[constant[router_id]]]]]
if <ast.UnaryOp object at 0x7da1b1b7e9e0> begin[:]
call[name[LOG].error, parameter[constant[Native FW: Attach intf router failed for tenant %s], name[tenant_id]]]
return[constant[False]]
call[name[self].create_tenant_dict, parameter[name[tenant_id], call[name[data].get, parameter[constant[router_id]]]]]
variable[arg_dict] assign[=] call[name[self]._create_arg_dict, parameter[name[tenant_id], name[data], name[in_sub], name[out_sub]]]
variable[ret] assign[=] call[name[self].update_dcnm_partition_static_route, parameter[name[tenant_id], name[arg_dict]]]
if <ast.UnaryOp object at 0x7da1b1b7dff0> begin[:]
return[constant[False]]
variable[ret] assign[=] call[name[self].program_default_gw, parameter[name[tenant_id], name[arg_dict]]]
if <ast.UnaryOp object at 0x7da1b1b7f340> begin[:]
return[constant[False]]
variable[ret] assign[=] call[name[self].program_next_hop, parameter[name[tenant_id], name[arg_dict]]]
if <ast.UnaryOp object at 0x7da1b1b7c3a0> begin[:]
return[constant[False]]
variable[ret] assign[=] call[name[self].send_in_router_port_msg, parameter[name[tenant_id], name[arg_dict], constant[up]]]
if <ast.UnaryOp object at 0x7da18dc99d50> begin[:]
return[constant[False]]
return[call[name[self].send_out_router_port_msg, parameter[name[tenant_id], name[arg_dict], constant[up]]]] | keyword[def] identifier[_create_fw] ( identifier[self] , identifier[tenant_id] , identifier[data] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] , identifier[data] )
identifier[ret] , identifier[in_sub] , identifier[out_sub] = identifier[self] . identifier[attach_intf_router] ( identifier[tenant_id] ,
identifier[data] . identifier[get] ( literal[string] ),
identifier[data] . identifier[get] ( literal[string] ))
keyword[if] keyword[not] identifier[ret] :
identifier[LOG] . identifier[error] ( literal[string]
literal[string] , identifier[tenant_id] )
keyword[return] keyword[False]
identifier[self] . identifier[create_tenant_dict] ( identifier[tenant_id] , identifier[data] . identifier[get] ( literal[string] ))
identifier[arg_dict] = identifier[self] . identifier[_create_arg_dict] ( identifier[tenant_id] , identifier[data] , identifier[in_sub] , identifier[out_sub] )
identifier[ret] = identifier[self] . identifier[update_dcnm_partition_static_route] ( identifier[tenant_id] , identifier[arg_dict] )
keyword[if] keyword[not] identifier[ret] :
keyword[return] keyword[False]
identifier[ret] = identifier[self] . identifier[program_default_gw] ( identifier[tenant_id] , identifier[arg_dict] )
keyword[if] keyword[not] identifier[ret] :
keyword[return] keyword[False]
identifier[ret] = identifier[self] . identifier[program_next_hop] ( identifier[tenant_id] , identifier[arg_dict] )
keyword[if] keyword[not] identifier[ret] :
keyword[return] keyword[False]
identifier[ret] = identifier[self] . identifier[send_in_router_port_msg] ( identifier[tenant_id] , identifier[arg_dict] , literal[string] )
keyword[if] keyword[not] identifier[ret] :
keyword[return] keyword[False]
keyword[return] identifier[self] . identifier[send_out_router_port_msg] ( identifier[tenant_id] , identifier[arg_dict] , literal[string] ) | def _create_fw(self, tenant_id, data):
"""Internal routine that gets called when a FW is created. """
LOG.debug('In creating Native FW data is %s', data)
# TODO(padkrish):
# Check if router is already added and only then add, needed for
# restart cases since native doesn't have a special DB
(ret, in_sub, out_sub) = self.attach_intf_router(tenant_id, data.get('tenant_name'), data.get('router_id'))
if not ret:
LOG.error('Native FW: Attach intf router failed for tenant %s', tenant_id)
return False # depends on [control=['if'], data=[]]
self.create_tenant_dict(tenant_id, data.get('router_id'))
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub)
# Program DCNM to update profile's static IP address on OUT part
ret = self.update_dcnm_partition_static_route(tenant_id, arg_dict)
if not ret:
return False # depends on [control=['if'], data=[]]
# Program the default GW in router namespace
ret = self.program_default_gw(tenant_id, arg_dict)
if not ret:
return False # depends on [control=['if'], data=[]]
# Program router namespace to have all tenant networks to be routed
# to IN service network
ret = self.program_next_hop(tenant_id, arg_dict)
if not ret:
return False # depends on [control=['if'], data=[]]
# Send message for router port auto config for in service nwk
ret = self.send_in_router_port_msg(tenant_id, arg_dict, 'up')
if not ret:
return False # depends on [control=['if'], data=[]]
# Send message for router port auto config for out service nwk
return self.send_out_router_port_msg(tenant_id, arg_dict, 'up') |
def _parse_expiry(response_data):
"""Parses the expiry field from a response into a datetime.
Args:
response_data (Mapping): The JSON-parsed response data.
Returns:
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
"""
expires_in = response_data.get('expires_in', None)
if expires_in is not None:
return _helpers.utcnow() + datetime.timedelta(
seconds=expires_in)
else:
return None | def function[_parse_expiry, parameter[response_data]]:
constant[Parses the expiry field from a response into a datetime.
Args:
response_data (Mapping): The JSON-parsed response data.
Returns:
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
]
variable[expires_in] assign[=] call[name[response_data].get, parameter[constant[expires_in], constant[None]]]
if compare[name[expires_in] is_not constant[None]] begin[:]
return[binary_operation[call[name[_helpers].utcnow, parameter[]] + call[name[datetime].timedelta, parameter[]]]] | keyword[def] identifier[_parse_expiry] ( identifier[response_data] ):
literal[string]
identifier[expires_in] = identifier[response_data] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[expires_in] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[_helpers] . identifier[utcnow] ()+ identifier[datetime] . identifier[timedelta] (
identifier[seconds] = identifier[expires_in] )
keyword[else] :
keyword[return] keyword[None] | def _parse_expiry(response_data):
"""Parses the expiry field from a response into a datetime.
Args:
response_data (Mapping): The JSON-parsed response data.
Returns:
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
"""
expires_in = response_data.get('expires_in', None)
if expires_in is not None:
return _helpers.utcnow() + datetime.timedelta(seconds=expires_in) # depends on [control=['if'], data=['expires_in']]
else:
return None |
def view_export(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#export-view"
api_path = "/api/v2/views/{id}/export.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | def function[view_export, parameter[self, id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/views#export-view]
variable[api_path] assign[=] constant[/api/v2/views/{id}/export.json]
variable[api_path] assign[=] call[name[api_path].format, parameter[]]
return[call[name[self].call, parameter[name[api_path]]]] | keyword[def] identifier[view_export] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[id] = identifier[id] )
keyword[return] identifier[self] . identifier[call] ( identifier[api_path] ,** identifier[kwargs] ) | def view_export(self, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/views#export-view"""
api_path = '/api/v2/views/{id}/export.json'
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == u'(':
sents[i][j] = (token, u'-LRB-')
elif tag == u')':
sents[i][j] = (token, u'-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(model=model)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy)) | def function[evaluate_perceptron, parameter[ctx, model, corpus]]:
constant[Evaluate performance of Averaged Perceptron POS Tagger.]
call[name[click].echo, parameter[constant[chemdataextractor.pos.evaluate]]]
if compare[name[corpus] equal[==] constant[wsj]] begin[:]
variable[evaluation] assign[=] name[wsj_evaluation]
variable[sents] assign[=] call[name[list], parameter[call[name[evaluation].tagged_sents, parameter[]]]]
for taget[tuple[[<ast.Name object at 0x7da18dc9b5e0>, <ast.Name object at 0x7da18dc9aad0>]]] in starred[call[name[enumerate], parameter[name[sents]]]] begin[:]
call[name[sents]][name[i]] assign[=] <ast.ListComp object at 0x7da18dc99f30>
variable[tagger] assign[=] call[name[ChemApPosTagger], parameter[]]
variable[accuracy] assign[=] call[name[tagger].evaluate, parameter[name[sents]]]
call[name[click].echo, parameter[binary_operation[constant[%s on %s: %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b1388550>, <ast.Name object at 0x7da1b1388940>, <ast.Name object at 0x7da1b13890c0>]]]]] | keyword[def] identifier[evaluate_perceptron] ( identifier[ctx] , identifier[model] , identifier[corpus] ):
literal[string]
identifier[click] . identifier[echo] ( literal[string] )
keyword[if] identifier[corpus] == literal[string] :
identifier[evaluation] = identifier[wsj_evaluation]
identifier[sents] = identifier[list] ( identifier[evaluation] . identifier[tagged_sents] ())
keyword[for] identifier[i] , identifier[wsj_sent] keyword[in] identifier[enumerate] ( identifier[sents] ):
identifier[sents] [ identifier[i] ]=[ identifier[t] keyword[for] identifier[t] keyword[in] identifier[wsj_sent] keyword[if] keyword[not] identifier[t] [ literal[int] ]== literal[string] ]
keyword[elif] identifier[corpus] == literal[string] :
identifier[evaluation] = identifier[genia_evaluation]
identifier[sents] = identifier[list] ( identifier[evaluation] . identifier[tagged_sents] ())
keyword[for] identifier[i] , identifier[genia_sent] keyword[in] identifier[enumerate] ( identifier[sents] ):
keyword[for] identifier[j] ,( identifier[token] , identifier[tag] ) keyword[in] identifier[enumerate] ( identifier[genia_sent] ):
keyword[if] identifier[tag] == literal[string] :
identifier[sents] [ identifier[i] ][ identifier[j] ]=( identifier[token] , literal[string] )
keyword[elif] identifier[tag] == literal[string] :
identifier[sents] [ identifier[i] ][ identifier[j] ]=( identifier[token] , literal[string] )
keyword[else] :
keyword[raise] identifier[click] . identifier[ClickException] ( literal[string] )
identifier[tagger] = identifier[ChemApPosTagger] ( identifier[model] = identifier[model] )
identifier[accuracy] = identifier[tagger] . identifier[evaluate] ( identifier[sents] )
identifier[click] . identifier[echo] ( literal[string] %( identifier[model] , identifier[evaluation] , identifier[accuracy] )) | def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for (i, wsj_sent) in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-'] # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for (i, genia_sent) in enumerate(sents):
for (j, (token, tag)) in enumerate(genia_sent):
if tag == u'(':
sents[i][j] = (token, u'-LRB-') # depends on [control=['if'], data=[]]
elif tag == u')':
sents[i][j] = (token, u'-RRB-') # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(model=model)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy)) |
def set_cmap_cb(self, w, index):
"""This callback is invoked when the user selects a new color
map from the preferences pane."""
name = cmap.get_names()[index]
self.t_.set(color_map=name) | def function[set_cmap_cb, parameter[self, w, index]]:
constant[This callback is invoked when the user selects a new color
map from the preferences pane.]
variable[name] assign[=] call[call[name[cmap].get_names, parameter[]]][name[index]]
call[name[self].t_.set, parameter[]] | keyword[def] identifier[set_cmap_cb] ( identifier[self] , identifier[w] , identifier[index] ):
literal[string]
identifier[name] = identifier[cmap] . identifier[get_names] ()[ identifier[index] ]
identifier[self] . identifier[t_] . identifier[set] ( identifier[color_map] = identifier[name] ) | def set_cmap_cb(self, w, index):
"""This callback is invoked when the user selects a new color
map from the preferences pane."""
name = cmap.get_names()[index]
self.t_.set(color_map=name) |
def save_png_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a matplotlib figure to a png with metadata
"""
from PIL import Image, PngImagePlugin
fig.savefig(filename, **fig_kwds)
im = Image.open(filename)
meta = PngImagePlugin.PngInfo()
for key in kwds:
meta.add_text(str(key), str(kwds[key]))
im.save(filename, "png", pnginfo=meta) | def function[save_png_with_metadata, parameter[fig, filename, fig_kwds, kwds]]:
constant[ Save a matplotlib figure to a png with metadata
]
from relative_module[PIL] import module[Image], module[PngImagePlugin]
call[name[fig].savefig, parameter[name[filename]]]
variable[im] assign[=] call[name[Image].open, parameter[name[filename]]]
variable[meta] assign[=] call[name[PngImagePlugin].PngInfo, parameter[]]
for taget[name[key]] in starred[name[kwds]] begin[:]
call[name[meta].add_text, parameter[call[name[str], parameter[name[key]]], call[name[str], parameter[call[name[kwds]][name[key]]]]]]
call[name[im].save, parameter[name[filename], constant[png]]] | keyword[def] identifier[save_png_with_metadata] ( identifier[fig] , identifier[filename] , identifier[fig_kwds] , identifier[kwds] ):
literal[string]
keyword[from] identifier[PIL] keyword[import] identifier[Image] , identifier[PngImagePlugin]
identifier[fig] . identifier[savefig] ( identifier[filename] ,** identifier[fig_kwds] )
identifier[im] = identifier[Image] . identifier[open] ( identifier[filename] )
identifier[meta] = identifier[PngImagePlugin] . identifier[PngInfo] ()
keyword[for] identifier[key] keyword[in] identifier[kwds] :
identifier[meta] . identifier[add_text] ( identifier[str] ( identifier[key] ), identifier[str] ( identifier[kwds] [ identifier[key] ]))
identifier[im] . identifier[save] ( identifier[filename] , literal[string] , identifier[pnginfo] = identifier[meta] ) | def save_png_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a matplotlib figure to a png with metadata
"""
from PIL import Image, PngImagePlugin
fig.savefig(filename, **fig_kwds)
im = Image.open(filename)
meta = PngImagePlugin.PngInfo()
for key in kwds:
meta.add_text(str(key), str(kwds[key])) # depends on [control=['for'], data=['key']]
im.save(filename, 'png', pnginfo=meta) |
def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = "{0:." + str(task.decimals) + "f}"
percents = str_format.format(100 * (task.progress / float(task.total)))
filled_length = int(round(task.bar_length * task.progress / float(task.total)))
bar = '█' * filled_length + '-' * (task.bar_length - filled_length)
# Build elapsed time if needed
elapsed_time = None
if task.display_time:
if task.end_time:
# If the task has ended, stop the chrono
if not task.elapsed_time_at_end:
task.elapsed_time_at_end = self.millis_to_human_readable(task.end_time - task.begin_time)
elapsed_time = task.elapsed_time_at_end
else:
# If task is new then start the chrono
if not task.begin_time:
task.begin_time = millis()
elapsed_time = self.millis_to_human_readable(millis() - task.begin_time)
prefix_pattern = '%{}s'.format(self.longest_bar_prefix_size)
time_container_pattern = '(%s)' if task.display_time and not task.end_time else '[%s]'
if len(task.suffix) > 0 and task.display_time:
sys.stdout.write('\n {} |%s| %3s %% {} - %s'.format(prefix_pattern, time_container_pattern)
% (task.prefix, bar, percents, elapsed_time, task.suffix))
elif len(task.suffix) > 0 and not task.display_time:
sys.stdout.write('\n {} |%s| %3s %% - %s'.format(prefix_pattern)
% (task.prefix, bar, percents, task.suffix))
elif task.display_time and not len(task.suffix) > 0:
sys.stdout.write('\n {} |%s| %3s %% {}'.format(prefix_pattern, time_container_pattern)
% (task.prefix, bar, percents, elapsed_time))
else:
sys.stdout.write('\n {} |%s| %3s %%'.format(prefix_pattern)
% (task.prefix, bar, percents))
sys.stdout.write('\n')
sys.stdout.flush() | def function[print_progress_bar, parameter[self, task]]:
constant[
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
]
variable[str_format] assign[=] binary_operation[binary_operation[constant[{0:.] + call[name[str], parameter[name[task].decimals]]] + constant[f}]]
variable[percents] assign[=] call[name[str_format].format, parameter[binary_operation[constant[100] * binary_operation[name[task].progress / call[name[float], parameter[name[task].total]]]]]]
variable[filled_length] assign[=] call[name[int], parameter[call[name[round], parameter[binary_operation[binary_operation[name[task].bar_length * name[task].progress] / call[name[float], parameter[name[task].total]]]]]]]
variable[bar] assign[=] binary_operation[binary_operation[constant[█] * name[filled_length]] + binary_operation[constant[-] * binary_operation[name[task].bar_length - name[filled_length]]]]
variable[elapsed_time] assign[=] constant[None]
if name[task].display_time begin[:]
if name[task].end_time begin[:]
if <ast.UnaryOp object at 0x7da1b1470c10> begin[:]
name[task].elapsed_time_at_end assign[=] call[name[self].millis_to_human_readable, parameter[binary_operation[name[task].end_time - name[task].begin_time]]]
variable[elapsed_time] assign[=] name[task].elapsed_time_at_end
variable[prefix_pattern] assign[=] call[constant[%{}s].format, parameter[name[self].longest_bar_prefix_size]]
variable[time_container_pattern] assign[=] <ast.IfExp object at 0x7da1b1473370>
if <ast.BoolOp object at 0x7da1b1471690> begin[:]
call[name[sys].stdout.write, parameter[binary_operation[call[constant[
{} |%s| %3s %% {} - %s].format, parameter[name[prefix_pattern], name[time_container_pattern]]] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b1472650>, <ast.Name object at 0x7da1b1470a90>, <ast.Name object at 0x7da1b1471930>, <ast.Name object at 0x7da1b1473e50>, <ast.Attribute object at 0x7da1b1472a40>]]]]]
call[name[sys].stdout.write, parameter[constant[
]]]
call[name[sys].stdout.flush, parameter[]] | keyword[def] identifier[print_progress_bar] ( identifier[self] , identifier[task] ):
literal[string]
identifier[str_format] = literal[string] + identifier[str] ( identifier[task] . identifier[decimals] )+ literal[string]
identifier[percents] = identifier[str_format] . identifier[format] ( literal[int] *( identifier[task] . identifier[progress] / identifier[float] ( identifier[task] . identifier[total] )))
identifier[filled_length] = identifier[int] ( identifier[round] ( identifier[task] . identifier[bar_length] * identifier[task] . identifier[progress] / identifier[float] ( identifier[task] . identifier[total] )))
identifier[bar] = literal[string] * identifier[filled_length] + literal[string] *( identifier[task] . identifier[bar_length] - identifier[filled_length] )
identifier[elapsed_time] = keyword[None]
keyword[if] identifier[task] . identifier[display_time] :
keyword[if] identifier[task] . identifier[end_time] :
keyword[if] keyword[not] identifier[task] . identifier[elapsed_time_at_end] :
identifier[task] . identifier[elapsed_time_at_end] = identifier[self] . identifier[millis_to_human_readable] ( identifier[task] . identifier[end_time] - identifier[task] . identifier[begin_time] )
identifier[elapsed_time] = identifier[task] . identifier[elapsed_time_at_end]
keyword[else] :
keyword[if] keyword[not] identifier[task] . identifier[begin_time] :
identifier[task] . identifier[begin_time] = identifier[millis] ()
identifier[elapsed_time] = identifier[self] . identifier[millis_to_human_readable] ( identifier[millis] ()- identifier[task] . identifier[begin_time] )
identifier[prefix_pattern] = literal[string] . identifier[format] ( identifier[self] . identifier[longest_bar_prefix_size] )
identifier[time_container_pattern] = literal[string] keyword[if] identifier[task] . identifier[display_time] keyword[and] keyword[not] identifier[task] . identifier[end_time] keyword[else] literal[string]
keyword[if] identifier[len] ( identifier[task] . identifier[suffix] )> literal[int] keyword[and] identifier[task] . identifier[display_time] :
identifier[sys] . identifier[stdout] . identifier[write] ( literal[string] . identifier[format] ( identifier[prefix_pattern] , identifier[time_container_pattern] )
%( identifier[task] . identifier[prefix] , identifier[bar] , identifier[percents] , identifier[elapsed_time] , identifier[task] . identifier[suffix] ))
keyword[elif] identifier[len] ( identifier[task] . identifier[suffix] )> literal[int] keyword[and] keyword[not] identifier[task] . identifier[display_time] :
identifier[sys] . identifier[stdout] . identifier[write] ( literal[string] . identifier[format] ( identifier[prefix_pattern] )
%( identifier[task] . identifier[prefix] , identifier[bar] , identifier[percents] , identifier[task] . identifier[suffix] ))
keyword[elif] identifier[task] . identifier[display_time] keyword[and] keyword[not] identifier[len] ( identifier[task] . identifier[suffix] )> literal[int] :
identifier[sys] . identifier[stdout] . identifier[write] ( literal[string] . identifier[format] ( identifier[prefix_pattern] , identifier[time_container_pattern] )
%( identifier[task] . identifier[prefix] , identifier[bar] , identifier[percents] , identifier[elapsed_time] ))
keyword[else] :
identifier[sys] . identifier[stdout] . identifier[write] ( literal[string] . identifier[format] ( identifier[prefix_pattern] )
%( identifier[task] . identifier[prefix] , identifier[bar] , identifier[percents] ))
identifier[sys] . identifier[stdout] . identifier[write] ( literal[string] )
identifier[sys] . identifier[stdout] . identifier[flush] () | def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = '{0:.' + str(task.decimals) + 'f}'
percents = str_format.format(100 * (task.progress / float(task.total)))
filled_length = int(round(task.bar_length * task.progress / float(task.total)))
bar = '█' * filled_length + '-' * (task.bar_length - filled_length)
# Build elapsed time if needed
elapsed_time = None
if task.display_time:
if task.end_time:
# If the task has ended, stop the chrono
if not task.elapsed_time_at_end:
task.elapsed_time_at_end = self.millis_to_human_readable(task.end_time - task.begin_time) # depends on [control=['if'], data=[]]
elapsed_time = task.elapsed_time_at_end # depends on [control=['if'], data=[]]
else:
# If task is new then start the chrono
if not task.begin_time:
task.begin_time = millis() # depends on [control=['if'], data=[]]
elapsed_time = self.millis_to_human_readable(millis() - task.begin_time) # depends on [control=['if'], data=[]]
prefix_pattern = '%{}s'.format(self.longest_bar_prefix_size)
time_container_pattern = '(%s)' if task.display_time and (not task.end_time) else '[%s]'
if len(task.suffix) > 0 and task.display_time:
sys.stdout.write('\n {} |%s| %3s %% {} - %s'.format(prefix_pattern, time_container_pattern) % (task.prefix, bar, percents, elapsed_time, task.suffix)) # depends on [control=['if'], data=[]]
elif len(task.suffix) > 0 and (not task.display_time):
sys.stdout.write('\n {} |%s| %3s %% - %s'.format(prefix_pattern) % (task.prefix, bar, percents, task.suffix)) # depends on [control=['if'], data=[]]
elif task.display_time and (not len(task.suffix) > 0):
sys.stdout.write('\n {} |%s| %3s %% {}'.format(prefix_pattern, time_container_pattern) % (task.prefix, bar, percents, elapsed_time)) # depends on [control=['if'], data=[]]
else:
sys.stdout.write('\n {} |%s| %3s %%'.format(prefix_pattern) % (task.prefix, bar, percents))
sys.stdout.write('\n')
sys.stdout.flush() |
def set_interpolation_coefficients(self):
"""
computes the coefficients for the single polynomials of the spline.
"""
left_boundary_slope = 0
right_boundary_slope = 0
if isinstance(self.boundary_condition, tuple):
left_boundary_slope = self.boundary_condition[0]
right_boundary_slope = self.boundary_condition[1]
elif self.boundary_condition is None:
pass
else:
msg = 'The given object {} of type {} is not a valid condition ' \
'for the border'.format(self.boundary_condition, type(self.boundary_condition))
raise ValueError(msg)
# getting the values such that we get a continuous second derivative
# by solving a system of linear equations
# setup the matrix
n = len(self.x_list)
mat = numpy.zeros((n, n))
b = numpy.zeros((n, 1))
x = self.x_list
y = self.y_list
if n > 2:
for i in range(1, n - 1):
mat[i, i - 1] = 1.0 / (x[i] - x[i - 1])
mat[i, i + 1] = 1.0 / (x[i + 1] - x[i])
mat[i, i] = 2 * (mat[i, i - 1] + mat[i, i + 1])
b[i, 0] = 3 * ((y[i] - y[i - 1]) / (x[i] - x[i - 1]) ** 2
+ (y[i + 1] - y[i]) / (x[i + 1] - x[i]) ** 2)
elif n < 2:
raise ValueError('too less points for interpolation')
if self.boundary_condition is None: # not a knot
mat[0, 0] = 1.0 / (x[1] - x[0]) ** 2
mat[0, 2] = -1.0 / (x[2] - x[1]) ** 2
mat[0, 1] = mat[0, 0] + mat[0, 2]
b[0, 0] = 2.0 * ((y[1] - y[0]) / (x[1] - x[0]) ** 3
- (y[2] - y[1]) / (x[2] - x[1]) ** 3)
mat[n - 1, n - 3] = 1.0 / (x[n - 2] - x[n - 3]) ** 2
mat[n - 1, n - 1] = -1.0 / (x[n - 1] - x[n - 2]) ** 2
mat[n - 1, n - 2] = mat[n - 1, n - 3] + mat[n - 1, n - 1]
b[n - 1, 0] = 2.0 * ((y[n - 2] - y[n - 3]) / (x[n - 2] - x[n - 3]) ** 3
- (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]) ** 3)
else:
mat[0, 0] = 2.0 / (x[1] - x[0])
mat[0, 1] = 1.0 / (x[1] - x[0])
b[0, 0] = 3 * (y[1] - y[0]) / (x[1] - x[0]) ** 2 - 0.5 * left_boundary_slope
mat[n - 1, n - 2] = 1.0 / (x[n - 1] - x[n - 2])
mat[n - 1, n - 1] = 2.0 / (x[n - 1] - x[n - 2])
b[n - 1, 0] = 3 * (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]) ** 2 + 0.5 * right_boundary_slope
k = numpy.linalg.solve(mat, b)
for i in range(1, n):
c1 = k[i - 1, 0] * (x[i] - x[i - 1]) - (y[i] - y[i - 1])
c2 = -k[i, 0] * (x[i] - x[i - 1]) + (y[i] - y[i - 1])
self.interpolation_coefficients.append([c1, c2]) | def function[set_interpolation_coefficients, parameter[self]]:
constant[
computes the coefficients for the single polynomials of the spline.
]
variable[left_boundary_slope] assign[=] constant[0]
variable[right_boundary_slope] assign[=] constant[0]
if call[name[isinstance], parameter[name[self].boundary_condition, name[tuple]]] begin[:]
variable[left_boundary_slope] assign[=] call[name[self].boundary_condition][constant[0]]
variable[right_boundary_slope] assign[=] call[name[self].boundary_condition][constant[1]]
variable[n] assign[=] call[name[len], parameter[name[self].x_list]]
variable[mat] assign[=] call[name[numpy].zeros, parameter[tuple[[<ast.Name object at 0x7da1b2344100>, <ast.Name object at 0x7da1b2346740>]]]]
variable[b] assign[=] call[name[numpy].zeros, parameter[tuple[[<ast.Name object at 0x7da1b2344af0>, <ast.Constant object at 0x7da1b2345090>]]]]
variable[x] assign[=] name[self].x_list
variable[y] assign[=] name[self].y_list
if compare[name[n] greater[>] constant[2]] begin[:]
for taget[name[i]] in starred[call[name[range], parameter[constant[1], binary_operation[name[n] - constant[1]]]]] begin[:]
call[name[mat]][tuple[[<ast.Name object at 0x7da1b23477f0>, <ast.BinOp object at 0x7da1b2344a30>]]] assign[=] binary_operation[constant[1.0] / binary_operation[call[name[x]][name[i]] - call[name[x]][binary_operation[name[i] - constant[1]]]]]
call[name[mat]][tuple[[<ast.Name object at 0x7da1b23470d0>, <ast.BinOp object at 0x7da1b2346b00>]]] assign[=] binary_operation[constant[1.0] / binary_operation[call[name[x]][binary_operation[name[i] + constant[1]]] - call[name[x]][name[i]]]]
call[name[mat]][tuple[[<ast.Name object at 0x7da1b2345cf0>, <ast.Name object at 0x7da1b2344d00>]]] assign[=] binary_operation[constant[2] * binary_operation[call[name[mat]][tuple[[<ast.Name object at 0x7da1b2345a50>, <ast.BinOp object at 0x7da1b2346e60>]]] + call[name[mat]][tuple[[<ast.Name object at 0x7da1b2344970>, <ast.BinOp object at 0x7da1b23468f0>]]]]]
call[name[b]][tuple[[<ast.Name object at 0x7da1b004e680>, <ast.Constant object at 0x7da2049607f0>]]] assign[=] binary_operation[constant[3] * binary_operation[binary_operation[binary_operation[call[name[y]][name[i]] - call[name[y]][binary_operation[name[i] - constant[1]]]] / binary_operation[binary_operation[call[name[x]][name[i]] - call[name[x]][binary_operation[name[i] - constant[1]]]] ** constant[2]]] + binary_operation[binary_operation[call[name[y]][binary_operation[name[i] + constant[1]]] - call[name[y]][name[i]]] / binary_operation[binary_operation[call[name[x]][binary_operation[name[i] + constant[1]]] - call[name[x]][name[i]]] ** constant[2]]]]]
if compare[name[self].boundary_condition is constant[None]] begin[:]
call[name[mat]][tuple[[<ast.Constant object at 0x7da1b2346260>, <ast.Constant object at 0x7da1b2346290>]]] assign[=] binary_operation[constant[1.0] / binary_operation[binary_operation[call[name[x]][constant[1]] - call[name[x]][constant[0]]] ** constant[2]]]
call[name[mat]][tuple[[<ast.Constant object at 0x7da18f721930>, <ast.Constant object at 0x7da18f721030>]]] assign[=] binary_operation[<ast.UnaryOp object at 0x7da18f720a60> / binary_operation[binary_operation[call[name[x]][constant[2]] - call[name[x]][constant[1]]] ** constant[2]]]
call[name[mat]][tuple[[<ast.Constant object at 0x7da18f720160>, <ast.Constant object at 0x7da18f723490>]]] assign[=] binary_operation[call[name[mat]][tuple[[<ast.Constant object at 0x7da18f7228c0>, <ast.Constant object at 0x7da18f7204c0>]]] + call[name[mat]][tuple[[<ast.Constant object at 0x7da18f722170>, <ast.Constant object at 0x7da18f7209a0>]]]]
call[name[b]][tuple[[<ast.Constant object at 0x7da18f720a00>, <ast.Constant object at 0x7da18f720fd0>]]] assign[=] binary_operation[constant[2.0] * binary_operation[binary_operation[binary_operation[call[name[y]][constant[1]] - call[name[y]][constant[0]]] / binary_operation[binary_operation[call[name[x]][constant[1]] - call[name[x]][constant[0]]] ** constant[3]]] - binary_operation[binary_operation[call[name[y]][constant[2]] - call[name[y]][constant[1]]] / binary_operation[binary_operation[call[name[x]][constant[2]] - call[name[x]][constant[1]]] ** constant[3]]]]]
call[name[mat]][tuple[[<ast.BinOp object at 0x7da18f723730>, <ast.BinOp object at 0x7da18f720d90>]]] assign[=] binary_operation[constant[1.0] / binary_operation[binary_operation[call[name[x]][binary_operation[name[n] - constant[2]]] - call[name[x]][binary_operation[name[n] - constant[3]]]] ** constant[2]]]
call[name[mat]][tuple[[<ast.BinOp object at 0x7da18f723190>, <ast.BinOp object at 0x7da18f720580>]]] assign[=] binary_operation[<ast.UnaryOp object at 0x7da18f720460> / binary_operation[binary_operation[call[name[x]][binary_operation[name[n] - constant[1]]] - call[name[x]][binary_operation[name[n] - constant[2]]]] ** constant[2]]]
call[name[mat]][tuple[[<ast.BinOp object at 0x7da18f7208b0>, <ast.BinOp object at 0x7da18f720c40>]]] assign[=] binary_operation[call[name[mat]][tuple[[<ast.BinOp object at 0x7da18f722500>, <ast.BinOp object at 0x7da18f721ae0>]]] + call[name[mat]][tuple[[<ast.BinOp object at 0x7da18f721960>, <ast.BinOp object at 0x7da18f723850>]]]]
call[name[b]][tuple[[<ast.BinOp object at 0x7da18f7210f0>, <ast.Constant object at 0x7da204346b90>]]] assign[=] binary_operation[constant[2.0] * binary_operation[binary_operation[binary_operation[call[name[y]][binary_operation[name[n] - constant[2]]] - call[name[y]][binary_operation[name[n] - constant[3]]]] / binary_operation[binary_operation[call[name[x]][binary_operation[name[n] - constant[2]]] - call[name[x]][binary_operation[name[n] - constant[3]]]] ** constant[3]]] - binary_operation[binary_operation[call[name[y]][binary_operation[name[n] - constant[1]]] - call[name[y]][binary_operation[name[n] - constant[2]]]] / binary_operation[binary_operation[call[name[x]][binary_operation[name[n] - constant[1]]] - call[name[x]][binary_operation[name[n] - constant[2]]]] ** constant[3]]]]]
variable[k] assign[=] call[name[numpy].linalg.solve, parameter[name[mat], name[b]]]
for taget[name[i]] in starred[call[name[range], parameter[constant[1], name[n]]]] begin[:]
variable[c1] assign[=] binary_operation[binary_operation[call[name[k]][tuple[[<ast.BinOp object at 0x7da204347340>, <ast.Constant object at 0x7da204347e20>]]] * binary_operation[call[name[x]][name[i]] - call[name[x]][binary_operation[name[i] - constant[1]]]]] - binary_operation[call[name[y]][name[i]] - call[name[y]][binary_operation[name[i] - constant[1]]]]]
variable[c2] assign[=] binary_operation[binary_operation[<ast.UnaryOp object at 0x7da204344220> * binary_operation[call[name[x]][name[i]] - call[name[x]][binary_operation[name[i] - constant[1]]]]] + binary_operation[call[name[y]][name[i]] - call[name[y]][binary_operation[name[i] - constant[1]]]]]
call[name[self].interpolation_coefficients.append, parameter[list[[<ast.Name object at 0x7da204622ad0>, <ast.Name object at 0x7da204622140>]]]] | keyword[def] identifier[set_interpolation_coefficients] ( identifier[self] ):
literal[string]
identifier[left_boundary_slope] = literal[int]
identifier[right_boundary_slope] = literal[int]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[boundary_condition] , identifier[tuple] ):
identifier[left_boundary_slope] = identifier[self] . identifier[boundary_condition] [ literal[int] ]
identifier[right_boundary_slope] = identifier[self] . identifier[boundary_condition] [ literal[int] ]
keyword[elif] identifier[self] . identifier[boundary_condition] keyword[is] keyword[None] :
keyword[pass]
keyword[else] :
identifier[msg] = literal[string] literal[string] . identifier[format] ( identifier[self] . identifier[boundary_condition] , identifier[type] ( identifier[self] . identifier[boundary_condition] ))
keyword[raise] identifier[ValueError] ( identifier[msg] )
identifier[n] = identifier[len] ( identifier[self] . identifier[x_list] )
identifier[mat] = identifier[numpy] . identifier[zeros] (( identifier[n] , identifier[n] ))
identifier[b] = identifier[numpy] . identifier[zeros] (( identifier[n] , literal[int] ))
identifier[x] = identifier[self] . identifier[x_list]
identifier[y] = identifier[self] . identifier[y_list]
keyword[if] identifier[n] > literal[int] :
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[n] - literal[int] ):
identifier[mat] [ identifier[i] , identifier[i] - literal[int] ]= literal[int] /( identifier[x] [ identifier[i] ]- identifier[x] [ identifier[i] - literal[int] ])
identifier[mat] [ identifier[i] , identifier[i] + literal[int] ]= literal[int] /( identifier[x] [ identifier[i] + literal[int] ]- identifier[x] [ identifier[i] ])
identifier[mat] [ identifier[i] , identifier[i] ]= literal[int] *( identifier[mat] [ identifier[i] , identifier[i] - literal[int] ]+ identifier[mat] [ identifier[i] , identifier[i] + literal[int] ])
identifier[b] [ identifier[i] , literal[int] ]= literal[int] *(( identifier[y] [ identifier[i] ]- identifier[y] [ identifier[i] - literal[int] ])/( identifier[x] [ identifier[i] ]- identifier[x] [ identifier[i] - literal[int] ])** literal[int]
+( identifier[y] [ identifier[i] + literal[int] ]- identifier[y] [ identifier[i] ])/( identifier[x] [ identifier[i] + literal[int] ]- identifier[x] [ identifier[i] ])** literal[int] )
keyword[elif] identifier[n] < literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[self] . identifier[boundary_condition] keyword[is] keyword[None] :
identifier[mat] [ literal[int] , literal[int] ]= literal[int] /( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])** literal[int]
identifier[mat] [ literal[int] , literal[int] ]=- literal[int] /( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])** literal[int]
identifier[mat] [ literal[int] , literal[int] ]= identifier[mat] [ literal[int] , literal[int] ]+ identifier[mat] [ literal[int] , literal[int] ]
identifier[b] [ literal[int] , literal[int] ]= literal[int] *(( identifier[y] [ literal[int] ]- identifier[y] [ literal[int] ])/( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])** literal[int]
-( identifier[y] [ literal[int] ]- identifier[y] [ literal[int] ])/( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])** literal[int] )
identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]= literal[int] /( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])** literal[int]
identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]=- literal[int] /( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])** literal[int]
identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]= identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]+ identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]
identifier[b] [ identifier[n] - literal[int] , literal[int] ]= literal[int] *(( identifier[y] [ identifier[n] - literal[int] ]- identifier[y] [ identifier[n] - literal[int] ])/( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])** literal[int]
-( identifier[y] [ identifier[n] - literal[int] ]- identifier[y] [ identifier[n] - literal[int] ])/( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])** literal[int] )
keyword[else] :
identifier[mat] [ literal[int] , literal[int] ]= literal[int] /( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])
identifier[mat] [ literal[int] , literal[int] ]= literal[int] /( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])
identifier[b] [ literal[int] , literal[int] ]= literal[int] *( identifier[y] [ literal[int] ]- identifier[y] [ literal[int] ])/( identifier[x] [ literal[int] ]- identifier[x] [ literal[int] ])** literal[int] - literal[int] * identifier[left_boundary_slope]
identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]= literal[int] /( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])
identifier[mat] [ identifier[n] - literal[int] , identifier[n] - literal[int] ]= literal[int] /( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])
identifier[b] [ identifier[n] - literal[int] , literal[int] ]= literal[int] *( identifier[y] [ identifier[n] - literal[int] ]- identifier[y] [ identifier[n] - literal[int] ])/( identifier[x] [ identifier[n] - literal[int] ]- identifier[x] [ identifier[n] - literal[int] ])** literal[int] + literal[int] * identifier[right_boundary_slope]
identifier[k] = identifier[numpy] . identifier[linalg] . identifier[solve] ( identifier[mat] , identifier[b] )
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[n] ):
identifier[c1] = identifier[k] [ identifier[i] - literal[int] , literal[int] ]*( identifier[x] [ identifier[i] ]- identifier[x] [ identifier[i] - literal[int] ])-( identifier[y] [ identifier[i] ]- identifier[y] [ identifier[i] - literal[int] ])
identifier[c2] =- identifier[k] [ identifier[i] , literal[int] ]*( identifier[x] [ identifier[i] ]- identifier[x] [ identifier[i] - literal[int] ])+( identifier[y] [ identifier[i] ]- identifier[y] [ identifier[i] - literal[int] ])
identifier[self] . identifier[interpolation_coefficients] . identifier[append] ([ identifier[c1] , identifier[c2] ]) | def set_interpolation_coefficients(self):
"""
computes the coefficients for the single polynomials of the spline.
"""
left_boundary_slope = 0
right_boundary_slope = 0
if isinstance(self.boundary_condition, tuple):
left_boundary_slope = self.boundary_condition[0]
right_boundary_slope = self.boundary_condition[1] # depends on [control=['if'], data=[]]
elif self.boundary_condition is None:
pass # depends on [control=['if'], data=[]]
else:
msg = 'The given object {} of type {} is not a valid condition for the border'.format(self.boundary_condition, type(self.boundary_condition))
raise ValueError(msg)
# getting the values such that we get a continuous second derivative
# by solving a system of linear equations
# setup the matrix
n = len(self.x_list)
mat = numpy.zeros((n, n))
b = numpy.zeros((n, 1))
x = self.x_list
y = self.y_list
if n > 2:
for i in range(1, n - 1):
mat[i, i - 1] = 1.0 / (x[i] - x[i - 1])
mat[i, i + 1] = 1.0 / (x[i + 1] - x[i])
mat[i, i] = 2 * (mat[i, i - 1] + mat[i, i + 1])
b[i, 0] = 3 * ((y[i] - y[i - 1]) / (x[i] - x[i - 1]) ** 2 + (y[i + 1] - y[i]) / (x[i + 1] - x[i]) ** 2) # depends on [control=['for'], data=['i']] # depends on [control=['if'], data=['n']]
elif n < 2:
raise ValueError('too less points for interpolation') # depends on [control=['if'], data=[]]
if self.boundary_condition is None: # not a knot
mat[0, 0] = 1.0 / (x[1] - x[0]) ** 2
mat[0, 2] = -1.0 / (x[2] - x[1]) ** 2
mat[0, 1] = mat[0, 0] + mat[0, 2]
b[0, 0] = 2.0 * ((y[1] - y[0]) / (x[1] - x[0]) ** 3 - (y[2] - y[1]) / (x[2] - x[1]) ** 3)
mat[n - 1, n - 3] = 1.0 / (x[n - 2] - x[n - 3]) ** 2
mat[n - 1, n - 1] = -1.0 / (x[n - 1] - x[n - 2]) ** 2
mat[n - 1, n - 2] = mat[n - 1, n - 3] + mat[n - 1, n - 1]
b[n - 1, 0] = 2.0 * ((y[n - 2] - y[n - 3]) / (x[n - 2] - x[n - 3]) ** 3 - (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]) ** 3) # depends on [control=['if'], data=[]]
else:
mat[0, 0] = 2.0 / (x[1] - x[0])
mat[0, 1] = 1.0 / (x[1] - x[0])
b[0, 0] = 3 * (y[1] - y[0]) / (x[1] - x[0]) ** 2 - 0.5 * left_boundary_slope
mat[n - 1, n - 2] = 1.0 / (x[n - 1] - x[n - 2])
mat[n - 1, n - 1] = 2.0 / (x[n - 1] - x[n - 2])
b[n - 1, 0] = 3 * (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]) ** 2 + 0.5 * right_boundary_slope
k = numpy.linalg.solve(mat, b)
for i in range(1, n):
c1 = k[i - 1, 0] * (x[i] - x[i - 1]) - (y[i] - y[i - 1])
c2 = -k[i, 0] * (x[i] - x[i - 1]) + (y[i] - y[i - 1])
self.interpolation_coefficients.append([c1, c2]) # depends on [control=['for'], data=['i']] |
def main():
"""
Example application that prints messages from the panel to the terminal.
"""
try:
# Retrieve the first USB device
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_lrr_message += handle_lrr_message
with device.open(baudrate=BAUDRATE):
while True:
time.sleep(1)
except Exception as ex:
print('Exception:', ex) | def function[main, parameter[]]:
constant[
Example application that prints messages from the panel to the terminal.
]
<ast.Try object at 0x7da1b28f4790> | keyword[def] identifier[main] ():
literal[string]
keyword[try] :
identifier[device] = identifier[AlarmDecoder] ( identifier[SerialDevice] ( identifier[interface] = identifier[SERIAL_DEVICE] ))
identifier[device] . identifier[on_lrr_message] += identifier[handle_lrr_message]
keyword[with] identifier[device] . identifier[open] ( identifier[baudrate] = identifier[BAUDRATE] ):
keyword[while] keyword[True] :
identifier[time] . identifier[sleep] ( literal[int] )
keyword[except] identifier[Exception] keyword[as] identifier[ex] :
identifier[print] ( literal[string] , identifier[ex] ) | def main():
"""
Example application that prints messages from the panel to the terminal.
"""
try:
# Retrieve the first USB device
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_lrr_message += handle_lrr_message
with device.open(baudrate=BAUDRATE):
while True:
time.sleep(1) # depends on [control=['while'], data=[]] # depends on [control=['with'], data=[]] # depends on [control=['try'], data=[]]
except Exception as ex:
print('Exception:', ex) # depends on [control=['except'], data=['ex']] |
def handle_new_selection(self, models):
"""Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:
* If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
models
* If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
selection are selected, those that are in the previous selection are deselected
:param models: The list of models that are newly selected/clicked on
"""
models = self._check_model_types(models)
if extend_selection():
already_selected_elements = models & self._selected
newly_selected_elements = models - self._selected
self._selected.difference_update(already_selected_elements)
self._selected.update(newly_selected_elements)
else:
self._selected = models
self._selected = reduce_to_parent_states(self._selected) | def function[handle_new_selection, parameter[self, models]]:
constant[Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:
* If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
models
* If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
selection are selected, those that are in the previous selection are deselected
:param models: The list of models that are newly selected/clicked on
]
variable[models] assign[=] call[name[self]._check_model_types, parameter[name[models]]]
if call[name[extend_selection], parameter[]] begin[:]
variable[already_selected_elements] assign[=] binary_operation[name[models] <ast.BitAnd object at 0x7da2590d6b60> name[self]._selected]
variable[newly_selected_elements] assign[=] binary_operation[name[models] - name[self]._selected]
call[name[self]._selected.difference_update, parameter[name[already_selected_elements]]]
call[name[self]._selected.update, parameter[name[newly_selected_elements]]]
name[self]._selected assign[=] call[name[reduce_to_parent_states], parameter[name[self]._selected]] | keyword[def] identifier[handle_new_selection] ( identifier[self] , identifier[models] ):
literal[string]
identifier[models] = identifier[self] . identifier[_check_model_types] ( identifier[models] )
keyword[if] identifier[extend_selection] ():
identifier[already_selected_elements] = identifier[models] & identifier[self] . identifier[_selected]
identifier[newly_selected_elements] = identifier[models] - identifier[self] . identifier[_selected]
identifier[self] . identifier[_selected] . identifier[difference_update] ( identifier[already_selected_elements] )
identifier[self] . identifier[_selected] . identifier[update] ( identifier[newly_selected_elements] )
keyword[else] :
identifier[self] . identifier[_selected] = identifier[models]
identifier[self] . identifier[_selected] = identifier[reduce_to_parent_states] ( identifier[self] . identifier[_selected] ) | def handle_new_selection(self, models):
"""Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:
* If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
models
* If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
selection are selected, those that are in the previous selection are deselected
:param models: The list of models that are newly selected/clicked on
"""
models = self._check_model_types(models)
if extend_selection():
already_selected_elements = models & self._selected
newly_selected_elements = models - self._selected
self._selected.difference_update(already_selected_elements)
self._selected.update(newly_selected_elements) # depends on [control=['if'], data=[]]
else:
self._selected = models
self._selected = reduce_to_parent_states(self._selected) |
def _set_area_value(self, v, load=False):
"""
Setter method for area_value, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/area_value (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_value is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_area_value() directly.
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'MissingTerminationCharacter': {'value': 0}, u'CRCAlignErrors': {'value': 1}, u'IFG': {'value': 3}, u'SymbolErrors': {'value': 2}},), is_leaf=True, yang_name="area_value", rest_name="area", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'alt-name': u'area', u'cli-expose-key-name': None, u'cli-incomplete-command': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-threshold-monitor', defining_module='brocade-threshold-monitor', yang_type='enumeration', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """area_value must be of a type compatible with enumeration""",
'defined-type': "brocade-threshold-monitor:enumeration",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'MissingTerminationCharacter': {'value': 0}, u'CRCAlignErrors': {'value': 1}, u'IFG': {'value': 3}, u'SymbolErrors': {'value': 2}},), is_leaf=True, yang_name="area_value", rest_name="area", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'alt-name': u'area', u'cli-expose-key-name': None, u'cli-incomplete-command': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-threshold-monitor', defining_module='brocade-threshold-monitor', yang_type='enumeration', is_config=True)""",
})
self.__area_value = t
if hasattr(self, '_set'):
self._set() | def function[_set_area_value, parameter[self, v, load]]:
constant[
Setter method for area_value, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/area_value (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_value is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_area_value() directly.
]
variable[parent] assign[=] call[name[getattr], parameter[name[self], constant[_parent], constant[None]]]
if <ast.BoolOp object at 0x7da207f035e0> begin[:]
<ast.Raise object at 0x7da207f03490>
if call[name[hasattr], parameter[name[v], constant[_utype]]] begin[:]
variable[v] assign[=] call[name[v]._utype, parameter[name[v]]]
<ast.Try object at 0x7da18bcc8b50>
name[self].__area_value assign[=] name[t]
if call[name[hasattr], parameter[name[self], constant[_set]]] begin[:]
call[name[self]._set, parameter[]] | keyword[def] identifier[_set_area_value] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
identifier[parent] = identifier[getattr] ( identifier[self] , literal[string] , keyword[None] )
keyword[if] identifier[parent] keyword[is] keyword[not] keyword[None] keyword[and] identifier[load] keyword[is] keyword[False] :
keyword[raise] identifier[AttributeError] ( literal[string] +
literal[string] )
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identifier[t] = identifier[YANGDynClass] ( identifier[v] , identifier[base] = identifier[RestrictedClassType] ( identifier[base_type] = identifier[unicode] , identifier[restriction_type] = literal[string] , identifier[restriction_arg] ={ literal[string] :{ literal[string] : literal[int] }, literal[string] :{ literal[string] : literal[int] }, literal[string] :{ literal[string] : literal[int] }, literal[string] :{ literal[string] : literal[int] }},), identifier[is_leaf] = keyword[True] , identifier[yang_name] = literal[string] , identifier[rest_name] = literal[string] , identifier[parent] = identifier[self] , identifier[path_helper] = identifier[self] . identifier[_path_helper] , identifier[extmethods] = identifier[self] . identifier[_extmethods] , identifier[register_paths] = keyword[True] , identifier[extensions] ={ literal[string] :{ literal[string] : literal[string] , literal[string] : keyword[None] , literal[string] : keyword[None] }}, identifier[is_keyval] = keyword[True] , identifier[namespace] = literal[string] , identifier[defining_module] = literal[string] , identifier[yang_type] = literal[string] , identifier[is_config] = keyword[True] )
keyword[except] ( identifier[TypeError] , identifier[ValueError] ):
keyword[raise] identifier[ValueError] ({
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
})
identifier[self] . identifier[__area_value] = identifier[t]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[_set] () | def _set_area_value(self, v, load=False):
"""
Setter method for area_value, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/area_value (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_value is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_area_value() directly.
"""
parent = getattr(self, '_parent', None)
if parent is not None and load is False:
raise AttributeError('Cannot set keys directly when' + ' within an instantiated list') # depends on [control=['if'], data=[]]
if hasattr(v, '_utype'):
v = v._utype(v) # depends on [control=['if'], data=[]]
try:
t = YANGDynClass(v, base=RestrictedClassType(base_type=unicode, restriction_type='dict_key', restriction_arg={u'MissingTerminationCharacter': {'value': 0}, u'CRCAlignErrors': {'value': 1}, u'IFG': {'value': 3}, u'SymbolErrors': {'value': 2}}), is_leaf=True, yang_name='area_value', rest_name='area', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'alt-name': u'area', u'cli-expose-key-name': None, u'cli-incomplete-command': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-threshold-monitor', defining_module='brocade-threshold-monitor', yang_type='enumeration', is_config=True) # depends on [control=['try'], data=[]]
except (TypeError, ValueError):
raise ValueError({'error-string': 'area_value must be of a type compatible with enumeration', 'defined-type': 'brocade-threshold-monitor:enumeration', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u\'MissingTerminationCharacter\': {\'value\': 0}, u\'CRCAlignErrors\': {\'value\': 1}, u\'IFG\': {\'value\': 3}, u\'SymbolErrors\': {\'value\': 2}},), is_leaf=True, yang_name="area_value", rest_name="area", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u\'tailf-common\': {u\'alt-name\': u\'area\', u\'cli-expose-key-name\': None, u\'cli-incomplete-command\': None}}, is_keyval=True, namespace=\'urn:brocade.com:mgmt:brocade-threshold-monitor\', defining_module=\'brocade-threshold-monitor\', yang_type=\'enumeration\', is_config=True)'}) # depends on [control=['except'], data=[]]
self.__area_value = t
if hasattr(self, '_set'):
self._set() # depends on [control=['if'], data=[]] |
def setup_user_signals(self, ):
"""Setup the signals for the user page
:returns: None
:rtype: None
:raises: None
"""
log.debug("Setting up user page signals.")
self.user_task_view_pb.clicked.connect(self.user_view_task)
self.user_prj_view_pb.clicked.connect(self.user_view_prj)
self.user_prj_add_pb.clicked.connect(self.user_add_prj)
self.user_prj_remove_pb.clicked.connect(self.user_remove_prj)
self.user_username_le.editingFinished.connect(self.user_save)
self.user_first_le.editingFinished.connect(self.user_save)
self.user_last_le.editingFinished.connect(self.user_save)
self.user_email_le.editingFinished.connect(self.user_save) | def function[setup_user_signals, parameter[self]]:
constant[Setup the signals for the user page
:returns: None
:rtype: None
:raises: None
]
call[name[log].debug, parameter[constant[Setting up user page signals.]]]
call[name[self].user_task_view_pb.clicked.connect, parameter[name[self].user_view_task]]
call[name[self].user_prj_view_pb.clicked.connect, parameter[name[self].user_view_prj]]
call[name[self].user_prj_add_pb.clicked.connect, parameter[name[self].user_add_prj]]
call[name[self].user_prj_remove_pb.clicked.connect, parameter[name[self].user_remove_prj]]
call[name[self].user_username_le.editingFinished.connect, parameter[name[self].user_save]]
call[name[self].user_first_le.editingFinished.connect, parameter[name[self].user_save]]
call[name[self].user_last_le.editingFinished.connect, parameter[name[self].user_save]]
call[name[self].user_email_le.editingFinished.connect, parameter[name[self].user_save]] | keyword[def] identifier[setup_user_signals] ( identifier[self] ,):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[self] . identifier[user_task_view_pb] . identifier[clicked] . identifier[connect] ( identifier[self] . identifier[user_view_task] )
identifier[self] . identifier[user_prj_view_pb] . identifier[clicked] . identifier[connect] ( identifier[self] . identifier[user_view_prj] )
identifier[self] . identifier[user_prj_add_pb] . identifier[clicked] . identifier[connect] ( identifier[self] . identifier[user_add_prj] )
identifier[self] . identifier[user_prj_remove_pb] . identifier[clicked] . identifier[connect] ( identifier[self] . identifier[user_remove_prj] )
identifier[self] . identifier[user_username_le] . identifier[editingFinished] . identifier[connect] ( identifier[self] . identifier[user_save] )
identifier[self] . identifier[user_first_le] . identifier[editingFinished] . identifier[connect] ( identifier[self] . identifier[user_save] )
identifier[self] . identifier[user_last_le] . identifier[editingFinished] . identifier[connect] ( identifier[self] . identifier[user_save] )
identifier[self] . identifier[user_email_le] . identifier[editingFinished] . identifier[connect] ( identifier[self] . identifier[user_save] ) | def setup_user_signals(self):
"""Setup the signals for the user page
:returns: None
:rtype: None
:raises: None
"""
log.debug('Setting up user page signals.')
self.user_task_view_pb.clicked.connect(self.user_view_task)
self.user_prj_view_pb.clicked.connect(self.user_view_prj)
self.user_prj_add_pb.clicked.connect(self.user_add_prj)
self.user_prj_remove_pb.clicked.connect(self.user_remove_prj)
self.user_username_le.editingFinished.connect(self.user_save)
self.user_first_le.editingFinished.connect(self.user_save)
self.user_last_le.editingFinished.connect(self.user_save)
self.user_email_le.editingFinished.connect(self.user_save) |
def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
"""
import glob
pattern = self.fname + '_*' + self.ext
for fname in glob.glob1(self.dpath, pattern):
fpath = join(self.dpath, fname)
yield fpath | def function[existing_versions, parameter[self]]:
constant[
Returns data with different cfgstr values that were previously computed
with this cacher.
]
import module[glob]
variable[pattern] assign[=] binary_operation[binary_operation[name[self].fname + constant[_*]] + name[self].ext]
for taget[name[fname]] in starred[call[name[glob].glob1, parameter[name[self].dpath, name[pattern]]]] begin[:]
variable[fpath] assign[=] call[name[join], parameter[name[self].dpath, name[fname]]]
<ast.Yield object at 0x7da1b24ada20> | keyword[def] identifier[existing_versions] ( identifier[self] ):
literal[string]
keyword[import] identifier[glob]
identifier[pattern] = identifier[self] . identifier[fname] + literal[string] + identifier[self] . identifier[ext]
keyword[for] identifier[fname] keyword[in] identifier[glob] . identifier[glob1] ( identifier[self] . identifier[dpath] , identifier[pattern] ):
identifier[fpath] = identifier[join] ( identifier[self] . identifier[dpath] , identifier[fname] )
keyword[yield] identifier[fpath] | def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
"""
import glob
pattern = self.fname + '_*' + self.ext
for fname in glob.glob1(self.dpath, pattern):
fpath = join(self.dpath, fname)
yield fpath # depends on [control=['for'], data=['fname']] |
def set_dst_mode(self, index, dst):
'''Enable/disable daylight savings
Values: True, False
'''
body = {
'selection': {
'selectionType': 'thermostats',
'selectionMatch': self.thermostats[index]['identifier']},
'thermostat': {
'location': {
'isDaylightSaving': dst}}}
log_msg_action = 'set dst mode'
return self.make_request(body, log_msg_action) | def function[set_dst_mode, parameter[self, index, dst]]:
constant[Enable/disable daylight savings
Values: True, False
]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b0354a30>, <ast.Constant object at 0x7da1b0354040>], [<ast.Dict object at 0x7da1b0354070>, <ast.Dict object at 0x7da1b0354df0>]]
variable[log_msg_action] assign[=] constant[set dst mode]
return[call[name[self].make_request, parameter[name[body], name[log_msg_action]]]] | keyword[def] identifier[set_dst_mode] ( identifier[self] , identifier[index] , identifier[dst] ):
literal[string]
identifier[body] ={
literal[string] :{
literal[string] : literal[string] ,
literal[string] : identifier[self] . identifier[thermostats] [ identifier[index] ][ literal[string] ]},
literal[string] :{
literal[string] :{
literal[string] : identifier[dst] }}}
identifier[log_msg_action] = literal[string]
keyword[return] identifier[self] . identifier[make_request] ( identifier[body] , identifier[log_msg_action] ) | def set_dst_mode(self, index, dst):
"""Enable/disable daylight savings
Values: True, False
"""
body = {'selection': {'selectionType': 'thermostats', 'selectionMatch': self.thermostats[index]['identifier']}, 'thermostat': {'location': {'isDaylightSaving': dst}}}
log_msg_action = 'set dst mode'
return self.make_request(body, log_msg_action) |
def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = reader.ReadUInt32()
self.Index = reader.ReadUInt32()
self.ConsensusData = reader.ReadUInt64()
self.NextConsensus = reader.ReadUInt160() | def function[DeserializeUnsigned, parameter[self, reader]]:
constant[
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
]
name[self].Version assign[=] call[name[reader].ReadUInt32, parameter[]]
name[self].PrevHash assign[=] call[name[reader].ReadUInt256, parameter[]]
name[self].MerkleRoot assign[=] call[name[reader].ReadUInt256, parameter[]]
name[self].Timestamp assign[=] call[name[reader].ReadUInt32, parameter[]]
name[self].Index assign[=] call[name[reader].ReadUInt32, parameter[]]
name[self].ConsensusData assign[=] call[name[reader].ReadUInt64, parameter[]]
name[self].NextConsensus assign[=] call[name[reader].ReadUInt160, parameter[]] | keyword[def] identifier[DeserializeUnsigned] ( identifier[self] , identifier[reader] ):
literal[string]
identifier[self] . identifier[Version] = identifier[reader] . identifier[ReadUInt32] ()
identifier[self] . identifier[PrevHash] = identifier[reader] . identifier[ReadUInt256] ()
identifier[self] . identifier[MerkleRoot] = identifier[reader] . identifier[ReadUInt256] ()
identifier[self] . identifier[Timestamp] = identifier[reader] . identifier[ReadUInt32] ()
identifier[self] . identifier[Index] = identifier[reader] . identifier[ReadUInt32] ()
identifier[self] . identifier[ConsensusData] = identifier[reader] . identifier[ReadUInt64] ()
identifier[self] . identifier[NextConsensus] = identifier[reader] . identifier[ReadUInt160] () | def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = reader.ReadUInt32()
self.Index = reader.ReadUInt32()
self.ConsensusData = reader.ReadUInt64()
self.NextConsensus = reader.ReadUInt160() |
def from_job_desc(cls, warm_start_config):
"""Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fields:
* "type": Type of warm start tuner, currently two supported types - "IdenticalDataAndAlgorithm" and
"TransferLearning".
* "parents": List of tuning job names from which the warm start should be done.
Returns:
sagemaker.tuner.WarmStartConfig: De-serialized instance of WarmStartConfig containing the type and parents
provided as part of ``warm_start_config``.
Examples:
>>> warm_start_config = WarmStartConfig.from_job_desc(warm_start_config={
>>> "WarmStartType":"TransferLearning",
>>> "ParentHyperParameterTuningJobs": [
>>> {'HyperParameterTuningJobName': "p1"},
>>> {'HyperParameterTuningJobName': "p2"},
>>> ]
>>>})
>>> warm_start_config.type
"TransferLearning"
>>> warm_start_config.parents
["p1","p2"]
"""
if not warm_start_config or \
WARM_START_TYPE not in warm_start_config or \
PARENT_HYPERPARAMETER_TUNING_JOBS not in warm_start_config:
return None
parents = []
for parent in warm_start_config[PARENT_HYPERPARAMETER_TUNING_JOBS]:
parents.append(parent[HYPERPARAMETER_TUNING_JOB_NAME])
return cls(warm_start_type=WarmStartTypes(warm_start_config[WARM_START_TYPE]),
parents=parents) | def function[from_job_desc, parameter[cls, warm_start_config]]:
constant[Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fields:
* "type": Type of warm start tuner, currently two supported types - "IdenticalDataAndAlgorithm" and
"TransferLearning".
* "parents": List of tuning job names from which the warm start should be done.
Returns:
sagemaker.tuner.WarmStartConfig: De-serialized instance of WarmStartConfig containing the type and parents
provided as part of ``warm_start_config``.
Examples:
>>> warm_start_config = WarmStartConfig.from_job_desc(warm_start_config={
>>> "WarmStartType":"TransferLearning",
>>> "ParentHyperParameterTuningJobs": [
>>> {'HyperParameterTuningJobName': "p1"},
>>> {'HyperParameterTuningJobName': "p2"},
>>> ]
>>>})
>>> warm_start_config.type
"TransferLearning"
>>> warm_start_config.parents
["p1","p2"]
]
if <ast.BoolOp object at 0x7da1b1c183d0> begin[:]
return[constant[None]]
variable[parents] assign[=] list[[]]
for taget[name[parent]] in starred[call[name[warm_start_config]][name[PARENT_HYPERPARAMETER_TUNING_JOBS]]] begin[:]
call[name[parents].append, parameter[call[name[parent]][name[HYPERPARAMETER_TUNING_JOB_NAME]]]]
return[call[name[cls], parameter[]]] | keyword[def] identifier[from_job_desc] ( identifier[cls] , identifier[warm_start_config] ):
literal[string]
keyword[if] keyword[not] identifier[warm_start_config] keyword[or] identifier[WARM_START_TYPE] keyword[not] keyword[in] identifier[warm_start_config] keyword[or] identifier[PARENT_HYPERPARAMETER_TUNING_JOBS] keyword[not] keyword[in] identifier[warm_start_config] :
keyword[return] keyword[None]
identifier[parents] =[]
keyword[for] identifier[parent] keyword[in] identifier[warm_start_config] [ identifier[PARENT_HYPERPARAMETER_TUNING_JOBS] ]:
identifier[parents] . identifier[append] ( identifier[parent] [ identifier[HYPERPARAMETER_TUNING_JOB_NAME] ])
keyword[return] identifier[cls] ( identifier[warm_start_type] = identifier[WarmStartTypes] ( identifier[warm_start_config] [ identifier[WARM_START_TYPE] ]),
identifier[parents] = identifier[parents] ) | def from_job_desc(cls, warm_start_config):
"""Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fields:
* "type": Type of warm start tuner, currently two supported types - "IdenticalDataAndAlgorithm" and
"TransferLearning".
* "parents": List of tuning job names from which the warm start should be done.
Returns:
sagemaker.tuner.WarmStartConfig: De-serialized instance of WarmStartConfig containing the type and parents
provided as part of ``warm_start_config``.
Examples:
>>> warm_start_config = WarmStartConfig.from_job_desc(warm_start_config={
>>> "WarmStartType":"TransferLearning",
>>> "ParentHyperParameterTuningJobs": [
>>> {'HyperParameterTuningJobName': "p1"},
>>> {'HyperParameterTuningJobName': "p2"},
>>> ]
>>>})
>>> warm_start_config.type
"TransferLearning"
>>> warm_start_config.parents
["p1","p2"]
"""
if not warm_start_config or WARM_START_TYPE not in warm_start_config or PARENT_HYPERPARAMETER_TUNING_JOBS not in warm_start_config:
return None # depends on [control=['if'], data=[]]
parents = []
for parent in warm_start_config[PARENT_HYPERPARAMETER_TUNING_JOBS]:
parents.append(parent[HYPERPARAMETER_TUNING_JOB_NAME]) # depends on [control=['for'], data=['parent']]
return cls(warm_start_type=WarmStartTypes(warm_start_config[WARM_START_TYPE]), parents=parents) |
def to_files(self, resource, directory):
"""
Dumps the given resource and all resources linked to it into a set of
representation files in the given directory.
"""
collections = self.__collect(resource)
for (mb_cls, coll) in iteritems_(collections):
fn = get_write_collection_path(mb_cls,
self.__content_type,
directory=directory)
with open_text(os.path.join(directory, fn)) as strm:
dump_resource(coll, strm, content_type=self.__content_type) | def function[to_files, parameter[self, resource, directory]]:
constant[
Dumps the given resource and all resources linked to it into a set of
representation files in the given directory.
]
variable[collections] assign[=] call[name[self].__collect, parameter[name[resource]]]
for taget[tuple[[<ast.Name object at 0x7da1b287c9d0>, <ast.Name object at 0x7da1b287c070>]]] in starred[call[name[iteritems_], parameter[name[collections]]]] begin[:]
variable[fn] assign[=] call[name[get_write_collection_path], parameter[name[mb_cls], name[self].__content_type]]
with call[name[open_text], parameter[call[name[os].path.join, parameter[name[directory], name[fn]]]]] begin[:]
call[name[dump_resource], parameter[name[coll], name[strm]]] | keyword[def] identifier[to_files] ( identifier[self] , identifier[resource] , identifier[directory] ):
literal[string]
identifier[collections] = identifier[self] . identifier[__collect] ( identifier[resource] )
keyword[for] ( identifier[mb_cls] , identifier[coll] ) keyword[in] identifier[iteritems_] ( identifier[collections] ):
identifier[fn] = identifier[get_write_collection_path] ( identifier[mb_cls] ,
identifier[self] . identifier[__content_type] ,
identifier[directory] = identifier[directory] )
keyword[with] identifier[open_text] ( identifier[os] . identifier[path] . identifier[join] ( identifier[directory] , identifier[fn] )) keyword[as] identifier[strm] :
identifier[dump_resource] ( identifier[coll] , identifier[strm] , identifier[content_type] = identifier[self] . identifier[__content_type] ) | def to_files(self, resource, directory):
"""
Dumps the given resource and all resources linked to it into a set of
representation files in the given directory.
"""
collections = self.__collect(resource)
for (mb_cls, coll) in iteritems_(collections):
fn = get_write_collection_path(mb_cls, self.__content_type, directory=directory)
with open_text(os.path.join(directory, fn)) as strm:
dump_resource(coll, strm, content_type=self.__content_type) # depends on [control=['with'], data=['strm']] # depends on [control=['for'], data=[]] |
def stop_app(self, callback_function_param=False):
""" Stops the current running app on the Chromecast. """
self.logger.info("Receiver:Stopping current app '%s'", self.app_id)
return self.send_message(
{MESSAGE_TYPE: 'STOP'},
inc_session_id=True, callback_function=callback_function_param) | def function[stop_app, parameter[self, callback_function_param]]:
constant[ Stops the current running app on the Chromecast. ]
call[name[self].logger.info, parameter[constant[Receiver:Stopping current app '%s'], name[self].app_id]]
return[call[name[self].send_message, parameter[dictionary[[<ast.Name object at 0x7da20c7cafb0>], [<ast.Constant object at 0x7da20c7c96f0>]]]]] | keyword[def] identifier[stop_app] ( identifier[self] , identifier[callback_function_param] = keyword[False] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[self] . identifier[app_id] )
keyword[return] identifier[self] . identifier[send_message] (
{ identifier[MESSAGE_TYPE] : literal[string] },
identifier[inc_session_id] = keyword[True] , identifier[callback_function] = identifier[callback_function_param] ) | def stop_app(self, callback_function_param=False):
""" Stops the current running app on the Chromecast. """
self.logger.info("Receiver:Stopping current app '%s'", self.app_id)
return self.send_message({MESSAGE_TYPE: 'STOP'}, inc_session_id=True, callback_function=callback_function_param) |
def schema(tg):
"""
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
"""
tables = {}
for tname, table in tg.tabledict.items():
t = TableSpec.from_table_metadata(table)
tables[t.name] = t
for at in t.many_to_many.values():
tables[at.name] = at
# We must determine the order in which tables must be created!
ordered = OrderedDict()
i = 0
# We loop through the tables repeatedly, and whenever we find one, which has all
# referenced tables already in ordered, we move it from tables to ordered.
while tables and i < 100:
i += 1
for table in list(tables.keys()):
if all((ref[1] in ordered) or ref[1] == table for ref in tables[table].foreign_keys):
# All referenced tables are already created (or self-referential).
ordered[table] = tables.pop(table)
break
if tables: # pragma: no cover
raise ValueError('there seem to be cyclic dependencies between the tables')
return list(ordered.values()) | def function[schema, parameter[tg]]:
constant[
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
]
variable[tables] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1afe50730>, <ast.Name object at 0x7da1afe517e0>]]] in starred[call[name[tg].tabledict.items, parameter[]]] begin[:]
variable[t] assign[=] call[name[TableSpec].from_table_metadata, parameter[name[table]]]
call[name[tables]][name[t].name] assign[=] name[t]
for taget[name[at]] in starred[call[name[t].many_to_many.values, parameter[]]] begin[:]
call[name[tables]][name[at].name] assign[=] name[at]
variable[ordered] assign[=] call[name[OrderedDict], parameter[]]
variable[i] assign[=] constant[0]
while <ast.BoolOp object at 0x7da1afe51240> begin[:]
<ast.AugAssign object at 0x7da1affe7ee0>
for taget[name[table]] in starred[call[name[list], parameter[call[name[tables].keys, parameter[]]]]] begin[:]
if call[name[all], parameter[<ast.GeneratorExp object at 0x7da1affe68f0>]] begin[:]
call[name[ordered]][name[table]] assign[=] call[name[tables].pop, parameter[name[table]]]
break
if name[tables] begin[:]
<ast.Raise object at 0x7da1affe6aa0>
return[call[name[list], parameter[call[name[ordered].values, parameter[]]]]] | keyword[def] identifier[schema] ( identifier[tg] ):
literal[string]
identifier[tables] ={}
keyword[for] identifier[tname] , identifier[table] keyword[in] identifier[tg] . identifier[tabledict] . identifier[items] ():
identifier[t] = identifier[TableSpec] . identifier[from_table_metadata] ( identifier[table] )
identifier[tables] [ identifier[t] . identifier[name] ]= identifier[t]
keyword[for] identifier[at] keyword[in] identifier[t] . identifier[many_to_many] . identifier[values] ():
identifier[tables] [ identifier[at] . identifier[name] ]= identifier[at]
identifier[ordered] = identifier[OrderedDict] ()
identifier[i] = literal[int]
keyword[while] identifier[tables] keyword[and] identifier[i] < literal[int] :
identifier[i] += literal[int]
keyword[for] identifier[table] keyword[in] identifier[list] ( identifier[tables] . identifier[keys] ()):
keyword[if] identifier[all] (( identifier[ref] [ literal[int] ] keyword[in] identifier[ordered] ) keyword[or] identifier[ref] [ literal[int] ]== identifier[table] keyword[for] identifier[ref] keyword[in] identifier[tables] [ identifier[table] ]. identifier[foreign_keys] ):
identifier[ordered] [ identifier[table] ]= identifier[tables] . identifier[pop] ( identifier[table] )
keyword[break]
keyword[if] identifier[tables] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[list] ( identifier[ordered] . identifier[values] ()) | def schema(tg):
"""
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
"""
tables = {}
for (tname, table) in tg.tabledict.items():
t = TableSpec.from_table_metadata(table)
tables[t.name] = t
for at in t.many_to_many.values():
tables[at.name] = at # depends on [control=['for'], data=['at']] # depends on [control=['for'], data=[]]
# We must determine the order in which tables must be created!
ordered = OrderedDict()
i = 0
# We loop through the tables repeatedly, and whenever we find one, which has all
# referenced tables already in ordered, we move it from tables to ordered.
while tables and i < 100:
i += 1
for table in list(tables.keys()):
if all((ref[1] in ordered or ref[1] == table for ref in tables[table].foreign_keys)):
# All referenced tables are already created (or self-referential).
ordered[table] = tables.pop(table)
break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['table']] # depends on [control=['while'], data=[]]
if tables: # pragma: no cover
raise ValueError('there seem to be cyclic dependencies between the tables') # depends on [control=['if'], data=[]]
return list(ordered.values()) |
def get_height_for_line(self, lineno, width):
"""
Return the height that a given line would need if it is rendered in a
space with the given width.
"""
try:
return self._line_heights[lineno, width]
except KeyError:
text = token_list_to_text(self.get_line(lineno))
result = self.get_height_for_text(text, width)
# Cache and return
self._line_heights[lineno, width] = result
return result | def function[get_height_for_line, parameter[self, lineno, width]]:
constant[
Return the height that a given line would need if it is rendered in a
space with the given width.
]
<ast.Try object at 0x7da204345990> | keyword[def] identifier[get_height_for_line] ( identifier[self] , identifier[lineno] , identifier[width] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_line_heights] [ identifier[lineno] , identifier[width] ]
keyword[except] identifier[KeyError] :
identifier[text] = identifier[token_list_to_text] ( identifier[self] . identifier[get_line] ( identifier[lineno] ))
identifier[result] = identifier[self] . identifier[get_height_for_text] ( identifier[text] , identifier[width] )
identifier[self] . identifier[_line_heights] [ identifier[lineno] , identifier[width] ]= identifier[result]
keyword[return] identifier[result] | def get_height_for_line(self, lineno, width):
"""
Return the height that a given line would need if it is rendered in a
space with the given width.
"""
try:
return self._line_heights[lineno, width] # depends on [control=['try'], data=[]]
except KeyError:
text = token_list_to_text(self.get_line(lineno))
result = self.get_height_for_text(text, width)
# Cache and return
self._line_heights[lineno, width] = result
return result # depends on [control=['except'], data=[]] |
def _send_update_port_statuses(self, port_ids, status):
"""Sends update notifications to set the operational status of the
list of router ports provided. To make each notification doesn't exceed
the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH
port ids.
:param port_ids: List of ports to update the status
:param status: operational status to update
(ex: bc.constants.PORT_STATUS_ACTIVE)
"""
if not port_ids:
return
MAX_PORTS_IN_BATCH = 50
list_chunks_ports = [port_ids[i:i + MAX_PORTS_IN_BATCH]
for i in six.moves.range(0, len(port_ids), MAX_PORTS_IN_BATCH)]
for chunk_ports in list_chunks_ports:
self.plugin_rpc.send_update_port_statuses(self.context,
chunk_ports, status) | def function[_send_update_port_statuses, parameter[self, port_ids, status]]:
constant[Sends update notifications to set the operational status of the
list of router ports provided. To make each notification doesn't exceed
the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH
port ids.
:param port_ids: List of ports to update the status
:param status: operational status to update
(ex: bc.constants.PORT_STATUS_ACTIVE)
]
if <ast.UnaryOp object at 0x7da1b1bab610> begin[:]
return[None]
variable[MAX_PORTS_IN_BATCH] assign[=] constant[50]
variable[list_chunks_ports] assign[=] <ast.ListComp object at 0x7da1b1ba9b10>
for taget[name[chunk_ports]] in starred[name[list_chunks_ports]] begin[:]
call[name[self].plugin_rpc.send_update_port_statuses, parameter[name[self].context, name[chunk_ports], name[status]]] | keyword[def] identifier[_send_update_port_statuses] ( identifier[self] , identifier[port_ids] , identifier[status] ):
literal[string]
keyword[if] keyword[not] identifier[port_ids] :
keyword[return]
identifier[MAX_PORTS_IN_BATCH] = literal[int]
identifier[list_chunks_ports] =[ identifier[port_ids] [ identifier[i] : identifier[i] + identifier[MAX_PORTS_IN_BATCH] ]
keyword[for] identifier[i] keyword[in] identifier[six] . identifier[moves] . identifier[range] ( literal[int] , identifier[len] ( identifier[port_ids] ), identifier[MAX_PORTS_IN_BATCH] )]
keyword[for] identifier[chunk_ports] keyword[in] identifier[list_chunks_ports] :
identifier[self] . identifier[plugin_rpc] . identifier[send_update_port_statuses] ( identifier[self] . identifier[context] ,
identifier[chunk_ports] , identifier[status] ) | def _send_update_port_statuses(self, port_ids, status):
"""Sends update notifications to set the operational status of the
list of router ports provided. To make each notification doesn't exceed
the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH
port ids.
:param port_ids: List of ports to update the status
:param status: operational status to update
(ex: bc.constants.PORT_STATUS_ACTIVE)
"""
if not port_ids:
return # depends on [control=['if'], data=[]]
MAX_PORTS_IN_BATCH = 50
list_chunks_ports = [port_ids[i:i + MAX_PORTS_IN_BATCH] for i in six.moves.range(0, len(port_ids), MAX_PORTS_IN_BATCH)]
for chunk_ports in list_chunks_ports:
self.plugin_rpc.send_update_port_statuses(self.context, chunk_ports, status) # depends on [control=['for'], data=['chunk_ports']] |
def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None,
raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to catch
:param tries: number of tries to retry the function
:param wait: time to wait between executions in seconds
:param handler: function to check if output is valid, must return bool
:param raised_exception: default is ReusablesError
:param raised_message: message to pass to raised exception
"""
def func_wrapper(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = (raised_message if raised_message
else "Max retries exceeded for function '{func}'")
if not raised_message:
msg = _add_args(msg, *args, **kwargs)
try:
result = func(*args, **kwargs)
except exceptions:
if tries:
if wait:
time.sleep(wait)
return retry_it(exceptions=exceptions, tries=tries-1,
handler=handler,
wait=wait)(func)(*args, **kwargs)
if raised_exception:
exc = raised_exception(msg.format(func=func.__name__,
args=args, kwargs=kwargs))
exc.__cause__ = None
raise exc
else:
if handler:
if not handler(result):
return retry_it(exceptions=exceptions, tries=tries - 1,
handler=handler,
wait=wait)(func)(*args, **kwargs)
return result
return wrapper
return func_wrapper | def function[retry_it, parameter[exceptions, tries, wait, handler, raised_exception, raised_message]]:
constant[
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to catch
:param tries: number of tries to retry the function
:param wait: time to wait between executions in seconds
:param handler: function to check if output is valid, must return bool
:param raised_exception: default is ReusablesError
:param raised_message: message to pass to raised exception
]
def function[func_wrapper, parameter[func]]:
def function[wrapper, parameter[]]:
variable[msg] assign[=] <ast.IfExp object at 0x7da20c76c1c0>
if <ast.UnaryOp object at 0x7da20c76d2d0> begin[:]
variable[msg] assign[=] call[name[_add_args], parameter[name[msg], <ast.Starred object at 0x7da20c76f280>]]
<ast.Try object at 0x7da20c76f7c0>
return[name[wrapper]]
return[name[func_wrapper]] | keyword[def] identifier[retry_it] ( identifier[exceptions] =( identifier[Exception] ,), identifier[tries] = literal[int] , identifier[wait] = literal[int] , identifier[handler] = keyword[None] ,
identifier[raised_exception] = identifier[ReusablesError] , identifier[raised_message] = keyword[None] ):
literal[string]
keyword[def] identifier[func_wrapper] ( identifier[func] ):
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[msg] =( identifier[raised_message] keyword[if] identifier[raised_message]
keyword[else] literal[string] )
keyword[if] keyword[not] identifier[raised_message] :
identifier[msg] = identifier[_add_args] ( identifier[msg] ,* identifier[args] ,** identifier[kwargs] )
keyword[try] :
identifier[result] = identifier[func] (* identifier[args] ,** identifier[kwargs] )
keyword[except] identifier[exceptions] :
keyword[if] identifier[tries] :
keyword[if] identifier[wait] :
identifier[time] . identifier[sleep] ( identifier[wait] )
keyword[return] identifier[retry_it] ( identifier[exceptions] = identifier[exceptions] , identifier[tries] = identifier[tries] - literal[int] ,
identifier[handler] = identifier[handler] ,
identifier[wait] = identifier[wait] )( identifier[func] )(* identifier[args] ,** identifier[kwargs] )
keyword[if] identifier[raised_exception] :
identifier[exc] = identifier[raised_exception] ( identifier[msg] . identifier[format] ( identifier[func] = identifier[func] . identifier[__name__] ,
identifier[args] = identifier[args] , identifier[kwargs] = identifier[kwargs] ))
identifier[exc] . identifier[__cause__] = keyword[None]
keyword[raise] identifier[exc]
keyword[else] :
keyword[if] identifier[handler] :
keyword[if] keyword[not] identifier[handler] ( identifier[result] ):
keyword[return] identifier[retry_it] ( identifier[exceptions] = identifier[exceptions] , identifier[tries] = identifier[tries] - literal[int] ,
identifier[handler] = identifier[handler] ,
identifier[wait] = identifier[wait] )( identifier[func] )(* identifier[args] ,** identifier[kwargs] )
keyword[return] identifier[result]
keyword[return] identifier[wrapper]
keyword[return] identifier[func_wrapper] | def retry_it(exceptions=(Exception,), tries=10, wait=0, handler=None, raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to catch
:param tries: number of tries to retry the function
:param wait: time to wait between executions in seconds
:param handler: function to check if output is valid, must return bool
:param raised_exception: default is ReusablesError
:param raised_message: message to pass to raised exception
"""
def func_wrapper(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = raised_message if raised_message else "Max retries exceeded for function '{func}'"
if not raised_message:
msg = _add_args(msg, *args, **kwargs) # depends on [control=['if'], data=[]]
try:
result = func(*args, **kwargs) # depends on [control=['try'], data=[]]
except exceptions:
if tries:
if wait:
time.sleep(wait) # depends on [control=['if'], data=[]]
return retry_it(exceptions=exceptions, tries=tries - 1, handler=handler, wait=wait)(func)(*args, **kwargs) # depends on [control=['if'], data=[]]
if raised_exception:
exc = raised_exception(msg.format(func=func.__name__, args=args, kwargs=kwargs))
exc.__cause__ = None
raise exc # depends on [control=['if'], data=[]] # depends on [control=['except'], data=[]]
else:
if handler:
if not handler(result):
return retry_it(exceptions=exceptions, tries=tries - 1, handler=handler, wait=wait)(func)(*args, **kwargs) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
return result
return wrapper
return func_wrapper |
def get_select_sql(self):
"""
Gets the SELECT field portion for the field without the alias. If the field
has a table, it will be included here like table.field
:return: Gets the SELECT field portion for the field without the alias
:rtype: str
"""
if self.table:
return '{0}.{1}'.format(self.table.get_identifier(), self.name)
return '{0}'.format(self.name) | def function[get_select_sql, parameter[self]]:
constant[
Gets the SELECT field portion for the field without the alias. If the field
has a table, it will be included here like table.field
:return: Gets the SELECT field portion for the field without the alias
:rtype: str
]
if name[self].table begin[:]
return[call[constant[{0}.{1}].format, parameter[call[name[self].table.get_identifier, parameter[]], name[self].name]]]
return[call[constant[{0}].format, parameter[name[self].name]]] | keyword[def] identifier[get_select_sql] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[table] :
keyword[return] literal[string] . identifier[format] ( identifier[self] . identifier[table] . identifier[get_identifier] (), identifier[self] . identifier[name] )
keyword[return] literal[string] . identifier[format] ( identifier[self] . identifier[name] ) | def get_select_sql(self):
"""
Gets the SELECT field portion for the field without the alias. If the field
has a table, it will be included here like table.field
:return: Gets the SELECT field portion for the field without the alias
:rtype: str
"""
if self.table:
return '{0}.{1}'.format(self.table.get_identifier(), self.name) # depends on [control=['if'], data=[]]
return '{0}'.format(self.name) |
def get_data(datastore, path):
'''
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, / separated
:type path: ``list``, ``str`` OR ``tuple``
:return: The network configuration at that tree
:rtype: ``dict``
.. code-block:: bash
salt cisco-nso cisconso.get_data running 'devices/ex0'
'''
if isinstance(path, six.string_types):
path = '/'.split(path)
return _proxy_cmd('get_data', datastore, path) | def function[get_data, parameter[datastore, path]]:
constant[
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, / separated
:type path: ``list``, ``str`` OR ``tuple``
:return: The network configuration at that tree
:rtype: ``dict``
.. code-block:: bash
salt cisco-nso cisconso.get_data running 'devices/ex0'
]
if call[name[isinstance], parameter[name[path], name[six].string_types]] begin[:]
variable[path] assign[=] call[constant[/].split, parameter[name[path]]]
return[call[name[_proxy_cmd], parameter[constant[get_data], name[datastore], name[path]]]] | keyword[def] identifier[get_data] ( identifier[datastore] , identifier[path] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[path] , identifier[six] . identifier[string_types] ):
identifier[path] = literal[string] . identifier[split] ( identifier[path] )
keyword[return] identifier[_proxy_cmd] ( literal[string] , identifier[datastore] , identifier[path] ) | def get_data(datastore, path):
"""
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, / separated
:type path: ``list``, ``str`` OR ``tuple``
:return: The network configuration at that tree
:rtype: ``dict``
.. code-block:: bash
salt cisco-nso cisconso.get_data running 'devices/ex0'
"""
if isinstance(path, six.string_types):
path = '/'.split(path) # depends on [control=['if'], data=[]]
return _proxy_cmd('get_data', datastore, path) |
def CoerceValue(value, value_type):
"""Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
An item of the Python type appropriate to the given value_type. Strings
are also converted to Unicode using UTF-8 encoding if necessary.
If a tuple is given, it should be in one of the following forms:
- (value, formatted value)
- (value, formatted value, custom properties)
where the formatted value is a string, and custom properties is a
dictionary of the custom properties for this cell.
To specify custom properties without specifying formatted value, one can
pass None as the formatted value.
One can also have a null-valued cell with formatted value and/or custom
properties by specifying None for the value.
This method ignores the custom properties except for checking that it is a
dictionary. The custom properties are handled in the ToJSon and ToJSCode
methods.
The real type of the given value is not strictly checked. For example,
any type can be used for string - as we simply take its str( ) and for
boolean value we just check "if value".
Examples:
CoerceValue(None, "string") returns None
CoerceValue((5, "5$"), "number") returns (5, "5$")
CoerceValue(100, "string") returns "100"
CoerceValue(0, "boolean") returns False
Raises:
DataTableException: The value and type did not match in a not-recoverable
way, for example given value 'abc' for type 'number'.
"""
if isinstance(value, tuple):
# In case of a tuple, we run the same function on the value itself and
# add the formatted value.
if (len(value) not in [2, 3] or
(len(value) == 3 and not isinstance(value[2], dict))):
raise DataTableException("Wrong format for value and formatting - %s." %
str(value))
if not isinstance(value[1], six.string_types + (type(None),)):
raise DataTableException("Formatted value is not string, given %s." %
type(value[1]))
js_value = DataTable.CoerceValue(value[0], value_type)
return (js_value,) + value[1:]
t_value = type(value)
if value is None:
return value
if value_type == "boolean":
return bool(value)
elif value_type == "number":
if isinstance(value, six.integer_types + (float,)):
return value
raise DataTableException("Wrong type %s when expected number" % t_value)
elif value_type == "string":
if isinstance(value, six.text_type):
return value
if isinstance(value, bytes):
return six.text_type(value, encoding="utf-8")
else:
return six.text_type(value)
elif value_type == "date":
if isinstance(value, datetime.datetime):
return datetime.date(value.year, value.month, value.day)
elif isinstance(value, datetime.date):
return value
else:
raise DataTableException("Wrong type %s when expected date" % t_value)
elif value_type == "timeofday":
if isinstance(value, datetime.datetime):
return datetime.time(value.hour, value.minute, value.second)
elif isinstance(value, datetime.time):
return value
else:
raise DataTableException("Wrong type %s when expected time" % t_value)
elif value_type == "datetime":
if isinstance(value, datetime.datetime):
return value
else:
raise DataTableException("Wrong type %s when expected datetime" %
t_value)
# If we got here, it means the given value_type was not one of the
# supported types.
raise DataTableException("Unsupported type %s" % value_type) | def function[CoerceValue, parameter[value, value_type]]:
constant[Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
An item of the Python type appropriate to the given value_type. Strings
are also converted to Unicode using UTF-8 encoding if necessary.
If a tuple is given, it should be in one of the following forms:
- (value, formatted value)
- (value, formatted value, custom properties)
where the formatted value is a string, and custom properties is a
dictionary of the custom properties for this cell.
To specify custom properties without specifying formatted value, one can
pass None as the formatted value.
One can also have a null-valued cell with formatted value and/or custom
properties by specifying None for the value.
This method ignores the custom properties except for checking that it is a
dictionary. The custom properties are handled in the ToJSon and ToJSCode
methods.
The real type of the given value is not strictly checked. For example,
any type can be used for string - as we simply take its str( ) and for
boolean value we just check "if value".
Examples:
CoerceValue(None, "string") returns None
CoerceValue((5, "5$"), "number") returns (5, "5$")
CoerceValue(100, "string") returns "100"
CoerceValue(0, "boolean") returns False
Raises:
DataTableException: The value and type did not match in a not-recoverable
way, for example given value 'abc' for type 'number'.
]
if call[name[isinstance], parameter[name[value], name[tuple]]] begin[:]
if <ast.BoolOp object at 0x7da20c6e51e0> begin[:]
<ast.Raise object at 0x7da20c6e6c20>
if <ast.UnaryOp object at 0x7da20c6e7ee0> begin[:]
<ast.Raise object at 0x7da20c6e73a0>
variable[js_value] assign[=] call[name[DataTable].CoerceValue, parameter[call[name[value]][constant[0]], name[value_type]]]
return[binary_operation[tuple[[<ast.Name object at 0x7da18dc98e80>]] + call[name[value]][<ast.Slice object at 0x7da18dc9b1c0>]]]
variable[t_value] assign[=] call[name[type], parameter[name[value]]]
if compare[name[value] is constant[None]] begin[:]
return[name[value]]
if compare[name[value_type] equal[==] constant[boolean]] begin[:]
return[call[name[bool], parameter[name[value]]]]
<ast.Raise object at 0x7da2041dbcd0> | keyword[def] identifier[CoerceValue] ( identifier[value] , identifier[value_type] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[tuple] ):
keyword[if] ( identifier[len] ( identifier[value] ) keyword[not] keyword[in] [ literal[int] , literal[int] ] keyword[or]
( identifier[len] ( identifier[value] )== literal[int] keyword[and] keyword[not] identifier[isinstance] ( identifier[value] [ literal[int] ], identifier[dict] ))):
keyword[raise] identifier[DataTableException] ( literal[string] %
identifier[str] ( identifier[value] ))
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] [ literal[int] ], identifier[six] . identifier[string_types] +( identifier[type] ( keyword[None] ),)):
keyword[raise] identifier[DataTableException] ( literal[string] %
identifier[type] ( identifier[value] [ literal[int] ]))
identifier[js_value] = identifier[DataTable] . identifier[CoerceValue] ( identifier[value] [ literal[int] ], identifier[value_type] )
keyword[return] ( identifier[js_value] ,)+ identifier[value] [ literal[int] :]
identifier[t_value] = identifier[type] ( identifier[value] )
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return] identifier[value]
keyword[if] identifier[value_type] == literal[string] :
keyword[return] identifier[bool] ( identifier[value] )
keyword[elif] identifier[value_type] == literal[string] :
keyword[if] identifier[isinstance] ( identifier[value] , identifier[six] . identifier[integer_types] +( identifier[float] ,)):
keyword[return] identifier[value]
keyword[raise] identifier[DataTableException] ( literal[string] % identifier[t_value] )
keyword[elif] identifier[value_type] == literal[string] :
keyword[if] identifier[isinstance] ( identifier[value] , identifier[six] . identifier[text_type] ):
keyword[return] identifier[value]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[bytes] ):
keyword[return] identifier[six] . identifier[text_type] ( identifier[value] , identifier[encoding] = literal[string] )
keyword[else] :
keyword[return] identifier[six] . identifier[text_type] ( identifier[value] )
keyword[elif] identifier[value_type] == literal[string] :
keyword[if] identifier[isinstance] ( identifier[value] , identifier[datetime] . identifier[datetime] ):
keyword[return] identifier[datetime] . identifier[date] ( identifier[value] . identifier[year] , identifier[value] . identifier[month] , identifier[value] . identifier[day] )
keyword[elif] identifier[isinstance] ( identifier[value] , identifier[datetime] . identifier[date] ):
keyword[return] identifier[value]
keyword[else] :
keyword[raise] identifier[DataTableException] ( literal[string] % identifier[t_value] )
keyword[elif] identifier[value_type] == literal[string] :
keyword[if] identifier[isinstance] ( identifier[value] , identifier[datetime] . identifier[datetime] ):
keyword[return] identifier[datetime] . identifier[time] ( identifier[value] . identifier[hour] , identifier[value] . identifier[minute] , identifier[value] . identifier[second] )
keyword[elif] identifier[isinstance] ( identifier[value] , identifier[datetime] . identifier[time] ):
keyword[return] identifier[value]
keyword[else] :
keyword[raise] identifier[DataTableException] ( literal[string] % identifier[t_value] )
keyword[elif] identifier[value_type] == literal[string] :
keyword[if] identifier[isinstance] ( identifier[value] , identifier[datetime] . identifier[datetime] ):
keyword[return] identifier[value]
keyword[else] :
keyword[raise] identifier[DataTableException] ( literal[string] %
identifier[t_value] )
keyword[raise] identifier[DataTableException] ( literal[string] % identifier[value_type] ) | def CoerceValue(value, value_type):
"""Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
An item of the Python type appropriate to the given value_type. Strings
are also converted to Unicode using UTF-8 encoding if necessary.
If a tuple is given, it should be in one of the following forms:
- (value, formatted value)
- (value, formatted value, custom properties)
where the formatted value is a string, and custom properties is a
dictionary of the custom properties for this cell.
To specify custom properties without specifying formatted value, one can
pass None as the formatted value.
One can also have a null-valued cell with formatted value and/or custom
properties by specifying None for the value.
This method ignores the custom properties except for checking that it is a
dictionary. The custom properties are handled in the ToJSon and ToJSCode
methods.
The real type of the given value is not strictly checked. For example,
any type can be used for string - as we simply take its str( ) and for
boolean value we just check "if value".
Examples:
CoerceValue(None, "string") returns None
CoerceValue((5, "5$"), "number") returns (5, "5$")
CoerceValue(100, "string") returns "100"
CoerceValue(0, "boolean") returns False
Raises:
DataTableException: The value and type did not match in a not-recoverable
way, for example given value 'abc' for type 'number'.
"""
if isinstance(value, tuple):
# In case of a tuple, we run the same function on the value itself and
# add the formatted value.
if len(value) not in [2, 3] or (len(value) == 3 and (not isinstance(value[2], dict))):
raise DataTableException('Wrong format for value and formatting - %s.' % str(value)) # depends on [control=['if'], data=[]]
if not isinstance(value[1], six.string_types + (type(None),)):
raise DataTableException('Formatted value is not string, given %s.' % type(value[1])) # depends on [control=['if'], data=[]]
js_value = DataTable.CoerceValue(value[0], value_type)
return (js_value,) + value[1:] # depends on [control=['if'], data=[]]
t_value = type(value)
if value is None:
return value # depends on [control=['if'], data=['value']]
if value_type == 'boolean':
return bool(value) # depends on [control=['if'], data=[]]
elif value_type == 'number':
if isinstance(value, six.integer_types + (float,)):
return value # depends on [control=['if'], data=[]]
raise DataTableException('Wrong type %s when expected number' % t_value) # depends on [control=['if'], data=[]]
elif value_type == 'string':
if isinstance(value, six.text_type):
return value # depends on [control=['if'], data=[]]
if isinstance(value, bytes):
return six.text_type(value, encoding='utf-8') # depends on [control=['if'], data=[]]
else:
return six.text_type(value) # depends on [control=['if'], data=[]]
elif value_type == 'date':
if isinstance(value, datetime.datetime):
return datetime.date(value.year, value.month, value.day) # depends on [control=['if'], data=[]]
elif isinstance(value, datetime.date):
return value # depends on [control=['if'], data=[]]
else:
raise DataTableException('Wrong type %s when expected date' % t_value) # depends on [control=['if'], data=[]]
elif value_type == 'timeofday':
if isinstance(value, datetime.datetime):
return datetime.time(value.hour, value.minute, value.second) # depends on [control=['if'], data=[]]
elif isinstance(value, datetime.time):
return value # depends on [control=['if'], data=[]]
else:
raise DataTableException('Wrong type %s when expected time' % t_value) # depends on [control=['if'], data=[]]
elif value_type == 'datetime':
if isinstance(value, datetime.datetime):
return value # depends on [control=['if'], data=[]]
else:
raise DataTableException('Wrong type %s when expected datetime' % t_value) # depends on [control=['if'], data=[]]
# If we got here, it means the given value_type was not one of the
# supported types.
raise DataTableException('Unsupported type %s' % value_type) |
def solve(self, X, rank, max_iter=500, stopping_criterion=1e-5,
lambda_reg=0.0, dtype=np.float32, rng=None):
"""Solve CPD
Args:
X (numpy.ndarray): Target tensor of CPD.
rank (int): Rank of the approximate tensor.
max_iter (int): Max iteration of the ALS.
stopping_criterion (float): Threshold for stopping the ALS.
If the value is negative, the convergence check is ignored;
in other words, it may reduce the computation time.
lambda_reg (float): regularization parameter. Larger lambda_reg
means larger regularization.
dtype (numpy.dtype): Data type
Returns:
list of numpy.ndarray: Decomposed matrices.
numpy.ndarray: Lambda of the CPD.
"""
N = X.ndim # Tensor dimensions
squared_norm_X = np.sum(X ** 2) # Frobenious norm square
# Initialize
if rng is None:
rng = np.random.RandomState(313)
A = [None for _ in range(N)]
for n in range(1, N):
A[n] = np.array(rng.rand(X.shape[n], rank), dtype=dtype)
# Solve ALS problem
criterion = 0
for itr in range(max_iter):
criterion_prev = criterion
# Fix one dimension
for n in range(N):
# Solve sub problem
V = self.hadamard_products_of_gramians(A, n)
P = self.khatrirao_products(A, n)
A_n = np.tensordot(
X,
P,
axes=(
[o for o in range(N) if o != n],
np.arange(N-1)[::-1]))
# L2 regularization
V = V+np.eye(rank)*lambda_reg
A_n = A_n.dot(pinv(V))
# Normalize
if itr == 0:
lmbda = np.sqrt((A_n ** 2).sum(axis=0))
else:
lmbda = A_n.max(axis=0)
lmbda[lmbda < 1] = 1
A[n] = A_n / lmbda
# Check convergence
if stopping_criterion < 0:
continue
X_approx = self.approximate_tensor(A, lmbda)
squared_norm_residual = squared_norm_X + \
np.sum(X_approx**2) - 2 * np.sum(X*X_approx)
criterion = 1.0 - (squared_norm_residual / squared_norm_X)
criterion_change = abs(criterion_prev - criterion)
if itr > 0 and criterion_change < stopping_criterion:
break
return A, lmbda | def function[solve, parameter[self, X, rank, max_iter, stopping_criterion, lambda_reg, dtype, rng]]:
constant[Solve CPD
Args:
X (numpy.ndarray): Target tensor of CPD.
rank (int): Rank of the approximate tensor.
max_iter (int): Max iteration of the ALS.
stopping_criterion (float): Threshold for stopping the ALS.
If the value is negative, the convergence check is ignored;
in other words, it may reduce the computation time.
lambda_reg (float): regularization parameter. Larger lambda_reg
means larger regularization.
dtype (numpy.dtype): Data type
Returns:
list of numpy.ndarray: Decomposed matrices.
numpy.ndarray: Lambda of the CPD.
]
variable[N] assign[=] name[X].ndim
variable[squared_norm_X] assign[=] call[name[np].sum, parameter[binary_operation[name[X] ** constant[2]]]]
if compare[name[rng] is constant[None]] begin[:]
variable[rng] assign[=] call[name[np].random.RandomState, parameter[constant[313]]]
variable[A] assign[=] <ast.ListComp object at 0x7da1b167c790>
for taget[name[n]] in starred[call[name[range], parameter[constant[1], name[N]]]] begin[:]
call[name[A]][name[n]] assign[=] call[name[np].array, parameter[call[name[rng].rand, parameter[call[name[X].shape][name[n]], name[rank]]]]]
variable[criterion] assign[=] constant[0]
for taget[name[itr]] in starred[call[name[range], parameter[name[max_iter]]]] begin[:]
variable[criterion_prev] assign[=] name[criterion]
for taget[name[n]] in starred[call[name[range], parameter[name[N]]]] begin[:]
variable[V] assign[=] call[name[self].hadamard_products_of_gramians, parameter[name[A], name[n]]]
variable[P] assign[=] call[name[self].khatrirao_products, parameter[name[A], name[n]]]
variable[A_n] assign[=] call[name[np].tensordot, parameter[name[X], name[P]]]
variable[V] assign[=] binary_operation[name[V] + binary_operation[call[name[np].eye, parameter[name[rank]]] * name[lambda_reg]]]
variable[A_n] assign[=] call[name[A_n].dot, parameter[call[name[pinv], parameter[name[V]]]]]
if compare[name[itr] equal[==] constant[0]] begin[:]
variable[lmbda] assign[=] call[name[np].sqrt, parameter[call[binary_operation[name[A_n] ** constant[2]].sum, parameter[]]]]
call[name[A]][name[n]] assign[=] binary_operation[name[A_n] / name[lmbda]]
if compare[name[stopping_criterion] less[<] constant[0]] begin[:]
continue
variable[X_approx] assign[=] call[name[self].approximate_tensor, parameter[name[A], name[lmbda]]]
variable[squared_norm_residual] assign[=] binary_operation[binary_operation[name[squared_norm_X] + call[name[np].sum, parameter[binary_operation[name[X_approx] ** constant[2]]]]] - binary_operation[constant[2] * call[name[np].sum, parameter[binary_operation[name[X] * name[X_approx]]]]]]
variable[criterion] assign[=] binary_operation[constant[1.0] - binary_operation[name[squared_norm_residual] / name[squared_norm_X]]]
variable[criterion_change] assign[=] call[name[abs], parameter[binary_operation[name[criterion_prev] - name[criterion]]]]
if <ast.BoolOp object at 0x7da1b1675540> begin[:]
break
return[tuple[[<ast.Name object at 0x7da212db5090>, <ast.Name object at 0x7da212db4ee0>]]] | keyword[def] identifier[solve] ( identifier[self] , identifier[X] , identifier[rank] , identifier[max_iter] = literal[int] , identifier[stopping_criterion] = literal[int] ,
identifier[lambda_reg] = literal[int] , identifier[dtype] = identifier[np] . identifier[float32] , identifier[rng] = keyword[None] ):
literal[string]
identifier[N] = identifier[X] . identifier[ndim]
identifier[squared_norm_X] = identifier[np] . identifier[sum] ( identifier[X] ** literal[int] )
keyword[if] identifier[rng] keyword[is] keyword[None] :
identifier[rng] = identifier[np] . identifier[random] . identifier[RandomState] ( literal[int] )
identifier[A] =[ keyword[None] keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[N] )]
keyword[for] identifier[n] keyword[in] identifier[range] ( literal[int] , identifier[N] ):
identifier[A] [ identifier[n] ]= identifier[np] . identifier[array] ( identifier[rng] . identifier[rand] ( identifier[X] . identifier[shape] [ identifier[n] ], identifier[rank] ), identifier[dtype] = identifier[dtype] )
identifier[criterion] = literal[int]
keyword[for] identifier[itr] keyword[in] identifier[range] ( identifier[max_iter] ):
identifier[criterion_prev] = identifier[criterion]
keyword[for] identifier[n] keyword[in] identifier[range] ( identifier[N] ):
identifier[V] = identifier[self] . identifier[hadamard_products_of_gramians] ( identifier[A] , identifier[n] )
identifier[P] = identifier[self] . identifier[khatrirao_products] ( identifier[A] , identifier[n] )
identifier[A_n] = identifier[np] . identifier[tensordot] (
identifier[X] ,
identifier[P] ,
identifier[axes] =(
[ identifier[o] keyword[for] identifier[o] keyword[in] identifier[range] ( identifier[N] ) keyword[if] identifier[o] != identifier[n] ],
identifier[np] . identifier[arange] ( identifier[N] - literal[int] )[::- literal[int] ]))
identifier[V] = identifier[V] + identifier[np] . identifier[eye] ( identifier[rank] )* identifier[lambda_reg]
identifier[A_n] = identifier[A_n] . identifier[dot] ( identifier[pinv] ( identifier[V] ))
keyword[if] identifier[itr] == literal[int] :
identifier[lmbda] = identifier[np] . identifier[sqrt] (( identifier[A_n] ** literal[int] ). identifier[sum] ( identifier[axis] = literal[int] ))
keyword[else] :
identifier[lmbda] = identifier[A_n] . identifier[max] ( identifier[axis] = literal[int] )
identifier[lmbda] [ identifier[lmbda] < literal[int] ]= literal[int]
identifier[A] [ identifier[n] ]= identifier[A_n] / identifier[lmbda]
keyword[if] identifier[stopping_criterion] < literal[int] :
keyword[continue]
identifier[X_approx] = identifier[self] . identifier[approximate_tensor] ( identifier[A] , identifier[lmbda] )
identifier[squared_norm_residual] = identifier[squared_norm_X] + identifier[np] . identifier[sum] ( identifier[X_approx] ** literal[int] )- literal[int] * identifier[np] . identifier[sum] ( identifier[X] * identifier[X_approx] )
identifier[criterion] = literal[int] -( identifier[squared_norm_residual] / identifier[squared_norm_X] )
identifier[criterion_change] = identifier[abs] ( identifier[criterion_prev] - identifier[criterion] )
keyword[if] identifier[itr] > literal[int] keyword[and] identifier[criterion_change] < identifier[stopping_criterion] :
keyword[break]
keyword[return] identifier[A] , identifier[lmbda] | def solve(self, X, rank, max_iter=500, stopping_criterion=1e-05, lambda_reg=0.0, dtype=np.float32, rng=None):
"""Solve CPD
Args:
X (numpy.ndarray): Target tensor of CPD.
rank (int): Rank of the approximate tensor.
max_iter (int): Max iteration of the ALS.
stopping_criterion (float): Threshold for stopping the ALS.
If the value is negative, the convergence check is ignored;
in other words, it may reduce the computation time.
lambda_reg (float): regularization parameter. Larger lambda_reg
means larger regularization.
dtype (numpy.dtype): Data type
Returns:
list of numpy.ndarray: Decomposed matrices.
numpy.ndarray: Lambda of the CPD.
"""
N = X.ndim # Tensor dimensions
squared_norm_X = np.sum(X ** 2) # Frobenious norm square
# Initialize
if rng is None:
rng = np.random.RandomState(313) # depends on [control=['if'], data=['rng']]
A = [None for _ in range(N)]
for n in range(1, N):
A[n] = np.array(rng.rand(X.shape[n], rank), dtype=dtype) # depends on [control=['for'], data=['n']]
# Solve ALS problem
criterion = 0
for itr in range(max_iter):
criterion_prev = criterion
# Fix one dimension
for n in range(N):
# Solve sub problem
V = self.hadamard_products_of_gramians(A, n)
P = self.khatrirao_products(A, n)
A_n = np.tensordot(X, P, axes=([o for o in range(N) if o != n], np.arange(N - 1)[::-1]))
# L2 regularization
V = V + np.eye(rank) * lambda_reg
A_n = A_n.dot(pinv(V))
# Normalize
if itr == 0:
lmbda = np.sqrt((A_n ** 2).sum(axis=0)) # depends on [control=['if'], data=[]]
else:
lmbda = A_n.max(axis=0)
lmbda[lmbda < 1] = 1
A[n] = A_n / lmbda # depends on [control=['for'], data=['n']]
# Check convergence
if stopping_criterion < 0:
continue # depends on [control=['if'], data=[]]
X_approx = self.approximate_tensor(A, lmbda)
squared_norm_residual = squared_norm_X + np.sum(X_approx ** 2) - 2 * np.sum(X * X_approx)
criterion = 1.0 - squared_norm_residual / squared_norm_X
criterion_change = abs(criterion_prev - criterion)
if itr > 0 and criterion_change < stopping_criterion:
break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['itr']]
return (A, lmbda) |
async def _drain_writer(self, timeout: NumType = None) -> None:
"""
Wraps writer.drain() with error handling.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
# Wrapping drain in a task makes mypy happy
drain_task = asyncio.Task(self._stream_writer.drain(), loop=self._loop)
try:
await asyncio.wait_for(drain_task, timeout, loop=self._loop)
except ConnectionError as exc:
raise SMTPServerDisconnected(str(exc))
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc)) | <ast.AsyncFunctionDef object at 0x7da18fe93550> | keyword[async] keyword[def] identifier[_drain_writer] ( identifier[self] , identifier[timeout] : identifier[NumType] = keyword[None] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[_stream_writer] keyword[is] keyword[None] :
keyword[raise] identifier[SMTPServerDisconnected] ( literal[string] )
identifier[drain_task] = identifier[asyncio] . identifier[Task] ( identifier[self] . identifier[_stream_writer] . identifier[drain] (), identifier[loop] = identifier[self] . identifier[_loop] )
keyword[try] :
keyword[await] identifier[asyncio] . identifier[wait_for] ( identifier[drain_task] , identifier[timeout] , identifier[loop] = identifier[self] . identifier[_loop] )
keyword[except] identifier[ConnectionError] keyword[as] identifier[exc] :
keyword[raise] identifier[SMTPServerDisconnected] ( identifier[str] ( identifier[exc] ))
keyword[except] identifier[asyncio] . identifier[TimeoutError] keyword[as] identifier[exc] :
keyword[raise] identifier[SMTPTimeoutError] ( identifier[str] ( identifier[exc] )) | async def _drain_writer(self, timeout: NumType=None) -> None:
"""
Wraps writer.drain() with error handling.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected('Client not connected') # depends on [control=['if'], data=[]]
# Wrapping drain in a task makes mypy happy
drain_task = asyncio.Task(self._stream_writer.drain(), loop=self._loop)
try:
await asyncio.wait_for(drain_task, timeout, loop=self._loop) # depends on [control=['try'], data=[]]
except ConnectionError as exc:
raise SMTPServerDisconnected(str(exc)) # depends on [control=['except'], data=['exc']]
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc)) # depends on [control=['except'], data=['exc']] |
def pausable_restart_on_change(restart_map, stopstart=False,
restart_functions=None):
"""A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.host, yet the openstack specific helpers are in this file
(contrib.openstack.utils). Thus, this needs to be an optional feature
for openstack charms (or charms that wish to use the openstack
pause/resume type features).
It is used as follows:
from contrib.openstack.utils import (
pausable_restart_on_change as restart_on_change)
@restart_on_change(restart_map, stopstart=<boolean>)
def some_hook(...):
pass
see core.utils.restart_on_change() for more details.
Note restart_map can be a callable, in which case, restart_map is only
evaluated at runtime. This means that it is lazy and the underlying
function won't be called if the decorated function is never called. Note,
retains backwards compatibility for passing a non-callable dictionary.
@param f: the function to decorate
@param restart_map: (optionally callable, which then returns the
restart_map) the restart map {conf_file: [services]}
@param stopstart: DEFAULT false; whether to stop, start or just restart
@returns decorator to use a restart_on_change with pausability
"""
def wrap(f):
# py27 compatible nonlocal variable. When py3 only, replace with
# nonlocal keyword
__restart_map_cache = {'cache': None}
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
if is_unit_paused_set():
return f(*args, **kwargs)
if __restart_map_cache['cache'] is None:
__restart_map_cache['cache'] = restart_map() \
if callable(restart_map) else restart_map
# otherwise, normal restart_on_change functionality
return restart_on_change_helper(
(lambda: f(*args, **kwargs)), __restart_map_cache['cache'],
stopstart, restart_functions)
return wrapped_f
return wrap | def function[pausable_restart_on_change, parameter[restart_map, stopstart, restart_functions]]:
constant[A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.host, yet the openstack specific helpers are in this file
(contrib.openstack.utils). Thus, this needs to be an optional feature
for openstack charms (or charms that wish to use the openstack
pause/resume type features).
It is used as follows:
from contrib.openstack.utils import (
pausable_restart_on_change as restart_on_change)
@restart_on_change(restart_map, stopstart=<boolean>)
def some_hook(...):
pass
see core.utils.restart_on_change() for more details.
Note restart_map can be a callable, in which case, restart_map is only
evaluated at runtime. This means that it is lazy and the underlying
function won't be called if the decorated function is never called. Note,
retains backwards compatibility for passing a non-callable dictionary.
@param f: the function to decorate
@param restart_map: (optionally callable, which then returns the
restart_map) the restart map {conf_file: [services]}
@param stopstart: DEFAULT false; whether to stop, start or just restart
@returns decorator to use a restart_on_change with pausability
]
def function[wrap, parameter[f]]:
variable[__restart_map_cache] assign[=] dictionary[[<ast.Constant object at 0x7da18fe90a30>], [<ast.Constant object at 0x7da18fe92890>]]
def function[wrapped_f, parameter[]]:
if call[name[is_unit_paused_set], parameter[]] begin[:]
return[call[name[f], parameter[<ast.Starred object at 0x7da18fe92e90>]]]
if compare[call[name[__restart_map_cache]][constant[cache]] is constant[None]] begin[:]
call[name[__restart_map_cache]][constant[cache]] assign[=] <ast.IfExp object at 0x7da18fe92800>
return[call[name[restart_on_change_helper], parameter[<ast.Lambda object at 0x7da1b11ab7c0>, call[name[__restart_map_cache]][constant[cache]], name[stopstart], name[restart_functions]]]]
return[name[wrapped_f]]
return[name[wrap]] | keyword[def] identifier[pausable_restart_on_change] ( identifier[restart_map] , identifier[stopstart] = keyword[False] ,
identifier[restart_functions] = keyword[None] ):
literal[string]
keyword[def] identifier[wrap] ( identifier[f] ):
identifier[__restart_map_cache] ={ literal[string] : keyword[None] }
@ identifier[functools] . identifier[wraps] ( identifier[f] )
keyword[def] identifier[wrapped_f] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[is_unit_paused_set] ():
keyword[return] identifier[f] (* identifier[args] ,** identifier[kwargs] )
keyword[if] identifier[__restart_map_cache] [ literal[string] ] keyword[is] keyword[None] :
identifier[__restart_map_cache] [ literal[string] ]= identifier[restart_map] () keyword[if] identifier[callable] ( identifier[restart_map] ) keyword[else] identifier[restart_map]
keyword[return] identifier[restart_on_change_helper] (
( keyword[lambda] : identifier[f] (* identifier[args] ,** identifier[kwargs] )), identifier[__restart_map_cache] [ literal[string] ],
identifier[stopstart] , identifier[restart_functions] )
keyword[return] identifier[wrapped_f]
keyword[return] identifier[wrap] | def pausable_restart_on_change(restart_map, stopstart=False, restart_functions=None):
"""A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.host, yet the openstack specific helpers are in this file
(contrib.openstack.utils). Thus, this needs to be an optional feature
for openstack charms (or charms that wish to use the openstack
pause/resume type features).
It is used as follows:
from contrib.openstack.utils import (
pausable_restart_on_change as restart_on_change)
@restart_on_change(restart_map, stopstart=<boolean>)
def some_hook(...):
pass
see core.utils.restart_on_change() for more details.
Note restart_map can be a callable, in which case, restart_map is only
evaluated at runtime. This means that it is lazy and the underlying
function won't be called if the decorated function is never called. Note,
retains backwards compatibility for passing a non-callable dictionary.
@param f: the function to decorate
@param restart_map: (optionally callable, which then returns the
restart_map) the restart map {conf_file: [services]}
@param stopstart: DEFAULT false; whether to stop, start or just restart
@returns decorator to use a restart_on_change with pausability
"""
def wrap(f):
# py27 compatible nonlocal variable. When py3 only, replace with
# nonlocal keyword
__restart_map_cache = {'cache': None}
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
if is_unit_paused_set():
return f(*args, **kwargs) # depends on [control=['if'], data=[]]
if __restart_map_cache['cache'] is None:
__restart_map_cache['cache'] = restart_map() if callable(restart_map) else restart_map # depends on [control=['if'], data=[]]
# otherwise, normal restart_on_change functionality
return restart_on_change_helper(lambda : f(*args, **kwargs), __restart_map_cache['cache'], stopstart, restart_functions)
return wrapped_f
return wrap |
def cmd_distclean(self, *args):
'''Clean the whole Buildozer environment.
'''
print("Warning: Your ndk, sdk and all other cached packages will be"
" removed. Continue? (y/n)")
if sys.stdin.readline().lower()[0] == 'y':
self.info('Clean the global build directory')
if not exists(self.global_buildozer_dir):
return
rmtree(self.global_buildozer_dir) | def function[cmd_distclean, parameter[self]]:
constant[Clean the whole Buildozer environment.
]
call[name[print], parameter[constant[Warning: Your ndk, sdk and all other cached packages will be removed. Continue? (y/n)]]]
if compare[call[call[call[name[sys].stdin.readline, parameter[]].lower, parameter[]]][constant[0]] equal[==] constant[y]] begin[:]
call[name[self].info, parameter[constant[Clean the global build directory]]]
if <ast.UnaryOp object at 0x7da18f812a70> begin[:]
return[None]
call[name[rmtree], parameter[name[self].global_buildozer_dir]] | keyword[def] identifier[cmd_distclean] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[print] ( literal[string]
literal[string] )
keyword[if] identifier[sys] . identifier[stdin] . identifier[readline] (). identifier[lower] ()[ literal[int] ]== literal[string] :
identifier[self] . identifier[info] ( literal[string] )
keyword[if] keyword[not] identifier[exists] ( identifier[self] . identifier[global_buildozer_dir] ):
keyword[return]
identifier[rmtree] ( identifier[self] . identifier[global_buildozer_dir] ) | def cmd_distclean(self, *args):
"""Clean the whole Buildozer environment.
"""
print('Warning: Your ndk, sdk and all other cached packages will be removed. Continue? (y/n)')
if sys.stdin.readline().lower()[0] == 'y':
self.info('Clean the global build directory')
if not exists(self.global_buildozer_dir):
return # depends on [control=['if'], data=[]]
rmtree(self.global_buildozer_dir) # depends on [control=['if'], data=[]] |
def _parse_canonical_decimal128(doc):
"""Decode a JSON decimal128 to bson.decimal128.Decimal128."""
d_str = doc['$numberDecimal']
if len(doc) != 1:
raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,))
if not isinstance(d_str, string_type):
raise TypeError('$numberDecimal must be string: %s' % (doc,))
return Decimal128(d_str) | def function[_parse_canonical_decimal128, parameter[doc]]:
constant[Decode a JSON decimal128 to bson.decimal128.Decimal128.]
variable[d_str] assign[=] call[name[doc]][constant[$numberDecimal]]
if compare[call[name[len], parameter[name[doc]]] not_equal[!=] constant[1]] begin[:]
<ast.Raise object at 0x7da20c6c6620>
if <ast.UnaryOp object at 0x7da20e957dc0> begin[:]
<ast.Raise object at 0x7da18f00ca60>
return[call[name[Decimal128], parameter[name[d_str]]]] | keyword[def] identifier[_parse_canonical_decimal128] ( identifier[doc] ):
literal[string]
identifier[d_str] = identifier[doc] [ literal[string] ]
keyword[if] identifier[len] ( identifier[doc] )!= literal[int] :
keyword[raise] identifier[TypeError] ( literal[string] %( identifier[doc] ,))
keyword[if] keyword[not] identifier[isinstance] ( identifier[d_str] , identifier[string_type] ):
keyword[raise] identifier[TypeError] ( literal[string] %( identifier[doc] ,))
keyword[return] identifier[Decimal128] ( identifier[d_str] ) | def _parse_canonical_decimal128(doc):
"""Decode a JSON decimal128 to bson.decimal128.Decimal128."""
d_str = doc['$numberDecimal']
if len(doc) != 1:
raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,)) # depends on [control=['if'], data=[]]
if not isinstance(d_str, string_type):
raise TypeError('$numberDecimal must be string: %s' % (doc,)) # depends on [control=['if'], data=[]]
return Decimal128(d_str) |
def combine_time_series(
time_series_dict: Dict, kind: str, *, split_directions: bool = False
) -> DataFrame:
"""
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
Has the form string -> time series
kind : string
``'route'`` or ``'stop'``
split_directions : boolean
If ``True``, then assume the original time series contains data
separated by trip direction; otherwise, assume not.
The separation is indicated by a suffix ``'-0'`` (direction 0)
or ``'-1'`` (direction 1) in the route ID or stop ID column
values.
Returns
-------
DataFrame
Columns are hierarchical (multi-index).
The top level columns are the keys of the dictionary and
the second level columns are ``'route_id'`` and
``'direction_id'``, if ``kind == 'route'``, or 'stop_id' and
``'direction_id'``, if ``kind == 'stop'``.
If ``split_directions``, then third column is
``'direction_id'``; otherwise, there is no ``'direction_id'``
column.
"""
if kind not in ["stop", "route"]:
raise ValueError("kind must be 'stop' or 'route'")
names = ["indicator"]
if kind == "stop":
names.append("stop_id")
else:
names.append("route_id")
if split_directions:
names.append("direction_id")
def process_index(k):
a, b = k.rsplit("-", 1)
return a, int(b)
frames = list(time_series_dict.values())
new_frames = []
if split_directions:
for f in frames:
ft = f.T
ft.index = pd.MultiIndex.from_tuples(
[process_index(k) for (k, __) in ft.iterrows()]
)
new_frames.append(ft.T)
else:
new_frames = frames
result = pd.concat(
new_frames, axis=1, keys=list(time_series_dict.keys()), names=names
)
return result | def function[combine_time_series, parameter[time_series_dict, kind]]:
constant[
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
Has the form string -> time series
kind : string
``'route'`` or ``'stop'``
split_directions : boolean
If ``True``, then assume the original time series contains data
separated by trip direction; otherwise, assume not.
The separation is indicated by a suffix ``'-0'`` (direction 0)
or ``'-1'`` (direction 1) in the route ID or stop ID column
values.
Returns
-------
DataFrame
Columns are hierarchical (multi-index).
The top level columns are the keys of the dictionary and
the second level columns are ``'route_id'`` and
``'direction_id'``, if ``kind == 'route'``, or 'stop_id' and
``'direction_id'``, if ``kind == 'stop'``.
If ``split_directions``, then third column is
``'direction_id'``; otherwise, there is no ``'direction_id'``
column.
]
if compare[name[kind] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object at 0x7da20c990a00>, <ast.Constant object at 0x7da20c991960>]]] begin[:]
<ast.Raise object at 0x7da20c991300>
variable[names] assign[=] list[[<ast.Constant object at 0x7da20c991b10>]]
if compare[name[kind] equal[==] constant[stop]] begin[:]
call[name[names].append, parameter[constant[stop_id]]]
if name[split_directions] begin[:]
call[name[names].append, parameter[constant[direction_id]]]
def function[process_index, parameter[k]]:
<ast.Tuple object at 0x7da20c6aa5c0> assign[=] call[name[k].rsplit, parameter[constant[-], constant[1]]]
return[tuple[[<ast.Name object at 0x7da20c6ab8e0>, <ast.Call object at 0x7da20c6a8910>]]]
variable[frames] assign[=] call[name[list], parameter[call[name[time_series_dict].values, parameter[]]]]
variable[new_frames] assign[=] list[[]]
if name[split_directions] begin[:]
for taget[name[f]] in starred[name[frames]] begin[:]
variable[ft] assign[=] name[f].T
name[ft].index assign[=] call[name[pd].MultiIndex.from_tuples, parameter[<ast.ListComp object at 0x7da204960070>]]
call[name[new_frames].append, parameter[name[ft].T]]
variable[result] assign[=] call[name[pd].concat, parameter[name[new_frames]]]
return[name[result]] | keyword[def] identifier[combine_time_series] (
identifier[time_series_dict] : identifier[Dict] , identifier[kind] : identifier[str] ,*, identifier[split_directions] : identifier[bool] = keyword[False]
)-> identifier[DataFrame] :
literal[string]
keyword[if] identifier[kind] keyword[not] keyword[in] [ literal[string] , literal[string] ]:
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[names] =[ literal[string] ]
keyword[if] identifier[kind] == literal[string] :
identifier[names] . identifier[append] ( literal[string] )
keyword[else] :
identifier[names] . identifier[append] ( literal[string] )
keyword[if] identifier[split_directions] :
identifier[names] . identifier[append] ( literal[string] )
keyword[def] identifier[process_index] ( identifier[k] ):
identifier[a] , identifier[b] = identifier[k] . identifier[rsplit] ( literal[string] , literal[int] )
keyword[return] identifier[a] , identifier[int] ( identifier[b] )
identifier[frames] = identifier[list] ( identifier[time_series_dict] . identifier[values] ())
identifier[new_frames] =[]
keyword[if] identifier[split_directions] :
keyword[for] identifier[f] keyword[in] identifier[frames] :
identifier[ft] = identifier[f] . identifier[T]
identifier[ft] . identifier[index] = identifier[pd] . identifier[MultiIndex] . identifier[from_tuples] (
[ identifier[process_index] ( identifier[k] ) keyword[for] ( identifier[k] , identifier[__] ) keyword[in] identifier[ft] . identifier[iterrows] ()]
)
identifier[new_frames] . identifier[append] ( identifier[ft] . identifier[T] )
keyword[else] :
identifier[new_frames] = identifier[frames]
identifier[result] = identifier[pd] . identifier[concat] (
identifier[new_frames] , identifier[axis] = literal[int] , identifier[keys] = identifier[list] ( identifier[time_series_dict] . identifier[keys] ()), identifier[names] = identifier[names]
)
keyword[return] identifier[result] | def combine_time_series(time_series_dict: Dict, kind: str, *, split_directions: bool=False) -> DataFrame:
"""
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
Has the form string -> time series
kind : string
``'route'`` or ``'stop'``
split_directions : boolean
If ``True``, then assume the original time series contains data
separated by trip direction; otherwise, assume not.
The separation is indicated by a suffix ``'-0'`` (direction 0)
or ``'-1'`` (direction 1) in the route ID or stop ID column
values.
Returns
-------
DataFrame
Columns are hierarchical (multi-index).
The top level columns are the keys of the dictionary and
the second level columns are ``'route_id'`` and
``'direction_id'``, if ``kind == 'route'``, or 'stop_id' and
``'direction_id'``, if ``kind == 'stop'``.
If ``split_directions``, then third column is
``'direction_id'``; otherwise, there is no ``'direction_id'``
column.
"""
if kind not in ['stop', 'route']:
raise ValueError("kind must be 'stop' or 'route'") # depends on [control=['if'], data=[]]
names = ['indicator']
if kind == 'stop':
names.append('stop_id') # depends on [control=['if'], data=[]]
else:
names.append('route_id')
if split_directions:
names.append('direction_id') # depends on [control=['if'], data=[]]
def process_index(k):
(a, b) = k.rsplit('-', 1)
return (a, int(b))
frames = list(time_series_dict.values())
new_frames = []
if split_directions:
for f in frames:
ft = f.T
ft.index = pd.MultiIndex.from_tuples([process_index(k) for (k, __) in ft.iterrows()])
new_frames.append(ft.T) # depends on [control=['for'], data=['f']] # depends on [control=['if'], data=[]]
else:
new_frames = frames
result = pd.concat(new_frames, axis=1, keys=list(time_series_dict.keys()), names=names)
return result |
def to_yaml(cls, representer, node):
"""How to serialize this class back to yaml."""
return representer.represent_scalar(cls.yaml_tag, node.value) | def function[to_yaml, parameter[cls, representer, node]]:
constant[How to serialize this class back to yaml.]
return[call[name[representer].represent_scalar, parameter[name[cls].yaml_tag, name[node].value]]] | keyword[def] identifier[to_yaml] ( identifier[cls] , identifier[representer] , identifier[node] ):
literal[string]
keyword[return] identifier[representer] . identifier[represent_scalar] ( identifier[cls] . identifier[yaml_tag] , identifier[node] . identifier[value] ) | def to_yaml(cls, representer, node):
"""How to serialize this class back to yaml."""
return representer.represent_scalar(cls.yaml_tag, node.value) |
def setup():
"""
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
"""
# create an index template
index_template = BlogPost._index.as_template(ALIAS, PATTERN)
# upload the template into elasticsearch
# potentially overriding the one already there
index_template.save()
# create the first index if it doesn't exist
if not BlogPost._index.exists():
migrate(move_data=False) | def function[setup, parameter[]]:
constant[
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
]
variable[index_template] assign[=] call[name[BlogPost]._index.as_template, parameter[name[ALIAS], name[PATTERN]]]
call[name[index_template].save, parameter[]]
if <ast.UnaryOp object at 0x7da20e9b37c0> begin[:]
call[name[migrate], parameter[]] | keyword[def] identifier[setup] ():
literal[string]
identifier[index_template] = identifier[BlogPost] . identifier[_index] . identifier[as_template] ( identifier[ALIAS] , identifier[PATTERN] )
identifier[index_template] . identifier[save] ()
keyword[if] keyword[not] identifier[BlogPost] . identifier[_index] . identifier[exists] ():
identifier[migrate] ( identifier[move_data] = keyword[False] ) | def setup():
"""
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
"""
# create an index template
index_template = BlogPost._index.as_template(ALIAS, PATTERN)
# upload the template into elasticsearch
# potentially overriding the one already there
index_template.save()
# create the first index if it doesn't exist
if not BlogPost._index.exists():
migrate(move_data=False) # depends on [control=['if'], data=[]] |
def _get_chunks(chunksize, *iterables):
"""Iterates over zip()ed iterables in chunks. """
if sys.version_info < (3, 3):
it = itertools.izip(*iterables)
else:
it = zip(*iterables)
while True:
chunk = tuple(itertools.islice(it, chunksize))
if not chunk:
return
yield chunk | def function[_get_chunks, parameter[chunksize]]:
constant[Iterates over zip()ed iterables in chunks. ]
if compare[name[sys].version_info less[<] tuple[[<ast.Constant object at 0x7da18f7219f0>, <ast.Constant object at 0x7da18f722bf0>]]] begin[:]
variable[it] assign[=] call[name[itertools].izip, parameter[<ast.Starred object at 0x7da18f722d70>]]
while constant[True] begin[:]
variable[chunk] assign[=] call[name[tuple], parameter[call[name[itertools].islice, parameter[name[it], name[chunksize]]]]]
if <ast.UnaryOp object at 0x7da20c992fb0> begin[:]
return[None]
<ast.Yield object at 0x7da20c990400> | keyword[def] identifier[_get_chunks] ( identifier[chunksize] ,* identifier[iterables] ):
literal[string]
keyword[if] identifier[sys] . identifier[version_info] <( literal[int] , literal[int] ):
identifier[it] = identifier[itertools] . identifier[izip] (* identifier[iterables] )
keyword[else] :
identifier[it] = identifier[zip] (* identifier[iterables] )
keyword[while] keyword[True] :
identifier[chunk] = identifier[tuple] ( identifier[itertools] . identifier[islice] ( identifier[it] , identifier[chunksize] ))
keyword[if] keyword[not] identifier[chunk] :
keyword[return]
keyword[yield] identifier[chunk] | def _get_chunks(chunksize, *iterables):
"""Iterates over zip()ed iterables in chunks. """
if sys.version_info < (3, 3):
it = itertools.izip(*iterables) # depends on [control=['if'], data=[]]
else:
it = zip(*iterables)
while True:
chunk = tuple(itertools.islice(it, chunksize))
if not chunk:
return # depends on [control=['if'], data=[]]
yield chunk # depends on [control=['while'], data=[]] |
def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_content: %s", body)
return body | def function[get_message_content, parameter[self]]:
constant[
Given the Slap XML, extract out the payload.
]
variable[body] assign[=] call[name[self].doc.find, parameter[constant[.//{http://salmon-protocol.org/ns/magic-env}data]]].text
variable[body] assign[=] call[name[urlsafe_b64decode], parameter[call[name[body].encode, parameter[constant[ascii]]]]]
call[name[logger].debug, parameter[constant[diaspora.protocol.get_message_content: %s], name[body]]]
return[name[body]] | keyword[def] identifier[get_message_content] ( identifier[self] ):
literal[string]
identifier[body] = identifier[self] . identifier[doc] . identifier[find] (
literal[string] ). identifier[text]
identifier[body] = identifier[urlsafe_b64decode] ( identifier[body] . identifier[encode] ( literal[string] ))
identifier[logger] . identifier[debug] ( literal[string] , identifier[body] )
keyword[return] identifier[body] | def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find('.//{http://salmon-protocol.org/ns/magic-env}data').text
body = urlsafe_b64decode(body.encode('ascii'))
logger.debug('diaspora.protocol.get_message_content: %s', body)
return body |
def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_width = 2:
793 B
100 KB
min_unit_width = 3:
793 B
100 KB
"""
unit, unit_divider = self._unit_info()
unit_color = self.SIZE_COLORS[unit]
# Multiply and then divide by 100 in order to have only two decimal places.
size_in_unit = (self.size * 100) / unit_divider / 100
# Add spaces to align the units.
unit = '{}{}'.format(' ' * (min_unit_width - len(unit)), unit)
size_string = f'{size_in_unit:.1f}'
total_len = len(size_string) + 1 + len(unit)
if printer is None:
printer = get_printer()
spaces_count = min_width - total_len
if spaces_count > 0:
printer.write(' ' * spaces_count)
printer.write(f'{size_string} {unit_color}{unit}') | def function[pretty_print, parameter[self, printer, min_width, min_unit_width]]:
constant[
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_width = 2:
793 B
100 KB
min_unit_width = 3:
793 B
100 KB
]
<ast.Tuple object at 0x7da20c990a30> assign[=] call[name[self]._unit_info, parameter[]]
variable[unit_color] assign[=] call[name[self].SIZE_COLORS][name[unit]]
variable[size_in_unit] assign[=] binary_operation[binary_operation[binary_operation[name[self].size * constant[100]] / name[unit_divider]] / constant[100]]
variable[unit] assign[=] call[constant[{}{}].format, parameter[binary_operation[constant[ ] * binary_operation[name[min_unit_width] - call[name[len], parameter[name[unit]]]]], name[unit]]]
variable[size_string] assign[=] <ast.JoinedStr object at 0x7da1b0b723e0>
variable[total_len] assign[=] binary_operation[binary_operation[call[name[len], parameter[name[size_string]]] + constant[1]] + call[name[len], parameter[name[unit]]]]
if compare[name[printer] is constant[None]] begin[:]
variable[printer] assign[=] call[name[get_printer], parameter[]]
variable[spaces_count] assign[=] binary_operation[name[min_width] - name[total_len]]
if compare[name[spaces_count] greater[>] constant[0]] begin[:]
call[name[printer].write, parameter[binary_operation[constant[ ] * name[spaces_count]]]]
call[name[printer].write, parameter[<ast.JoinedStr object at 0x7da1b0b70700>]] | keyword[def] identifier[pretty_print] ( identifier[self] , identifier[printer] : identifier[Optional] [ identifier[Printer] ]= keyword[None] , identifier[min_width] : identifier[int] = literal[int] , identifier[min_unit_width] : identifier[int] = literal[int] ):
literal[string]
identifier[unit] , identifier[unit_divider] = identifier[self] . identifier[_unit_info] ()
identifier[unit_color] = identifier[self] . identifier[SIZE_COLORS] [ identifier[unit] ]
identifier[size_in_unit] =( identifier[self] . identifier[size] * literal[int] )/ identifier[unit_divider] / literal[int]
identifier[unit] = literal[string] . identifier[format] ( literal[string] *( identifier[min_unit_width] - identifier[len] ( identifier[unit] )), identifier[unit] )
identifier[size_string] = literal[string]
identifier[total_len] = identifier[len] ( identifier[size_string] )+ literal[int] + identifier[len] ( identifier[unit] )
keyword[if] identifier[printer] keyword[is] keyword[None] :
identifier[printer] = identifier[get_printer] ()
identifier[spaces_count] = identifier[min_width] - identifier[total_len]
keyword[if] identifier[spaces_count] > literal[int] :
identifier[printer] . identifier[write] ( literal[string] * identifier[spaces_count] )
identifier[printer] . identifier[write] ( literal[string] ) | def pretty_print(self, printer: Optional[Printer]=None, min_width: int=1, min_unit_width: int=1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_width = 2:
793 B
100 KB
min_unit_width = 3:
793 B
100 KB
"""
(unit, unit_divider) = self._unit_info()
unit_color = self.SIZE_COLORS[unit]
# Multiply and then divide by 100 in order to have only two decimal places.
size_in_unit = self.size * 100 / unit_divider / 100
# Add spaces to align the units.
unit = '{}{}'.format(' ' * (min_unit_width - len(unit)), unit)
size_string = f'{size_in_unit:.1f}'
total_len = len(size_string) + 1 + len(unit)
if printer is None:
printer = get_printer() # depends on [control=['if'], data=['printer']]
spaces_count = min_width - total_len
if spaces_count > 0:
printer.write(' ' * spaces_count) # depends on [control=['if'], data=['spaces_count']]
printer.write(f'{size_string} {unit_color}{unit}') |
def lstrip_ws_and_chars(string, chars):
"""Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>> lstrip_ws_and_chars(' \\t.\\n , .x. ', '.,?!')
'x. '
"""
res = string.lstrip().lstrip(chars)
while len(res) != len(string):
string = res
res = string.lstrip().lstrip(chars)
return res | def function[lstrip_ws_and_chars, parameter[string, chars]]:
constant[Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>> lstrip_ws_and_chars(' \t.\n , .x. ', '.,?!')
'x. '
]
variable[res] assign[=] call[call[name[string].lstrip, parameter[]].lstrip, parameter[name[chars]]]
while compare[call[name[len], parameter[name[res]]] not_equal[!=] call[name[len], parameter[name[string]]]] begin[:]
variable[string] assign[=] name[res]
variable[res] assign[=] call[call[name[string].lstrip, parameter[]].lstrip, parameter[name[chars]]]
return[name[res]] | keyword[def] identifier[lstrip_ws_and_chars] ( identifier[string] , identifier[chars] ):
literal[string]
identifier[res] = identifier[string] . identifier[lstrip] (). identifier[lstrip] ( identifier[chars] )
keyword[while] identifier[len] ( identifier[res] )!= identifier[len] ( identifier[string] ):
identifier[string] = identifier[res]
identifier[res] = identifier[string] . identifier[lstrip] (). identifier[lstrip] ( identifier[chars] )
keyword[return] identifier[res] | def lstrip_ws_and_chars(string, chars):
"""Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>> lstrip_ws_and_chars(' \\t.\\n , .x. ', '.,?!')
'x. '
"""
res = string.lstrip().lstrip(chars)
while len(res) != len(string):
string = res
res = string.lstrip().lstrip(chars) # depends on [control=['while'], data=[]]
return res |
def forward_exception(self, etype, evalue, tb):
"""
Forward the exception onto the backup copy that was made of the sys.__excepthook__
:param etype: Exceoption type
:param evalue: Exception value
:param tb: Traceback
:return:
"""
self._excepthook(etype, evalue, tb) | def function[forward_exception, parameter[self, etype, evalue, tb]]:
constant[
Forward the exception onto the backup copy that was made of the sys.__excepthook__
:param etype: Exceoption type
:param evalue: Exception value
:param tb: Traceback
:return:
]
call[name[self]._excepthook, parameter[name[etype], name[evalue], name[tb]]] | keyword[def] identifier[forward_exception] ( identifier[self] , identifier[etype] , identifier[evalue] , identifier[tb] ):
literal[string]
identifier[self] . identifier[_excepthook] ( identifier[etype] , identifier[evalue] , identifier[tb] ) | def forward_exception(self, etype, evalue, tb):
"""
Forward the exception onto the backup copy that was made of the sys.__excepthook__
:param etype: Exceoption type
:param evalue: Exception value
:param tb: Traceback
:return:
"""
self._excepthook(etype, evalue, tb) |
def kernel():
"""
Handle linux kernel update
"""
print('================================')
print(' WARNING: upgrading the kernel')
print('================================')
time.sleep(5)
print('-[kernel]----------')
cmd('rpi-update', True)
print(' >> You MUST reboot to load the new kernel <<') | def function[kernel, parameter[]]:
constant[
Handle linux kernel update
]
call[name[print], parameter[constant[================================]]]
call[name[print], parameter[constant[ WARNING: upgrading the kernel]]]
call[name[print], parameter[constant[================================]]]
call[name[time].sleep, parameter[constant[5]]]
call[name[print], parameter[constant[-[kernel]----------]]]
call[name[cmd], parameter[constant[rpi-update], constant[True]]]
call[name[print], parameter[constant[ >> You MUST reboot to load the new kernel <<]]] | keyword[def] identifier[kernel] ():
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
identifier[time] . identifier[sleep] ( literal[int] )
identifier[print] ( literal[string] )
identifier[cmd] ( literal[string] , keyword[True] )
identifier[print] ( literal[string] ) | def kernel():
"""
Handle linux kernel update
"""
print('================================')
print(' WARNING: upgrading the kernel')
print('================================')
time.sleep(5)
print('-[kernel]----------')
cmd('rpi-update', True)
print(' >> You MUST reboot to load the new kernel <<') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.