I am looking for the cleanest way to declare multiple variables in Python. My code looks like this:
app_type = config_data["app"]
app_params = config_data["app_data"]
original_fps = config_data["main"][0]["original_fps"]
sub_sampled_fps = config_data["main"][0]["sub_sampled_fps"]
max_retries = config_data["main"][0]["max_retries"]
win_size = config_data["main"][0]["window_size"]
input_frame_rate = config_data["main"][0]["input_frame_rate"]
Is something like this acceptable by the styling guide?
app_type = config_data["app"]
app_params = config_data["app_data"]
original_fps = config_data["main"][0]["original_fps"]
sub_sampled_fps = config_data["main"][0]["sub_sampled_fps"]
max_retries = config_data["main"][0]["max_retries"]
win_size = config_data["main"][0]["window_size"]
input_frame_rate = config_data["main"][0]["input_frame_rate"]
If not are there any better ways to style it?
Not recommended according to pep8:
# Correct:
x = 1
y = 2
long_variable = 3
# Wrong:
x = 1
y = 2
long_variable = 3
See the reference here
Related
Is there a python-docx equivalent the following visual basic code? What is it? Pointers to the appropriate documentation or sample code would be great too.
With ListGalleries(wdOutlineNumberGallery).ListTemplates(1).ListLevels(2)
.NumberFormat = "%1.%2"
.TrailingCharacter = wdTrailingTab
.NumberStyle = wdListNumberStyleLegal
.NumberPosition = InchesToPoints(0)
.Alignment = wdListLevelAlignLeft
.TextPosition = InchesToPoints(0.5)
.TabPosition = wdUndefined
.ResetOnHigher = 1
.StartAt = 1
With .Font
.Bold = False
.Italic = False
.StrikeThrough = False
.Subscript = False
.Superscript = False
.Shadow = wdUndefined
.Outline = wdUndefined
.Emboss = wdUndefined
.Engrave = wdUndefined
.AllCaps = False
.Hidden = False
.Underline = wdUnderlineNone
.Color = wdUndefined
.Size = 10.5
.Animation = wdUndefined
.DoubleStrikeThrough = False
.Name = "Times New Roman"
End With
.LinkedStyle = "L2"
End With
The goal is to be able to assign a paragraph a style with the appropriately linked numbering so that I can then assign the style to the paragraph and get well numbered lists automatically.
How to I create a 3 level list in python 2.7? See Image of Nested Lists HERE
Setup:
I have the following inputs:
Files(s)
Categories
I then Search through each file, and iterate through each category to get every Value.
I just can't get the desired output.
# Combine Multiple Lists
LinkDoc = ["File1", "File2", "File3"]
cat = ["Walls", "Doors", "Columns"]
rvt1_wall = ["W1_rvt1", "W2_rvt1"]
rvt1_door = ["D1_rvt1", "D2_rvt1", "D3_rvt1", "D4_rvt1"]
rvt1_col = ["C1_rvt1"]
rvt2_wall = ["W2_rvt2", "W2_rvt2"]
rvt2_door = ["D2_rvt2", "D2_rvt2", "D3_rvt2", "D4_rvt2"]
rvt2_col = ["C2_rvt2"]
rvt3_wall = ["W3_rvt3", "W2_rvt3"]
rvt3_door = ["D3_rvt3", "D2_rvt3", "D3_rvt3", "D4_rvt3"]
rvt3_col = ["C3_rvt3"]
rvt4_wall = ["W4_rvt4", "W2_rvt4"]
rvt4_door = ["D4_rvt4", "D2_rvt4", "D3_rvt4", "D4_rvt4"]
rvt4_col = ["C4_rvt4"]
all_comb1 = [rvt1_wall,rvt1_door,rvt1_col]
all_comb2 = [rvt2_wall,rvt2_door,rvt2_col]
all_comb3 = [rvt3_wall,rvt3_door,rvt3_col]
all_comb4 = [rvt4_wall,rvt4_door,rvt4_col]
all_tot = [all_comb1, all_comb2, all_comb3, all_comb4]
xyz_pairs = [[x,y,z] for x in LinkDoc for y in cat for z in all_tot]
print(xyz_pairs)
print("========")
print("")
Here is my code:
n = 100000 #This is what makes it tricky - lots of files going into this hdf5 file
with h5py.File('image1.h5','w') as f:
dset_X = f.create_dataset('X',(1,960,224,224),maxshape=(None,960,224,224),chunks=True,compression='gzip')
dset_y = f.create_dataset('y',(1,112,224*224),maxshape=(None,112,224*224),chunks=True,compression='gzip')
n_images = 0
for fl in files[:n]:
X_chunk,y_chunk = get_arrays(fl)
dset_X.resize(n_images+1,axis=0)
dset_y.resize(n_images+1,axis=0)
print dset_X.shape,dset_y.shape
dset_X[n_images:n_images+1,:,:,:]=X_chunk
dset_y[n_images:n_images+1,:,:]=y_chunk
n_images+=1
This works fine and dandy. However, with 1 file, the size of the hdf5 is 6.7MB. With 2 files its 37MB ( should be 12 MB right?). With 10 its all the way up to 388MB (should be 67 right?)
So clearly adding the compression flag to the end of the 2nd and third line isn't working as intended. How can I achieve something like this?
I ended up doing this successfully using pytables.
def get_arrays(each_file):
lab = color.rgb2lab(io.imread(each_file))
X = lab[:,:,:1]
y = lab[:,:,1:]
X_rows,X_columns,X_channels=X.shape
y_rows,y_columns,y_channels=y.shape
X_channels_first = np.transpose(X,(2,0,1))
X_sample = np.expand_dims(X_channels_first,axis=0)
X_3d = np.tile(X_sample,(1,3,1,1))
X_3d_scaled = X_3d * 255.0/X_3d.max()
hc = extract_hypercolumn(model,[3,8,15,22],X_3d_scaled)
hc_scaled = (hc -hc.min())/(hc.max()-hc.min())
print hc_scaled.max(),hc_scaled.min()
hc_expand_dims = np.expand_dims(hc_scaled,axis=0)
y_reshaped = np.reshape(y,(y_rows*y_columns,y_channels))
classed_pixels_first = KNN.predict_proba(y_reshaped)
classed_classes_first = np.transpose(classed_pixels_first,(1,0))
classed_expand_dims = np.expand_dims(classed_classes_first,axis=0)
print "hypercolumn shape: ",hc_expand_dims.shape,"classified output color shape: ",classed_expand_dims.shape
return hc_expand_dims,classed_expand_dims
filters = tables.Filters(complevel=5, complib='zlib')
with tables.openFile('raw.h5','w') as f:
# filters = tables.Filters(complib='blosc', complevel=5)
dset_X = f.create_earray(f.root, 'X', tables.Atom.from_dtype(np.dtype('Float64')), (0,960,224,224),filters=filters)
dset_y = f.create_earray(f.root, 'y', tables.Atom.from_dtype(np.dtype('Float64')), (0,112,224*224),filters=filters)
for fl in files[0:12000]:
X_chunk,y_chunk=get_arrays(fl)
dset_X.append(X_chunk)
dset_y.append(y_chunk)
I am trying to make a program that will display total stock of cement, brick, spanner, mirror, and hammer. But the problem Please help me
is thsi program keeps showing me' cementinVar is not defined' but i already defined it above as (cementinVar = Tkinter.IntVar()) .
def textboxvalue2():
Total_StockIn = 0
CementIn = cementinVar.get()
HammerIn = hammerinVar.get()
SpannerIn = spannerinVar.get()
BrickIn = brickinVar.get()
MirrorIn = mirrorinVar.get()
CementOut = cementoutVar.get()
HammerOur = hammeroutVar.get()
SpannerOut = spanneroutVar.get()
BrickOut = brickoutVar.get()
MirrorOut = mirroroutVar.get()
Total_StockIn = (CementIn + HammerIn + SpannerIn + BrickIn + MirrorIn)+Total_StockIn
StockInLabel = Tkinter.Label(sub,text='The total stock in is '+str(Total_StockIn))
StockInLabel.grid(row=7, column =2)
You define cementinVar in another scope. You have two possible solutions:
Use a global variable
Use a class variable
I have created a class, ParRec, that reads data from Par/Rec-files (binary images -> numpy-arrays), and now I want to add additional methods to the class to increase functionality, such as a method createFigure(self, ind) that would draw an image of the 2D-image at ind in the 3D-stack of images.
However, this doesn't work no matter how I try, I only get empty figures which are "not responding". There is nothing wrong with the data per se, because when I saved the array to outside the python script and did the exact same thing as in the createFigure-method it did work. These are the relevant parts of the code:
import numpy as np
import matplotlib.pyplot as plt
class ParRec():
def __init__(self, filename, equalResolution = True):
"""
This class is used to read and create a ParRec-object, which contains
arrays of parameters and the corresponding image matrix, in a similar way
to the IDL-struct system previously implemented.
Additionally, the class has several methods that can be called later to
simplify calculations, e.g. removePhaseImages and selectSlice.
filename - full pathname to the Par/Rec-files, without .extension
equalResolution - if set to false, ParRec-object collects parameters like
xres and yres in arrays, otherwise they are constants
and all images in the stack are assumed to be of equal
dimensions.
"""
self.slice_number = 0
self.echo_number = 0
self.dynamic_scan_number = 0
self.cardiac_phase_number = 0
self.image_type_mr = 0
self.scanning_sequence = 0
self.index_in_REC_file = 0 # (in images)
self.image_pixel_size = 0 # (in bits)
self.scan_percentage = 0
self.recon_resolution = 0 # (x y)
self.rescale_intercept = 0
self.rescale_slope = 0
self.scale_slope = 0
self.window_center = 0
self.window_width = 0
self.image_angulation = 0 # (ap,fh,rl in degrees)
self.image_offcentre = 0 # (3*float)
self.slice_thickness = 0 # (in mm)
self.slice_gap = 0 # (in mm)
self.image_display_orientation = 0
self.slice_orientation = 0 # (TRA/SAG/COR) = (1/2/3)
self.fmri_status_indication = 0
self.image_type_ed_es = 0 # (end diast/end syst)
self.pixel_spacing = 0 # (x y) (in mm)
self.echo_time = 0
self.dyn_scan_begin_time = 0
self.trigger_time = 0
self.diffusion_b_factor = 0
self.number_of_averages = 0
self.image_flip_angle = 0 # (in degrees)
self.cardiac_frequency = 0 # (bpm)
self.minimum_RR_interval = 0 # (in ms)
self.maximum_RR_interval = 0 # (in ms)
self.turbo_factor = 0 # (0=no turbo)
self.inversion_delay = 0 # (in ms)
self.diffusion_b_value_number = 0 # (imagekey!)
self.gradient_orientation_number = 0 # (imagekey!)
self.contrast_type = 0
self.diffusion_anisotropy_type = 0
self.diffusion = 0 # (ap, fh, rl)
self.label_type = None # (ASL) (imagekey!)
self.xres = 0
self.yres = 0
self.size = 0
self.equalResolution = equalResolution
# Read ParRec-files
self.readPar(filename)
self.readRec(filename)
# Get number of slices, dynamics, information about phase images etc.
self.getAdditionalData()
def readPar(self,filename)
...
def redRec(self,filename)
...
self.matrix = ...
def createFigure(self, ind):
img = self.matrix[:,:,ind].astype(np.float32)
fig = plt.figure()
plt.imshow(img, cmap = plt.cm.gray)
return fig
if __name__ == '__main__':
filename = '...\filename'
obj = ParRec(filename)
fig = obj.createFigure(0)
plt.show()
Can anybody explain what's going on? That is, why the image-drawing doesn't work when used as a class-method like this, and how to make it work?
EDIT: Inserted the init method, and managed to screw up the indentation a bit, but that is not a problem in the original code.
Best regards,
Mikael