uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
8522048a8c0c2026572de78d
train
function
def drift_v(ele): """ Drift V list from ele dict """ # Let v[0] be the original ele, so the indexing looks the same. v = [ele, ele['zedge'], 0.0] # optional if 'radius' in ele: v[2] = ele['radius'] return v
def drift_v(ele):
""" Drift V list from ele dict """ # Let v[0] be the original ele, so the indexing looks the same. v = [ele, ele['zedge'], 0.0] # optional if 'radius' in ele: v[2] = ele['radius'] return v
V1: zedge V2: radius Not used. """ v = v_from_line(line) d={} d['zedge'] = float(v[1]) d['radius'] = float(v[2]) return d def drift_v(ele):
64
64
78
5
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
drift_v
drift_v
465
474
465
465
ffbaadf188664d065321c9ce3da63fd556105fd7
bigcode/the-stack
train
e77672b1cd23444a17b54774
train
function
def load_fieldmaps(eles, dir): """ Parses fieldmap data from list of elements. """ fmapdata={} for ele in eles: if 'filename' not in ele: continue name = ele['filename'] # Skip already parsed files if name in fmapdata: continue ...
def load_fieldmaps(eles, dir):
""" Parses fieldmap data from list of elements. """ fmapdata={} for ele in eles: if 'filename' not in ele: continue name = ele['filename'] # Skip already parsed files if name in fmapdata: continue type = ele['type'] ...
enoid':fieldmaps.read_solenoid_fieldmap, 'emfield_cylindrical':fieldmaps.read_fieldmap_symlink, # TODO: better parsing 'emfield_cartesian':fieldmaps.read_fieldmap_symlink # TODO: better parsing } def load_fieldmaps(eles, dir):
64
64
129
9
55
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fieldmaps
load_fieldmaps
1,359
1,382
1,359
1,359
41694f615f5ab725d35c385956ad52bd37e731a2
bigcode/the-stack
train
7f3761835fa3eb4f8b5ddb0d
train
function
def write_beam_v(ele): """ write_beam Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s']] return v
def write_beam_v(ele):
""" write_beam Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s']] return v
d['sample_frequency'] = int(x[1]) d['s'] = float(v[3]) if int(x[2]) in [40, 50]: print('warning, overwriting file fort.'+x[2]) return d def write_beam_v(ele):
64
64
67
7
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
write_beam_v
write_beam_v
1,008
1,016
1,008
1,008
415299b6e639a0f58d0284a6082650f187368282
bigcode/the-stack
train
0787240b47bef2fea23ca1a2
train
function
def load_fort18(filePath, keys=FORT_KEYS[18]): ''' From impact manual v2: 1st col: time (secs) 2nd col: distance (m) 3rd col: gamma 4th col: kinetic energy (MeV) 5th col: beta 6th col: Rmax (m) R is measured from the axis of pipe 7th col: rms energy deviation normali...
def load_fort18(filePath, keys=FORT_KEYS[18]):
''' From impact manual v2: 1st col: time (secs) 2nd col: distance (m) 3rd col: gamma 4th col: kinetic energy (MeV) 5th col: beta 6th col: Rmax (m) R is measured from the axis of pipe 7th col: rms energy deviation normalized by MC^2 ''' return load_fortX(fileP...
_MeV','mean_beta', 'max_r', 'sigma_gamma'] FORT_UNITS[18] = ['s', 'm', '1', 'MeV', '1', 'm', '1'] def load_fort18(filePath, keys=FORT_KEYS[18]):
64
64
118
15
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort18
load_fort18
1,614
1,623
1,614
1,614
654874fb3dc800b86f855dd2686e74c4db0df6fc
bigcode/the-stack
train
c5e97d07d6c9c4b99656e0ee
train
function
def emfield_cartesian_v(ele): """ emfield_cartesian V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int( ele['filename'].split('1T')[1].split('.')[0] ) v = [ele, ele['zedge'], ele['rf_field_s...
def emfield_cartesian_v(ele):
""" emfield_cartesian V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int( ele['filename'].split('1T')[1].split('.')[0] ) v = [ele, ele['zedge'], ele['rf_field_scale'], ele['rf_frequency'], e...
1T'+str(int(float(v[5])))+'.T7' d['radius'] = float(v[6]) # Not used: d2 = parse_misalignments(v[7:12]) # d.update(d2) return d def emfield_cartesian_v(ele):
64
64
135
8
55
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
emfield_cartesian_v
emfield_cartesian_v
829
846
829
829
b44cb2fb587dd84645c4ba840c8a2c0609342586
bigcode/the-stack
train
23c56830468ccf338947f7f8
train
function
def parse_impact_particles(filePath, names=('x', 'GBx', 'y', 'GBy', 'z', 'GBz'), skiprows=0): """ Parse Impact-T input and output particle data. Typical filenames: 'partcl.data', 'fort.40', 'fort.50'. Note that partcl.data has the number of par...
def parse_impact_particles(filePath, names=('x', 'GBx', 'y', 'GBy', 'z', 'GBz'), skiprows=0):
""" Parse Impact-T input and output particle data. Typical filenames: 'partcl.data', 'fort.40', 'fort.50'. Note that partcl.data has the number of particles in the first line, so skiprows=1 should be used. Returns a structured numpy array Impact-T input/output particles distribion...
attice'] = eles d['fieldmaps'] = fieldmaps return d #----------------------------------------------------------------- #----------------------------------------------------------------- # Particles def parse_impact_particles(filePath, names=('x', 'GBx', 'y...
70
70
235
38
31
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_impact_particles
parse_impact_particles
1,568
1,594
1,568
1,570
af298fef8413c1763d7ad76c4d39523a29f3058a
bigcode/the-stack
train
bc42f1a5192ffad22876ae64
train
function
def write_slice_info_v(ele): """ write_slice_info Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s']] return v
def write_slice_info_v(ele):
""" write_slice_info Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s']] return v
2]) v = v_from_line(line) d={} d['n_slices'] = Bnseg d['filename'] = 'fort.'+str(Bmpstp) d['s'] = float(v[3]) return d def write_slice_info_v(ele):
64
64
67
7
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
write_slice_info_v
write_slice_info_v
1,298
1,306
1,298
1,298
4611aa12cc897df25ca1d1684d4b66e166c8813c
bigcode/the-stack
train
3263b7ed17b77caebc91ff91
train
function
def load_fort(filePath, type = None, verbose=True): """ Loads a fort file, automatically detecting its type and selecting a loader. """ if not type: type = fort_type(filePath) if verbose: if type in FORT_DESCRIPTION: print('Loaded fort', type,':', FORT_DESCRIPTI...
def load_fort(filePath, type = None, verbose=True):
""" Loads a fort file, automatically detecting its type and selecting a loader. """ if not type: type = fort_type(filePath) if verbose: if type in FORT_DESCRIPTION: print('Loaded fort', type,':', FORT_DESCRIPTION[type]) else: print('unknown t...
_DESCRIPTION and verbose: print('Warning: unknown fort file_type for:', filePath) if file_type not in FORT_LOADER and verbose: print('Warning: no fort loader yet for:', filePath) return file_type def load_fort(filePath, type = None, verbose=True):
64
64
168
14
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort
load_fort
1,913
1,939
1,913
1,913
11f694b2dcd7e71ba14b2067e25ce4f36b7e6d65
bigcode/the-stack
train
60a9e4891cc7edd70dae246c
train
function
def solrf_v(ele): """ Solrf V list from ele dict. V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int(ele['filename'].split('rfdata')[1]) v = [ele, ele['zedge'], 1.0, 0.0, 0.0, file_id, 0.0] # optional if 'rf_fiel...
def solrf_v(ele):
""" Solrf V list from ele dict. V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int(ele['filename'].split('rfdata')[1]) v = [ele, ele['zedge'], 1.0, 0.0, 0.0, file_id, 0.0] # optional if 'rf_field_scale' in ele: v...
'] = 'rfdata'+str(int(float(v[5]))) d['radius'] = float(v[6]) d2 = parse_misalignments(v[7:12]) d.update(d2) d['solenoid_field_scale'] = float(v[12]) return d def solrf_v(ele):
70
70
236
6
63
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
solrf_v
solrf_v
746
772
746
746
d7b6606ec49c48b8c8dbec51f0394481fac82f4e
bigcode/the-stack
train
bfdbc4b05ce4eb9ff68edb4c
train
function
def parse_type(line): """ Parse a lattice line. This is the fourth item in the line. Returns the type as a string. """ if is_commented(line): return 'comment' i=int(line.split()[3]) if i in ele_type: return ele_type[i] else: #print('Undocumented: ', li...
def parse_type(line):
""" Parse a lattice line. This is the fourth item in the line. Returns the type as a string. """ if is_commented(line): return 'comment' i=int(line.split()[3]) if i in ele_type: return ele_type[i] else: #print('Undocumented: ', line) return 'un...
point_to_point_spacecharge', -16:'heat_beam', -17:'rotate_beam', -99:'stop' } # Inverse dictionary itype_of = {} for k in ele_type: itype_of[ele_type[k]] = k def parse_type(line):
64
64
86
5
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_type
parse_type
432
446
432
432
42211ccf025ea78326f8e8ab6d4a2694aa0dd494
bigcode/the-stack
train
fbf712a86ad5ed7eecf8b659
train
function
def stop_v(ele): """ stop Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. # V1 and V2 are not used. # Bad documentation? Looks like V1 and V3 are used dummy = 0.0 v = [ele, ele['s'], dummy, ele['s']] return v
def stop_v(ele):
""" stop Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. # V1 and V2 are not used. # Bad documentation? Looks like V1 and V3 are used dummy = 0.0 v = [ele, ele['s'], dummy, ele['s']] return v
parse_stop(line): """ Stop (type -99) If bytpe = −99, stop the simulation at given location V3(m). """ v = v_from_line(line) d={'s':float(v[3])} return d def stop_v(ele):
64
64
92
5
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
stop_v
stop_v
1,214
1,227
1,214
1,214
8c095a7016780b8bdf7339317d2d74dc9a30aca8
bigcode/the-stack
train
41175225a070c6190aac2815
train
function
def quadrupole_v(ele): """ Quadrupole V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. v = [ele, ele['zedge'], ele['b1_gradient'], 0, 0.0] if 'file_id' in ele: v[3] = ele['file_id'] else: v[3] = ele['L...
def quadrupole_v(ele):
""" Quadrupole V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. v = [ele, ele['zedge'], ele['b1_gradient'], 0, 0.0] if 'file_id' in ele: v[3] = ele['file_id'] else: v[3] = ele['L_effective'] ...
= parse_misalignments(v[5:10]) d.update(d2) if len(v) > 11: d['rf_frequency'] = float(v[10]) d['rf_phase_deg'] = float(v[11]) return(d) def quadrupole_v(ele):
63
64
183
7
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
quadrupole_v
quadrupole_v
556
579
556
556
5900406d5244af13db163d41a26aeed44aa1eb17
bigcode/the-stack
train
e47c2528edffde58d20a0b1a
train
function
def remove_comments(lines): return [l.split('!')[0] for l in lines if len(l) >0 and not is_commented(l)]
def remove_comments(lines):
return [l.split('!')[0] for l in lines if len(l) >0 and not is_commented(l)]
- # Util def is_commented(line, commentchar='!'): sline = line.strip() # remove spaces if len(sline) == 0: return True return sline[0] == commentchar # Strip comments, and trailing comments def remove_comments(lines):
64
64
32
5
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
remove_comments
remove_comments
306
307
306
306
648a4a6d8a65d3c5703aaea4af50326d9a9d8159
bigcode/the-stack
train
f7b2286a59b20832655aca12
train
function
def parse_drift(line): """ Drift (type 0) V1: zedge V2: radius Not used. """ v = v_from_line(line) d={} d['zedge'] = float(v[1]) d['radius'] = float(v[2]) return d
def parse_drift(line):
""" Drift (type 0) V1: zedge V2: radius Not used. """ v = v_from_line(line) d={} d['zedge'] = float(v[1]) d['radius'] = float(v[2]) return d
()[3]) if i in ele_type: return ele_type[i] else: #print('Undocumented: ', line) return 'undocumented' # Collect a dict of type:list of valid keys VALID_KEYS={} ELE_DEFAULTS={} #----------------------------------------------------------------- def parse_drift(line):
64
64
74
6
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_drift
parse_drift
453
464
453
453
592a49b6379be23842a06410d150ad98f105bfd5
bigcode/the-stack
train
9cfec18954c27cc92d410cf4
train
function
def v_from_line(line): """ Extracts the V values from an element line. Returns: v: list, with v[0] as the original line, so the indexing starts at 1 """ v = line.split('/')[0].split()[3:] # V data starts with index 4 v[0] = line # Preserve original line return v
def v_from_line(line):
""" Extracts the V values from an element line. Returns: v: list, with v[0] as the original line, so the indexing starts at 1 """ v = line.split('/')[0].split()[3:] # V data starts with index 4 v[0] = line # Preserve original line return v
""" slines = remove_comments(lines) latline = slines[9] for i in range(len(lines)): if latline in lines[i]: return i print('Error: no lattice found in stripped lines:', slines) raise def v_from_line(line):
64
64
86
6
57
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
v_from_line
v_from_line
346
355
346
346
dd8f0a1804f168c473cf53c25e75f4747729aaed
bigcode/the-stack
train
16a8bf258b69335fe9c1c5d4
train
function
def parse_line(line, names, types): """ parse line with expected names and types Example: parse_line(line, ['dt', 'ntstep', 'nbunch'], [float, int,int]) """ x = line.split() values = [types[i](x[i]) for i in range(len(x))] return dict(zip(names, values))
def parse_line(line, names, types):
""" parse line with expected names and types Example: parse_line(line, ['dt', 'ntstep', 'nbunch'], [float, int,int]) """ x = line.split() values = [types[i](x[i]) for i in range(len(x))] return dict(zip(names, values))
return True return sline[0] == commentchar # Strip comments, and trailing comments def remove_comments(lines): return [l.split('!')[0] for l in lines if len(l) >0 and not is_commented(l)] def parse_line(line, names, types):
63
64
80
9
54
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_line
parse_line
310
320
310
310
3c8a5327d02ebe955a650a4c1a27eb41e03ce739
bigcode/the-stack
train
3268cecb7477d008dd51f50d
train
function
def parse_impact_input(filePath, verbose=False): """ Parse and ImpactT.in file into header, lattice, fieldmaps """ # Full path path, _ = os.path.split(filePath) # Read lines try: with open(filePath, 'r') as f: data = f.read() except UnicodeDecodeErr...
def parse_impact_input(filePath, verbose=False):
""" Parse and ImpactT.in file into header, lattice, fieldmaps """ # Full path path, _ = os.path.split(filePath) # Read lines try: with open(filePath, 'r') as f: data = f.read() except UnicodeDecodeError: with open(filePath, 'r', encoding="ut...
counter[t]+1 e['name'] = e['type']+'_'+str(counter[t]) # Try from description if 'description' in e: alias_name = tools.find_property(e['description'], 'name') if alias_name: e['name'] = alias_name def parse_lattice(lines): ...
112
113
378
11
100
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_impact_input
parse_impact_input
1,506
1,560
1,506
1,506
75736f0d9c9bb8f0c484c73ee369b679f6dca1fb
bigcode/the-stack
train
6fb75bcbd4c9e946e0094ca1
train
function
def load_fort60(filePath): """ Returns dict with 'initial_particle_slices' """ data = load_fort60_and_70(filePath) return {'initial_particle_slices':data}
def load_fort60(filePath):
""" Returns dict with 'initial_particle_slices' """ data = load_fort60_and_70(filePath) return {'initial_particle_slices':data}
= parse_impact_particles(filePath) return {'initial_particles':data} def load_fort50(filePath): """ Returns dict with 'final_particles' """ data = parse_impact_particles(filePath) return {'final_particles':data} def load_fort60(filePath):
63
64
45
8
55
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort60
load_fort60
1,801
1,806
1,801
1,801
0fe4e8cbcd1f276be99ce1c06e54f3bba361a22a
bigcode/the-stack
train
313d5ea24e800c4851057da4
train
function
def load_fort27(filePath, keys=FORT_KEYS[27]): ''' fort.27: maximum amplitude information 1st col: time (secs) 2nd col: z distance (m) 3rd col: Max. X (m) 4th col: Max. Px (MC) 5th col: Max. Y (m) 6th col: Max. Py (MC) 7th col: Max. Z (m) (with respect to centroid) 8th col: Max....
def load_fort27(filePath, keys=FORT_KEYS[27]):
''' fort.27: maximum amplitude information 1st col: time (secs) 2nd col: z distance (m) 3rd col: Max. X (m) 4th col: Max. Px (MC) 5th col: Max. Y (m) 6th col: Max. Py (MC) 7th col: Max. Z (m) (with respect to centroid) 8th col: Max. Pz (MC) ''' return load_fortX(filePath...
_amplitude_z','max_amplitude_gammabeta_z'] FORT_UNITS[27] = ['s', 'm', 'm', '1', 'm', '1', 'm', '1'] def load_fort27(filePath, keys=FORT_KEYS[27]):
64
64
140
15
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort27
load_fort27
1,666
1,678
1,666
1,666
d640fbf71d5ec661dc3b1c0164ec5874c58a3b76
bigcode/the-stack
train
893ca82d7e8eca0c8d5c8700
train
function
def emfield_cylindrical_v(ele): """ emfield_cylindrical V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int( ele['filename'].split('1T')[1].split('.')[0] ) v = [ele, ele['zedge'], ele['rf_f...
def emfield_cylindrical_v(ele):
""" emfield_cylindrical V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int( ele['filename'].split('1T')[1].split('.')[0] ) v = [ele, ele['zedge'], ele['rf_field_scale'], ele['rf_frequency'...
'+str(int(float(v[5])))+'.T7' d['radius'] = float(v[6]) # Not used: d2 = parse_misalignments(v[7:12]) # d.update(d2) return d def emfield_cylindrical_v(ele):
64
64
140
10
53
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
emfield_cylindrical_v
emfield_cylindrical_v
899
916
899
899
401cbab625510d75369c376cf77d201419025e87
bigcode/the-stack
train
50d9ff177ba1a38db6a7597a
train
function
def change_timestep_v(ele): """ change_timestep Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s'], ele['dt']] return v
def change_timestep_v(ele):
""" change_timestep Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s'], ele['dt']] return v
after location V3(m). The maximum number of time step change is 100. """ v = v_from_line(line) d={} d['dt'] = float(v[4]) d['s'] = float(v[3]) return d def change_timestep_v(ele):
64
64
71
7
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
change_timestep_v
change_timestep_v
1,076
1,084
1,076
1,076
8cad51a9fbdcf3852e8e5550b0dcaea427f3e5b4
bigcode/the-stack
train
3be042049f2e61a090e313fc
train
function
def parse_solenoid(line): """ (type 3) V1: zedge V2: Bz0 (T) V3: file ID V4: radius V5: x misalignment error Not used. V6: y misalignment error Not used. V7: rotation error x Not used. V8: rotation error y Not used. V9: rotation error z Not used. The discre...
def parse_solenoid(line):
""" (type 3) V1: zedge V2: Bz0 (T) V3: file ID V4: radius V5: x misalignment error Not used. V6: y misalignment error Not used. V7: rotation error x Not used. V8: rotation error y Not used. V9: rotation error z Not used. The discrete magnetic field data is ...
, 'file_id':0, 'radius':0, 'rf_frequency':0, 'rf_phase_deg':0, 'x_offset':0, 'y_offset':0, 'x_rotation':0, 'y_rotation':0, 'z_rotation':0} #----------------------------------------------------------------- def parse_solenoid(line):
75
76
255
6
69
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_solenoid
parse_solenoid
598
628
598
598
70066aa083994f80657dfc836ece1d49939d470b
bigcode/the-stack
train
b245cc490e410a1ffaca03e3
train
function
def header_str(H): """ Summary information about the header """ qb_pC = H['Bcurr']/H['Bfreq']*1e12 Nbunch = H['Nbunch'] species = identify_species(H['Bmass'], H['Bcharge']) if H['Flagimg']: start_condition = 'Cathode start at z = 0 m\n emission time: '+str(H['Temission'])+' s\n...
def header_str(H):
""" Summary information about the header """ qb_pC = H['Bcurr']/H['Bfreq']*1e12 Nbunch = H['Nbunch'] species = identify_species(H['Bmass'], H['Bcharge']) if H['Flagimg']: start_condition = 'Cathode start at z = 0 m\n emission time: '+str(H['Temission'])+' s\n image charges ne...
in ALL_HEADER_NAMES: if k not in h: print('Missing key:', k) return False else: v1 = h.pop(k, None) # Check type conversion v2 = HEADER_TYPE_OF[k](v1) if v1 - v2 !=0: print('Type conversion failed: ', v1, v2) ...
107
107
357
5
101
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
header_str
header_str
207
248
207
207
f15638bd91d7e6e7c886f969629652501ddc0e69
bigcode/the-stack
train
0ea6042a74be22efda9dd9f0
train
function
def load_fort37(filePath, keys=FORT_KEYS[37] ): """Same as load_fort27, but in the dipole coordinate system""" return load_fortX(filePath, keys)
def load_fort37(filePath, keys=FORT_KEYS[37] ):
"""Same as load_fort27, but in the dipole coordinate system""" return load_fortX(filePath, keys)
Path, keys) def load_fort36(filePath, keys=FORT_KEYS[36] ): """Same as load_fort26, but in the dipole coordinate system""" return load_fortX(filePath, keys) def load_fort37(filePath, keys=FORT_KEYS[37] ):
64
64
44
16
48
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort37
load_fort37
1,745
1,747
1,745
1,745
f79e666d70a60de87d07feadf27f9cc23cdb90a3
bigcode/the-stack
train
07ae4e788bf8a4f44cd5bda1
train
function
def load_fort29(filePath, keys=FORT_KEYS[29]): ''' fort.29: cubic root of 3rd moments of the beam distribution 1st col: time (secs) 2nd col: z distance (m) 3rd col: X (m) 4th col: Px (mc) 5th col: Y (m) 6th col: Py (mc) 7th col: Z (m) 8th col: Pz (mc) ''' re...
def load_fort29(filePath, keys=FORT_KEYS[29]):
''' fort.29: cubic root of 3rd moments of the beam distribution 1st col: time (secs) 2nd col: z distance (m) 3rd col: X (m) 4th col: Px (mc) 5th col: Y (m) 6th col: Py (mc) 7th col: Z (m) 8th col: Pz (mc) ''' return load_fortX(filePath, keys)
'moment3_z','moment3_gammabeta_z'] FORT_UNITS[29] = ['s', 'm', 'm', '1', 'm', '1', 'm', '1'] def load_fort29(filePath, keys=FORT_KEYS[29]):
64
64
132
15
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort29
load_fort29
1,695
1,707
1,695
1,695
beeaf202233f2aaa516e6533ce417aba6993b8fb
bigcode/the-stack
train
917e0824b6c121c8bfac627d
train
function
def parse_dipole(line): """ Dipole (type 4) V1: zedge V2: x field strength (T) V3: y field strength (T) V4: file ID file ID to contain the geometry information of bend. V5: half of gap width (m). V6: x misalignment error Not used. V7: y misalignment error Not used. V...
def parse_dipole(line):
""" Dipole (type 4) V1: zedge V2: x field strength (T) V3: y field strength (T) V4: file ID file ID to contain the geometry information of bend. V5: half of gap width (m). V6: x misalignment error Not used. V7: y misalignment error Not used. V8: rotation error x Not...
0, 'filename':'1T99.T7', 'radius':0, 'x_offset':0, 'y_offset':0, 'x_rotation':0, 'y_rotation':0, 'z_rotation':0} #----------------------------------------------------------------- def parse_dipole(line):
65
66
223
7
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_dipole
parse_dipole
662
685
662
662
c4af64d7c527ede08c84e07afaa05ade863800e6
bigcode/the-stack
train
6703fc95c20733f2ed330d34
train
function
def parse_offset_beam(line, warn=False): """ offset_beam (type -1) If btype = −1, steer the transverse beam centroid at given location V2(m) to position x offset V3(m) Px (γβx) offset V4 y offset V5(m) Py (γβy) offset V6 z offset V7(m) Pz (γβz) offset V8 ...
def parse_offset_beam(line, warn=False):
""" offset_beam (type -1) If btype = −1, steer the transverse beam centroid at given location V2(m) to position x offset V3(m) Px (γβx) offset V4 y offset V5(m) Py (γβy) offset V6 z offset V7(m) Pz (γβz) offset V8 Assumes zero if these are not pres...
, 'theta0_deg':0, 'filename':0, 'radius':0, 'x_offset':0, 'y_offset':0, 'x_rotation':0, 'y_rotation':0, 'z_rotation':0} #----------------------------------------------------------------- def parse_offset_beam(line, warn=False):
72
73
244
10
62
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_offset_beam
parse_offset_beam
932
959
932
932
69481de08c8cdd134bd85e02e6448d9aebe82e75
bigcode/the-stack
train
3e7fd87ecc8c8189e71a3666
train
function
def wakefield_v(ele): """ wakefield Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. # V1 and V2 are not used. dummy = 1 v = [ele, dummy, dummy, ele['s_begin'], ele['s'] ] if ele['method'] == 'analytical': v += [ele['iris_rad...
def wakefield_v(ele):
""" wakefield Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. # V1 and V2 are not used. dummy = 1 v = [ele, dummy, dummy, ele['s_begin'], ele['s'] ] if ele['method'] == 'analytical': v += [ele['iris_radius'], ele['gap'], ele...
+str(Bnseg) else: d['method'] = 'analytical' d['iris_radius'] = float(v[5]) d['gap'] = float(v[6]) d['period'] = float(v[7]) return d def wakefield_v(ele):
64
64
111
6
57
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
wakefield_v
wakefield_v
1,168
1,184
1,168
1,168
5af2c82c74a764a67abcf317cc632e43c86a1193
bigcode/the-stack
train
30d7a21a7dc5ba9b8d90fb62
train
function
def load_fort34(filePath, keys=FORT_KEYS[34] ): """Same as load_fort24, but in the dipole coordinate system""" return load_fortX(filePath, keys)
def load_fort34(filePath, keys=FORT_KEYS[34] ):
"""Same as load_fort24, but in the dipole coordinate system""" return load_fortX(filePath, keys)
Z FORT_UNITS[36] = FORT_UNITS[26] FORT_KEYS[ 37] = FORT_KEYS[ 27] # Amplitude FORT_UNITS[37] = FORT_UNITS[27] def load_fort34(filePath, keys=FORT_KEYS[34] ):
64
64
44
16
48
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort34
load_fort34
1,736
1,738
1,736
1,736
3c64fe3fb4b73c8bfd511abc382433e6fa65d6e3
bigcode/the-stack
train
eafa0ddd5ca97ad934a442c6
train
function
def ix_lattice(lines): """ Find index of beginning of lattice, end of header """ slines = remove_comments(lines) latline = slines[9] for i in range(len(lines)): if latline in lines[i]: return i print('Error: no lattice found in stripped lines:', slines) ...
def ix_lattice(lines):
""" Find index of beginning of lattice, end of header """ slines = remove_comments(lines) latline = slines[9] for i in range(len(lines)): if latline in lines[i]: return i print('Error: no lattice found in stripped lines:', slines) raise
(len(x))] return dict(zip(names, values)) def parse_header(lines): x = remove_comments(lines) d = {} for i in range(9): d.update(parse_line(x[i], HEADER_NAMES[i], HEADER_TYPES[i])) return(d) # def ix_lattice(lines):
63
64
77
6
57
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
ix_lattice
ix_lattice
332
344
332
332
5af9124a3056bb6c48ba3c1f2cf4a6d3dcc946c6
bigcode/the-stack
train
a620f0729c300031a9d4ee52
train
function
def fort_files(path): """ Find fort.X fliles in path """ assert os.path.isdir(path) flist = os.listdir(path) fortfiles=[] for f in flist: if f.startswith('fort.'): fortfiles.append(os.path.join(path,f)) return fortfiles
def fort_files(path):
""" Find fort.X fliles in path """ assert os.path.isdir(path) flist = os.listdir(path) fortfiles=[] for f in flist: if f.startswith('fort.'): fortfiles.append(os.path.join(path,f)) return fortfiles
70(filePath) return {'initial_particle_slices':data} def load_fort70(filePath): """ Returns dict with 'final_particle_slices' """ data = load_fort60_and_70(filePath) return {'final_particle_slices':data} def fort_files(path):
64
64
67
5
59
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
fort_files
fort_files
1,817
1,827
1,817
1,817
344017ea1be890d977925b6ae53d1b69dcb55988
bigcode/the-stack
train
47e13d1e8275c699f0453734
train
function
def parse_write_beam_for_restart(line): """ Write_beam_for_restart (type -3) If btype = −3, output particle phase-space and prepare restart at given location V3(m) into filename fort.(Bmpstp+myid). Here, myid is processor id. On single processor, it is 0. If there are multiple restart lines in ...
def parse_write_beam_for_restart(line):
""" Write_beam_for_restart (type -3) If btype = −3, output particle phase-space and prepare restart at given location V3(m) into filename fort.(Bmpstp+myid). Here, myid is processor id. On single processor, it is 0. If there are multiple restart lines in the input file, only the last line matte...
v = [ele, dummy, dummy, ele['s']] return v ELE_DEFAULTS['write_beam'] = { 's':0, 'filename':'fort.99', 'sample_frequency':1} #----------------------------------------------------------------- def parse_write_beam_for_restart(line):
63
64
146
9
54
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_write_beam_for_restart
parse_write_beam_for_restart
1,026
1,040
1,026
1,026
59e21c1177f187ab27eb6d9c01726fa1cb8bb234
bigcode/the-stack
train
7a26362390d912620e165b11
train
function
def parse_misalignments(v): """ Parse misalignment portion of V list Common to several elements """ d = {} d['x_offset'] = float(v[0]) d['y_offset'] = float(v[1]) d['x_rotation'] = float(v[2]) d['y_rotation'] = float(v[3]) d['z_rotation'] = float(v[4]) return d
def parse_misalignments(v):
""" Parse misalignment portion of V list Common to several elements """ d = {} d['x_offset'] = float(v[0]) d['y_offset'] = float(v[1]) d['x_rotation'] = float(v[2]) d['y_rotation'] = float(v[3]) d['z_rotation'] = float(v[4]) return d
0] # optional if 'radius' in ele: v[2] = ele['radius'] return v ELE_DEFAULTS['drift'] = { 'zedge':0, 'radius':0 } #----------------------------------------------------------------- def parse_misalignments(v):
63
64
95
8
55
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_misalignments
parse_misalignments
483
494
483
483
da5203b071d178ee9950e4ff5c1edbeb42897ed5
bigcode/the-stack
train
0cc6f712400c713c6ae94e2c
train
function
def misalignment_v(ele): """ V list for misalignments """ v = [0.0, 0.0, 0.0, 0.0, 0.0] if 'x_offset' in ele: v[0] = ele['x_offset'] if 'y_offset' in ele: v[1] = ele['y_offset'] if 'x_rotation' in ele: v[2] = ele['x_rotation'] if 'y_rotation' in ele: v[3] = ele['y_rotation' ] if...
def misalignment_v(ele):
""" V list for misalignments """ v = [0.0, 0.0, 0.0, 0.0, 0.0] if 'x_offset' in ele: v[0] = ele['x_offset'] if 'y_offset' in ele: v[1] = ele['y_offset'] if 'x_rotation' in ele: v[2] = ele['x_rotation'] if 'y_rotation' in ele: v[3] = ele['y_rotation' ] if 'z_rotation' in ele: v[4...
= float(v[0]) d['y_offset'] = float(v[1]) d['x_rotation'] = float(v[2]) d['y_rotation'] = float(v[3]) d['z_rotation'] = float(v[4]) return d def misalignment_v(ele):
64
64
150
6
57
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
misalignment_v
misalignment_v
496
507
496
496
35761d1b0e9e864d921bb2164769e662c3cad4f9
bigcode/the-stack
train
9742f8d21b9276a931c7c7cd
train
function
def load_fort26(filePath, keys=FORT_KEYS[26]): '''From impact manual: fort.26: Z RMS size information 1st col: time (secs) 2nd col: centroid location (m) 3rd col: RMS size (m) 4th col: Centroid momentum normalized by MC 5th col: RMS momentum normalized by MC 6th col: Twiss parameter: -<z, ga...
def load_fort26(filePath, keys=FORT_KEYS[26]):
'''From impact manual: fort.26: Z RMS size information 1st col: time (secs) 2nd col: centroid location (m) 3rd col: RMS size (m) 4th col: Centroid momentum normalized by MC 5th col: RMS momentum normalized by MC 6th col: Twiss parameter: -<z, gamma*beta_z> 7th col: normalized RMS emittan...
'mean_z','sigma_z','mean_gammabeta_z', 'sigma_gammabeta_z', '-cov_z__gammabeta_z','norm_emit_z'] FORT_UNITS[26]= FORT_UNITS[25] def load_fort26(filePath, keys=FORT_KEYS[26]):
64
64
133
15
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort26
load_fort26
1,652
1,662
1,652
1,652
45ba0a8c86cffff19943b8dbf18364a40ed1c88d
bigcode/the-stack
train
616ebe2406d8868356b5246f
train
function
def add_s_position(elelist, s0=0): """ Add 's' to element list according to their length. s is at the end of an element. Assumes the list is in order. TODO: This isn't right """ #s0 = -2.1459294 s = s0 for ele in elelist: if 's' not in ele and 'zedge' in ele: ...
def add_s_position(elelist, s0=0):
""" Add 's' to element list according to their length. s is at the end of an element. Assumes the list is in order. TODO: This isn't right """ #s0 = -2.1459294 s = s0 for ele in elelist: if 's' not in ele and 'zedge' in ele: ele['s'] = ele['zedge'] + ele['L'...
d2 = ele_parsers[e['type']](line) e.update(d2) else: print('Warning: undocumented type', line) e['type'] ='undocumented' return e #----------------------------------------------------------------- def add_s_position(elelist, s0=0):
63
64
160
12
51
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
add_s_position
add_s_position
1,459
1,474
1,459
1,459
676e4e02b25a0921caa425b4985e3a6247b7e84f
bigcode/the-stack
train
c5dbd9de22f17b24e3fe517a
train
function
def parse_ele(line): """ Parse an Impact-T lattice line. Returns an ele dict. Parses everything after / as the 'description' """ if is_commented(line): return {'type':'comment', 'description':line} # Ele e = {} x = line.split('/') # Look for extra in...
def parse_ele(line):
""" Parse an Impact-T lattice line. Returns an ele dict. Parses everything after / as the 'description' """ if is_commented(line): return {'type':'comment', 'description':line} # Ele e = {} x = line.split('/') # Look for extra info past / # ...
ationally_symmetric_to_3d':parse_rotationally_symmetric_to_3d, 'wakefield':parse_wakefield, 'spacecharge':parse_spacecharge, 'write_slice_info':parse_write_slice_info, 'write_beam_for_restart':parse_write_beam_for_restart, 'stop':parse_stop ...
79
80
269
5
74
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_ele
parse_ele
1,409
1,453
1,409
1,409
3010191891b9322fed05401a1ae0bd4730e3f2a3
bigcode/the-stack
train
6059d7c9ee7d79050a2e3b7c
train
function
def parse_write_beam(line): """ Write_beam (type -2) If btype = −2, output particle phase-space coordinate information at given location V3(m) into filename fort.Bmpstp with particle sample frequency Bnseg. Here, the maximum number of phase- space files which can be output is 100. Here, 40 and ...
def parse_write_beam(line):
""" Write_beam (type -2) If btype = −2, output particle phase-space coordinate information at given location V3(m) into filename fort.Bmpstp with particle sample frequency Bnseg. Here, the maximum number of phase- space files which can be output is 100. Here, 40 and 50 should be avoided sin...
am'] = { 's':0, 'x_offset':0, 'px_offset':0, 'y_offset':0, 'py_offset':0, 'z_offset':0, 'pz_offset':0} #----------------------------------------------------------------- def parse_write_beam(line):
63
64
190
7
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_write_beam
parse_write_beam
987
1,004
987
987
b1813c62718b969aa90ce40b4448cbb60ef4f8bf
bigcode/the-stack
train
2ba30bfdfdb9ddce5cbe834a
train
function
def parse_emfield_cylindrical(line): """ emfield_cylindrical 112: EMfldCyl Read in discrete EM field data Ez(MV/m), Er(MV/m), and Hθ(A/m) as a function of (r,z) of EM field data (from SUPERFISH output). V1: zedge V2: rf_field_scale ! Typo in the manual V3: RF frequency ...
def parse_emfield_cylindrical(line):
""" emfield_cylindrical 112: EMfldCyl Read in discrete EM field data Ez(MV/m), Er(MV/m), and Hθ(A/m) as a function of (r,z) of EM field data (from SUPERFISH output). V1: zedge V2: rf_field_scale ! Typo in the manual V3: RF frequency V4: theta0_deg V5: file ID ...
alignment_v(ele) return v ELE_DEFAULTS['emfield_cartesian'] = { 'zedge':0, 'rf_field_scale':0, 'rf_frequency':0, 'theta0_deg':0, 'filename':0, 'radius':0, 'x_offset':0, 'y_offset':0, 'x_rotation':0, 'y_rotation':0, 'z_rotation':0} def parse_emfield_cylindrical(line)...
106
106
356
10
96
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_emfield_cylindrical
parse_emfield_cylindrical
861
897
861
861
d8c360507be8b7b09177eeae0cb9e578c0409466
bigcode/the-stack
train
a9c4b93a786fd6a0691c20c4
train
function
def header_bookkeeper(header, defaults=HEADER_DEFAULT, verbose=True): """ Checks header for missing or bad keys, fills in defaults. """ # Check for bad keys for k in header: if verbose and k not in defaults: print('Warning:', k, 'does not belong in header.') newheader = head...
def header_bookkeeper(header, defaults=HEADER_DEFAULT, verbose=True):
""" Checks header for missing or bad keys, fills in defaults. """ # Check for bad keys for k in header: if verbose and k not in defaults: print('Warning:', k, 'does not belong in header.') newheader = header.copy() # Fill defaults for k in defaults: if k n...
[item for sublist in HEADER_DEFAULTS for item in sublist] # Make dicts HEADER_DEFAULT = dict(zip(ALL_HEADER_NAMES, ALL_HEADER_DEFAULTS)) HEADER_TYPE = dict(zip(ALL_HEADER_NAMES, ALL_HEADER_TYPES)) def header_bookkeeper(header, defaults=HEADER_DEFAULT, verbose=True):
63
64
136
14
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
header_bookkeeper
header_bookkeeper
82
99
82
82
f940c41d82f864a27357aae7ec3edba9248e1643
bigcode/the-stack
train
56283b516a0ac7f853c51286
train
function
def parse_change_timestep(line): """ Change_timestep (type -4) If btype = −4, change the time step size from the initial Dt (secs) into V4 (secs) after location V3(m). The maximum number of time step change is 100. """ v = v_from_line(line) d={} d['dt'] = float(v[4]) d['s'] = ...
def parse_change_timestep(line):
""" Change_timestep (type -4) If btype = −4, change the time step size from the initial Dt (secs) into V4 (secs) after location V3(m). The maximum number of time step change is 100. """ v = v_from_line(line) d={} d['dt'] = float(v[4]) d['s'] = float(v[3]) return d
0.0 v = [ele, dummy, dummy, ele['s']] return v ELE_DEFAULTS['write_beam_for_restart'] = { 's':0, 'filename':'fort.99+myid'} #----------------------------------------------------------------- def parse_change_timestep(line):
63
64
103
7
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_change_timestep
parse_change_timestep
1,060
1,073
1,060
1,060
46111503816a83fc04618bd440d485b1b1c02cf3
bigcode/the-stack
train
bfd3cd5d926bf7e951e43a3e
train
function
def load_fort38(filePath, keys=FORT_KEYS[38]): ''' fort.38: reference particle information in dipole reference coordinate system (inside dipole ONLY) 1st col: time (secs) 2nd col: x distance (m) 3rd col: Px/MC 4th col: y (m) 5th col: Py/MC 6th col: z (m) 7th col: Pz/MC ''' ...
def load_fort38(filePath, keys=FORT_KEYS[38]):
''' fort.38: reference particle information in dipole reference coordinate system (inside dipole ONLY) 1st col: time (secs) 2nd col: x distance (m) 3rd col: Px/MC 4th col: y (m) 5th col: Py/MC 6th col: z (m) 7th col: Pz/MC ''' return load_fortX(filePath, keys)
eta_y', 'ref_z', 'ref_gammabeta_z', ] FORT_UNITS[38] = ['s', 'm', '1', 'm', '1', 'm', '1'] def load_fort38(filePath, keys=FORT_KEYS[38]):
64
64
121
15
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort38
load_fort38
1,752
1,761
1,752
1,752
1daafa6dffe10b2f0455c28d3304f72cfda2226e
bigcode/the-stack
train
74cd46aae570593c4b207a2b
train
function
def parse_wakefield(line): """ Wakefield (type -6) If btype = −6, turn on the wake field effects between location V3(m) and V4(m). If Bnseg is greater than 0, the longitudinal and transverse wake function will be read in from file “fort.Bmpstp”. If Bnseg ≤ 0, the code will use analytical wa...
def parse_wakefield(line):
""" Wakefield (type -6) If btype = −6, turn on the wake field effects between location V3(m) and V4(m). If Bnseg is greater than 0, the longitudinal and transverse wake function will be read in from file “fort.Bmpstp”. If Bnseg ≤ 0, the code will use analytical wake function described as fo...
the 3D simulation immediately after the electron emission. If there are multiple such lines in the input file, only the last line matters. """ v = v_from_line(line) d={} d['s'] = float(v[3]) return d def rotationally_symmetric_to_3d_v(ele): """ rotationally_symmetric_to...
170
171
570
7
163
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_wakefield
parse_wakefield
1,124
1,166
1,124
1,124
42b9c69b7f70e6b1f7ac526b91e508e5ebf4a030
bigcode/the-stack
train
7514a1b8155ebce5fcfbfcd4
train
function
def load_stats(path, species='electron', types=FORT_STAT_TYPES, verbose=False): """ Loads all Impact-T statistics output. Works with types= FORT_STAT_TYPES and FORT_DIPOLE_STAT_TYPES Returns dicts: data, units Converts gamma_beta_X keys to pX using the mass from the species, ...
def load_stats(path, species='electron', types=FORT_STAT_TYPES, verbose=False):
""" Loads all Impact-T statistics output. Works with types= FORT_STAT_TYPES and FORT_DIPOLE_STAT_TYPES Returns dicts: data, units Converts gamma_beta_X keys to pX using the mass from the species, in units eV/c. """ data = load_many_fort(path, types=types, v...
-20, # move on to next key without error. # https://numpy.org/devdocs/reference/generated/numpy.isclose.html#numpy.isclose pass else: # Data is not close enough to ignore differences. # Check that this data is ...
112
113
378
18
93
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_stats
load_stats
1,988
2,041
1,988
1,988
3d42dc3a7e9b76b3116f96d7c00694e5667c350c
bigcode/the-stack
train
29e75e600db65f4055d60db5
train
function
def parse_solrf(line): """ Solrf (type 105) V1: zedge, the real used field range in z is [zedge,zedge+Blength]. V2: scale of RF field V3: RF frequency V4: theta0 Initial phase in degree. V5: file ID V6: radius V7: x misalignment error V8: y misalignment error V9: rotati...
def parse_solrf(line):
""" Solrf (type 105) V1: zedge, the real used field range in z is [zedge,zedge+Blength]. V2: scale of RF field V3: RF frequency V4: theta0 Initial phase in degree. V5: file ID V6: radius V7: x misalignment error V8: y misalignment error V9: rotation error x V10: rot...
zedge'], ele['b_field_x'], ele['b_field'], ii, ele['half_gap'] ] return v ELE_DEFAULTS['dipole'] = { 'zedge':0, 'b_field_x':0, 'b_field':0, 'filename':'rfdata99', 'half_gap':0 } #----------------------------------------------------------------- def parse_solrf(line):
83
84
280
6
77
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_solrf
parse_solrf
716
744
716
716
0c55e412b63eabc6ed936795db6ee48664a90003
bigcode/the-stack
train
35690d4539fb573fbbdfa0fc
train
function
def load_fort25(filePath, keys=FORT_KEYS[25]): ''' Same columns as fort24, Y RMS ''' return load_fortX(filePath, keys)
def load_fort25(filePath, keys=FORT_KEYS[25]):
''' Same columns as fort24, Y RMS ''' return load_fortX(filePath, keys)
', 'sigma_y','mean_gammabeta_y', 'sigma_gammabeta_y', '-cov_y__gammabeta_y','norm_emit_y'] FORT_UNITS[25] = FORT_UNITS[24] def load_fort25(filePath, keys=FORT_KEYS[25]):
64
64
40
15
49
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort25
load_fort25
1,643
1,647
1,643
1,643
5b34369c87e598533d6e0290569be08c98550817
bigcode/the-stack
train
74a89899873f6c7c12fd3789
train
function
def parse_header(lines): x = remove_comments(lines) d = {} for i in range(9): d.update(parse_line(x[i], HEADER_NAMES[i], HEADER_TYPES[i])) return(d)
def parse_header(lines):
x = remove_comments(lines) d = {} for i in range(9): d.update(parse_line(x[i], HEADER_NAMES[i], HEADER_TYPES[i])) return(d)
: parse_line(line, ['dt', 'ntstep', 'nbunch'], [float, int,int]) """ x = line.split() values = [types[i](x[i]) for i in range(len(x))] return dict(zip(names, values)) def parse_header(lines):
63
64
44
5
58
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_header
parse_header
324
329
324
324
3fc24c6d5f19e52cd6d30bb0fb892c1bac0e3995
bigcode/the-stack
train
d0b5e00888f2bea1611c9d78
train
function
def solenoid_v(ele): """ Solenoid V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int( ele['filename'].split('1T')[1].split('.')[0] ) v = [ele, ele['zedge'], ele['b_field'], file_id, ele['radius']] ...
def solenoid_v(ele):
""" Solenoid V list from ele dict V[0] is the original ele """ # Let v[0] be the original ele, so the indexing looks the same. file_id = int( ele['filename'].split('1T')[1].split('.')[0] ) v = [ele, ele['zedge'], ele['b_field'], file_id, ele['radius']] #misalignment lis...
'1T'+str(int(float(v[3])))+'.T7' d['radius'] = float(v[4]) # Not used: d2 = parse_misalignments(v[5:10]) # d.update(d2) return d def solenoid_v(ele):
64
64
114
6
57
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
solenoid_v
solenoid_v
632
648
632
632
f7aa0eb8b6be8da7cb19825e3440b484f02f2661
bigcode/the-stack
train
fdb14619a505067fd9820edf
train
function
def load_fort36(filePath, keys=FORT_KEYS[36] ): """Same as load_fort26, but in the dipole coordinate system""" return load_fortX(filePath, keys)
def load_fort36(filePath, keys=FORT_KEYS[36] ):
"""Same as load_fort26, but in the dipole coordinate system""" return load_fortX(filePath, keys)
Path, keys) def load_fort35(filePath, keys=FORT_KEYS[35] ): """Same as load_fort25, but in the dipole coordinate system""" return load_fortX(filePath, keys) def load_fort36(filePath, keys=FORT_KEYS[36] ):
64
64
44
16
48
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
load_fort36
load_fort36
1,742
1,744
1,742
1,742
09ddc19108bd03dbf29998d7e53a90a223e644c4
bigcode/the-stack
train
fa9d141ba27e12ef6197cfe8
train
function
def dipole_v(ele): """ dipole Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 # Get file integer f = ele['filename'] ii = int(f.split('rfdata')[1]) v = [ele, ele['zedge'], ele['b_field_x'], ele['b_field'], ii, ele['half_gap'...
def dipole_v(ele):
""" dipole Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 # Get file integer f = ele['filename'] ii = int(f.split('rfdata')[1]) v = [ele, ele['zedge'], ele['b_field_x'], ele['b_field'], ii, ele['half_gap'] ] retur...
_field_x'] = float(v[2]) d['b_field'] = float(v[3]) d['filename'] = 'rfdata'+str(int(float(v[4]))) d['half_gap'] = float(v[5]) return d def dipole_v(ele):
63
64
107
6
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
dipole_v
dipole_v
688
701
688
688
c2717c5c16e338fbd4ee8d7ec6664af9285af6dd
bigcode/the-stack
train
3cf9a8cbf91eef37127eda9e
train
function
def parse_quadrupole(line): """ Quadrupole (type 1) V1: zedge V2: quad gradient (T/m) V3: file ID If > 0, then include fringe field (using Enge function) and V3 = effective length of quadrupole. V4: radius (m) V5: x misalignment error (m) V6: y misalignment error (m)...
def parse_quadrupole(line):
""" Quadrupole (type 1) V1: zedge V2: quad gradient (T/m) V3: file ID If > 0, then include fringe field (using Enge function) and V3 = effective length of quadrupole. V4: radius (m) V5: x misalignment error (m) V6: y misalignment error (m) V7: rotation error x (r...
3] = ele['y_rotation' ] if 'z_rotation' in ele: v[4] = ele['z_rotation' ] return v ELE_DEFAULTS['misalignment'] = { 'x_offset':0, 'y_offset':0, 'x_rotation':0, 'y_rotation':0, 'z_rotation':0} #-----------------------------------------------------------...
95
96
323
8
87
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_quadrupole
parse_quadrupole
518
553
518
518
50f3394b3c038fcde1e99706f46166c4bec7a458
bigcode/the-stack
train
c65870858657568bd1d890b5
train
function
def rotationally_symmetric_to_3d_v(ele): """ rotationally_symmetric_to_3d Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s']] return v
def rotationally_symmetric_to_3d_v(ele):
""" rotationally_symmetric_to_3d Impact-T style V list """ # Let v[0] be the original ele, so the indexing looks the same. dummy = 0.0 v = [ele, dummy, dummy, ele['s']] return v
electron emission. If there are multiple such lines in the input file, only the last line matters. """ v = v_from_line(line) d={} d['s'] = float(v[3]) return d def rotationally_symmetric_to_3d_v(ele):
63
64
77
12
50
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
rotationally_symmetric_to_3d_v
rotationally_symmetric_to_3d_v
1,108
1,116
1,108
1,108
ecf02ef53dba7aff497f93c1b15eea60b3ab84d4
bigcode/the-stack
train
c250e057c742f0099a3666e5
train
function
def parse_lattice(lines): eles = [parse_ele(line) for line in lines] add_s_position(eles) create_names(eles) return eles
def parse_lattice(lines):
eles = [parse_ele(line) for line in lines] add_s_position(eles) create_names(eles) return eles
['name'] = e['type']+'_'+str(counter[t]) # Try from description if 'description' in e: alias_name = tools.find_property(e['description'], 'name') if alias_name: e['name'] = alias_name def parse_lattice(lines):
63
64
36
6
56
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
parse_lattice
parse_lattice
1,497
1,501
1,497
1,497
ec00f965b8ee69dee89883404bd80fb3d4361237
bigcode/the-stack
train
57039482e1c95fb663bc07a7
train
function
def fort_type(filePath, verbose=False): """ Extract the integer type of a fort.X file, where X is the type. """ fullpath = os.path.abspath(filePath) p, f = os.path.split(fullpath) s = f.split('.') if s[0] != 'fort': print('Error: not a fort file:', filePath) else: file_ty...
def fort_type(filePath, verbose=False):
""" Extract the integer type of a fort.X file, where X is the type. """ fullpath = os.path.abspath(filePath) p, f = os.path.split(fullpath) s = f.split('.') if s[0] != 'fort': print('Error: not a fort file:', filePath) else: file_type = int(s[1]) if file_type ...
, 28, 29, 30, 34, 35, 36, 37, 38, 60]: for j, k in enumerate(FORT_KEYS[i]): UNITS[k] = FORT_UNITS[i][j] def fort_type(filePath, verbose=False):
63
64
152
9
54
jacquelinegarrahan/lume-impact
impact/parsers.py
Python
fort_type
fort_type
1,895
1,910
1,895
1,895
bd996ed791231fe434d2a482aae0b84f1caa2767
bigcode/the-stack
train
f4d1986531529014889c3468
train
function
def main(*argv): if not argv: argv = list(sys.argv) # attach SIGPIPE handler to properly handle broken pipe import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) # arguments to gpustat import argparse parser = argparse.ArgumentParser() parser_color = parser.add_mutually_...
def main(*argv):
if not argv: argv = list(sys.argv) # attach SIGPIPE handler to properly handle broken pipe import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) # arguments to gpustat import argparse parser = argparse.ArgumentParser() parser_color = parser.add_mutually_exclusive_group()...
except Exception: # NVMLError can't be processed by traceback: # https://bugs.python.org/issue28603 # as a workaround, simply re-throw the exception raise e sys.exit(1) if json: gpu_stats.print_json(sys.stdout) else: gpu...
213
213
712
5
207
seilna/gpustat
gpustat/cli.py
Python
main
main
98
176
98
98
307f22b5360905d9edb416e090115008018d6b14
bigcode/the-stack
train
535c2afab7f8f837f8908cb7
train
function
def loop_gpustat(interval=1.0, **kwargs): term = Terminal() with term.fullscreen(): while 1: try: query_start = time.time() with term.location(0, 0): print_gpustat(eol_char=term.clear_eol + '\n', **kwargs) print(term.cl...
def loop_gpustat(interval=1.0, **kwargs):
term = Terminal() with term.fullscreen(): while 1: try: query_start = time.time() with term.location(0, 0): print_gpustat(eol_char=term.clear_eol + '\n', **kwargs) print(term.clear_eos, end='') query_dur...
re-throw the exception raise e sys.exit(1) if json: gpu_stats.print_json(sys.stdout) else: gpu_stats.print_formatted(sys.stdout, **kwargs) update_history(gpu_stats) def loop_gpustat(interval=1.0, **kwargs):
64
64
124
14
50
seilna/gpustat
gpustat/cli.py
Python
loop_gpustat
loop_gpustat
80
95
80
80
5d9dc6093be1b9b0d209d5edd3af88f88584bd73
bigcode/the-stack
train
3804cbc99ab5cc97aedea5ba
train
function
def update_history(gpu_stats): hostname = gpu_stats.hostname if not os.path.exists('gpu_history.pkl'): pickle.dump({}, open('gpu_history.pkl', 'wb')) with open('gpu_history.pkl', 'rb') as f: history = pickle.load(f) # hostname 추가 hostname = gpu_stats.hostname if ho...
def update_history(gpu_stats):
hostname = gpu_stats.hostname if not os.path.exists('gpu_history.pkl'): pickle.dump({}, open('gpu_history.pkl', 'wb')) with open('gpu_history.pkl', 'rb') as f: history = pickle.load(f) # hostname 추가 hostname = gpu_stats.hostname if hostname not in history: ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import time import pickle import os import datetime from blessings import Terminal from gpustat import __version__ from .core import GPUStatCollection def update_history(gpu_stats):
66
91
304
7
58
seilna/gpustat
gpustat/cli.py
Python
update_history
update_history
15
50
15
15
778b7eebb186cfc2ce72da802a3926419057fc7c
bigcode/the-stack
train
678e4df665f04a63a2972f10
train
function
def print_gpustat(json=False, debug=False, **kwargs): ''' Display the GPU query results into standard output. ''' try: gpu_stats = GPUStatCollection.new_query() except Exception as e: sys.stderr.write('Error on querying NVIDIA devices.' ' Use --debug flag for...
def print_gpustat(json=False, debug=False, **kwargs):
''' Display the GPU query results into standard output. ''' try: gpu_stats = GPUStatCollection.new_query() except Exception as e: sys.stderr.write('Error on querying NVIDIA devices.' ' Use --debug flag for details\n') if debug: try: ...
than 3 days cleaned_users.append(username) for username in cleaned_users: history[hostname][gpu_id].pop(username) with open('gpu_history.pkl', 'wb') as f: pickle.dump(history, f) def print_gpustat(json=False, debug=False, **kwargs):
64
64
172
14
50
seilna/gpustat
gpustat/cli.py
Python
print_gpustat
print_gpustat
52
77
52
52
cf4e0cfd6c19bba4b5acd88bffb05e26f31e9e11
bigcode/the-stack
train
aebf0e173173b5f8d20255c0
train
class
class GymEnv(Env): # low dimensional observations def __init__(self, args, env_ind=0): super(GymEnv, self).__init__(args, env_ind) assert self.env_type == "gym" try: import gym except ImportError as e: self.logger.warning("WARNING: gym not found") self.env = gym.make(self....
class GymEnv(Env): # low dimensional observations
def __init__(self, args, env_ind=0): super(GymEnv, self).__init__(args, env_ind) assert self.env_type == "gym" try: import gym except ImportError as e: self.logger.warning("WARNING: gym not found") self.env = gym.make(self.game) self.env.seed(self.seed) # NOTE: s...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from copy import deepcopy from gym.spaces.box import Box import inspect from utils.helpers import Experience # NOTE: here state0 is always "None" from utils.helpers import preproce...
97
144
481
12
84
R3NI3/pytorch-rl
core/envs/gym.py
Python
GymEnv
GymEnv
13
73
13
13
53d200fc2ead3410510dea2287f3cfcbd49936df
bigcode/the-stack
train
de3dafc3bb1880d4ff103b0c
train
function
@jit(nopython=True) def model_TestModel_Monod_Constitutive_Double(y, t, params): x = y[0] s = y[1] mh = y[2] h = y[3] mu_max = params[0] Ks = params[1] Y = params[2] synm = params[3] degm = params[4] synh = params[5] mu = mu_max*s/(s+Ks) dx = x*mu ds = -dx/Y dmh= synm -mh*degm dh...
@jit(nopython=True) def model_TestModel_Monod_Constitutive_Double(y, t, params):
x = y[0] s = y[1] mh = y[2] h = y[3] mu_max = params[0] Ks = params[1] Y = params[2] synm = params[3] degm = params[4] synh = params[5] mu = mu_max*s/(s+Ks) dx = x*mu ds = -dx/Y dmh= synm -mh*degm dh = synh*mh -h *mu return np.array([dx, ds, dmh, dh])
import numpy as np from numpy import log as ln from numpy import log10 as log from numpy import exp from numba import jit @jit(nopython=True) def model_TestModel_Monod_Constitutive_Double(y, t, params):
58
64
165
26
31
EngBioNUS/BMSS2
examples/tutorial_5_model_selection/TestModel_Monod_Constitutive_Double.py
Python
model_TestModel_Monod_Constitutive_Double
model_TestModel_Monod_Constitutive_Double
7
28
7
8
621dd7fe9234b8ee9a1b5efb9e23ee17f030ecdb
bigcode/the-stack
train
84397163d536f25d56d191ec
train
class
class DockerStepHandler(StepHandler): def __init__( self, image=None, registry=None, env_vars=None, network=None, networks=None, container_kwargs=None, ): super().__init__() self._image = image self._registry = registry sel...
class DockerStepHandler(StepHandler):
def __init__( self, image=None, registry=None, env_vars=None, network=None, networks=None, container_kwargs=None, ): super().__init__() self._image = image self._registry = registry self._env_vars = env_vars if net...
containers created by the run launcher will also be set on the containers that are created for each step. """ from . import DockerRunLauncher image = init_context.executor_config.get("image") registry = init_context.executor_config.get("registry") env_vars = init_context.executor_config.get("e...
256
256
1,416
8
248
abkfenris/dagster
python_modules/libraries/dagster-docker/dagster_docker/docker_executor.py
Python
DockerStepHandler
DockerStepHandler
89
305
89
89
f0eec31ba7f2c1d29d7476b196dd879888869b37
bigcode/the-stack
train
0e917ad3253e261fb86d3470
train
function
@executor( name="docker", config_schema=merge_dicts( DOCKER_CONFIG_SCHEMA, { "retries": get_retries_config(), }, ), requirements=multiple_process_executor_requirements(), ) @experimental def docker_executor(init_context: InitExecutorContext) -> Executor: """ E...
@executor( name="docker", config_schema=merge_dicts( DOCKER_CONFIG_SCHEMA, { "retries": get_retries_config(), }, ), requirements=multiple_process_executor_requirements(), ) @experimental def docker_executor(init_context: InitExecutorContext) -> Executor:
""" Executor which launches steps as Docker containers. To use the `docker_executor`, set it as the `executor_def` when defining a job: .. literalinclude:: ../../../../../../python_modules/libraries/dagster-docker/dagster_docker_tests/test_example_executor.py :start-after: start_marker :...
.core.executor.init import InitExecutorContext from dagster.core.executor.step_delegating import StepDelegatingExecutor from dagster.core.executor.step_delegating.step_handler.base import StepHandler, StepHandlerContext from dagster.serdes.utils import hash_str from dagster.utils import merge_dicts from dagster.utils.b...
135
135
450
64
70
abkfenris/dagster
python_modules/libraries/dagster-docker/dagster_docker/docker_executor.py
Python
docker_executor
docker_executor
21
86
21
32
14f38eced5e01549483258f16d12f21256949c53
bigcode/the-stack
train
7fc02817d1947f0951b8bee7
train
function
@patch_to(GroupedEstimator) def transform(self, X, y=None): return self.predict(X)
@patch_to(GroupedEstimator) def transform(self, X, y=None):
return self.predict(X)
ColumnSelector = ColumnSelector # Cell from fastcore.basics import patch_to from sklego.meta import GroupedEstimator, GroupedPredictor, GroupedTransformer, EstimatorTransformer GroupedEstimator = GroupedEstimator @patch_to(GroupedEstimator) def transform(self, X, y=None):
64
64
22
16
47
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
transform
transform
31
33
31
32
0ab7b3de5f1932d3fd15e68651029653d730cecc
bigcode/the-stack
train
37e05b308eb660299bed2550
train
function
def train_test_split(*args, **kwargs): outputs = tts(*args, **kwargs) outputs = [i.reset_index(drop=True) for i in outputs] return outputs
def train_test_split(*args, **kwargs):
outputs = tts(*args, **kwargs) outputs = [i.reset_index(drop=True) for i in outputs] return outputs
Column'] # Cell from torch_snippets import * try: from sklearn.model_selection import train_test_split as tts except ModuleNotFoundError: logger.Exception('Please `pip install scikit-learn sklego` to use this submodule') def train_test_split(*args, **kwargs):
64
64
40
10
54
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
train_test_split
train_test_split
16
19
16
16
dd3bdd2a721e105ad71c6d2e92ad42a5fea5026a
bigcode/the-stack
train
82d66c097c8dac59b6d50725
train
class
class ImputeMissingValues(BaseEstimator, TransformerMixin): '''DataFrame input - DataFrame output During fit - 1. Store imputable value for each column During transform - 2. Impute missing values with imputable value 3. Create a '{col}_na' boolean column to tell if cells contained missing value ...
class ImputeMissingValues(BaseEstimator, TransformerMixin):
'''DataFrame input - DataFrame output During fit - 1. Store imputable value for each column During transform - 2. Impute missing values with imputable value 3. Create a '{col}_na' boolean column to tell if cells contained missing value ''' def __init__(self, num_mode=np.mean, cat_mode='M...
self.predict(X) EstimatorTransformer = EstimatorTransformer # Cell class MakeFrame(BaseEstimator, TransformerMixin): '''Convert sklearn's output to a pandas dataframe Especially useful when working with an ensemble of models ''' def __init__(self, column_names): self.column_names = column_nam...
115
115
386
11
103
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
ImputeMissingValues
ImputeMissingValues
57
97
57
57
29fa420a37d99003a118bcdfe00779dfcb90f41a
bigcode/the-stack
train
ed186dfce0bff1c00fb31be9
train
class
class SplitDateColumn(BaseEstimator, TransformerMixin): def __init__(self, column_names, has_date, has_time, date_format=None): self.column_names = column_names if isinstance(column_names, list) else [column_names] self.has_date = has_date self.has_time = has_time def fit(self, X, y=Non...
class SplitDateColumn(BaseEstimator, TransformerMixin):
def __init__(self, column_names, has_date, has_time, date_format=None): self.column_names = column_names if isinstance(column_names, list) else [column_names] self.has_date = has_date self.has_time = has_time def fit(self, X, y=None): return X def transform(self, X, y=None)...
transform(self, df, y=None): for col in self.cat_cols: df.loc[:, col] = df[col].map(lambda x: self.ids[col][x]) return df def fit_transform(self, trn_df, y=None): return self.transform(self.fit(trn_df, y)) # Cell class SplitDateColumn(BaseEstimator, TransformerMixin):
78
78
260
10
67
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
SplitDateColumn
SplitDateColumn
159
187
159
159
478877678178346ad2f3ebf135e6d260e35b9c3d
bigcode/the-stack
train
22c95f94ee2a6031eccd4b57
train
class
class MakeFrame(BaseEstimator, TransformerMixin): def __init__(self, column_names): self.column_names = column_names def fit(self, X, y=None): return X def transform(self, X, y=None): return pd.DataFrame(X, columns=self.column_names) def predict_proba(self, X, y=None): ...
class MakeFrame(BaseEstimator, TransformerMixin):
def __init__(self, column_names): self.column_names = column_names def fit(self, X, y=None): return X def transform(self, X, y=None): return pd.DataFrame(X, columns=self.column_names) def predict_proba(self, X, y=None): return self.transform(X) def predict(self, X...
def predict_proba(self, X, y=None): return self.fn(X) def transform(self, X, y=None): return self.fn(X) def fit_transform(self, X, y=None): return self.fit(self.transform(X)) # Cell class MakeFrame(BaseEstimator, TransformerMixin):
64
64
97
9
54
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
MakeFrame
MakeFrame
120
134
120
120
3182b78e8547881851932712bbee8c0174e76813
bigcode/the-stack
train
08a7e55344474ee311fc9d77
train
class
class Cat2Num(BaseEstimator, TransformerMixin): def __init__(self): ... def fit(self, df, y=None): self.cat_cols = df.select_dtypes('object').columns self.ids = {} for col in self.cat_cols: _d = defaultdict(lambda : 0) # 0 is reserved for the unknown _d.update({i...
class Cat2Num(BaseEstimator, TransformerMixin):
def __init__(self): ... def fit(self, df, y=None): self.cat_cols = df.select_dtypes('object').columns self.ids = {} for col in self.cat_cols: _d = defaultdict(lambda : 0) # 0 is reserved for the unknown _d.update({id:ix+1 for ix,id in enumerate(df[col].unique())}...
return pd.DataFrame(X, columns=self.column_names) def predict_proba(self, X, y=None): return self.transform(X) def predict(self, X, y=None): return self.transform(X) # Cell from collections import defaultdict class Cat2Num(BaseEstimator, TransformerMixin):
64
64
175
10
53
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
Cat2Num
Cat2Num
138
156
138
138
3eb0fc03edb906b1fd738741789b4decd1e777f5
bigcode/the-stack
train
ff47150b18a753b905c8b202
train
class
class MakeFrame(BaseEstimator, TransformerMixin): '''Convert sklearn's output to a pandas dataframe Especially useful when working with an ensemble of models ''' def __init__(self, column_names): self.column_names = column_names def fit(self, X, y=None): return X def transform(...
class MakeFrame(BaseEstimator, TransformerMixin):
'''Convert sklearn's output to a pandas dataframe Especially useful when working with an ensemble of models ''' def __init__(self, column_names): self.column_names = column_names def fit(self, X, y=None): return X def transform(self, X, y=None): return pd.DataFrame(X, c...
(self, X, y=None): return self.predict(X) GroupedPredictor = GroupedPredictor @patch_to(GroupedPredictor) def transform(self, X, y=None): return self.predict(X) EstimatorTransformer = EstimatorTransformer # Cell class MakeFrame(BaseEstimator, TransformerMixin):
64
64
87
9
54
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
MakeFrame
MakeFrame
43
54
43
43
927d1fb2ad6e3042fc02363d9a1dead7472522d8
bigcode/the-stack
train
4ccc1d0d43e1440fa89aa06e
train
class
class LambdaTransformer(BaseEstimator, TransformerMixin): def __init__(self, fn): self.fn = fn def fit(self, X, y=None): return X def predict(self, X, y=None): return self.fn(X) def predict_proba(self, X, y=None): return self.fn(X) def transform(self, X, y=None): ...
class LambdaTransformer(BaseEstimator, TransformerMixin):
def __init__(self, fn): self.fn = fn def fit(self, X, y=None): return X def predict(self, X, y=None): return self.fn(X) def predict_proba(self, X, y=None): return self.fn(X) def transform(self, X, y=None): return self.fn(X) def fit_transform(self, X, ...
self.imputable_values[col]]*len(jxs) X[f'{col}_na'] = ixs return X def fit_transform(self, trn_df, y=None): return self.transform(self.fit(trn_df, y)) # Cell class LambdaTransformer(BaseEstimator, TransformerMixin):
64
64
107
9
54
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
LambdaTransformer
LambdaTransformer
100
117
100
100
a43d4a0062fe723e51c79c93e5f242b56e779a6e
bigcode/the-stack
train
cbbb96cfcc6230c6209f9829
train
function
@patch_to(GroupedPredictor) def transform(self, X, y=None): return self.predict(X)
@patch_to(GroupedPredictor) def transform(self, X, y=None):
return self.predict(X)
, GroupedTransformer, EstimatorTransformer GroupedEstimator = GroupedEstimator @patch_to(GroupedEstimator) def transform(self, X, y=None): return self.predict(X) GroupedPredictor = GroupedPredictor @patch_to(GroupedPredictor) def transform(self, X, y=None):
64
64
23
17
46
omrylcn/torch_snippets
torch_snippets/sklegos.py
Python
transform
transform
36
38
36
37
8fc4098c5db4af8f5831f8a4d26fa8435b0ad021
bigcode/the-stack
train
f163f963a793ad28e9857237
train
function
def select_file(): filetypes = (('Audio Files', ['*.egg','*.ogg']),('All files', '*.*')) filename = fd.askopenfilename(title='Open a file',initialdir='/') showinfo(title='Selected File', message=filename)
def select_file():
filetypes = (('Audio Files', ['*.egg','*.ogg']),('All files', '*.*')) filename = fd.askopenfilename(title='Open a file',initialdir='/') showinfo(title='Selected File', message=filename)
tkinter as tk from tkinter import ttk from tkinter import filedialog as fd from tkinter.messagebox import showinfo # create the root window root = tk.Tk() root.title('Tkinter Open File Dialog') root.resizable(False, False) root.geometry('300x150') def select_file():
64
64
56
4
60
Codingmace/BeatSaber-AI
QT Test/Tkinter test/Tkinter test/selectFile.py
Python
select_file
select_file
13
16
13
13
31bd00909b9f27fee6a8abce353cdca03d129535
bigcode/the-stack
train
dccb93b433062977b4b1a5b9
train
class
class TestDatetime64(tm.TestCase): """ Also test support for datetime64[ns] in Series / DataFrame """ def setUp(self): dti = DatetimeIndex(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='Min') self.series = Series(rand(len(dti)), dti) def te...
class TestDatetime64(tm.TestCase):
""" Also test support for datetime64[ns] in Series / DataFrame """ def setUp(self): dti = DatetimeIndex(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq='Min') self.series = Series(rand(len(dti)), dti) def test_datetimeindex_accessors(self): ...
Timestamp('2015-02-01'):Timestamp('2014-10-01'):-1], SLC[13:8:-1]) assert_slices_equivalent(SLC['2015-02-01':Timestamp('2014-10-01'):-1], SLC[13:8:-1]) assert_slices_equivalent(SLC[Timestamp('2015-02-01'):'2014-10-01':-1], SLC[13:8:-1]) assert_slices_equivalent(SLC['2014-10-01':'2015-02-01':-1]...
255
256
4,707
8
247
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestDatetime64
TestDatetime64
3,134
3,502
3,134
3,134
2d0dc93f2983639a09cecd9e4cec44a61d4c52d7
bigcode/the-stack
train
a3ff881dcb6c9f6097a5cb22
train
class
class TestTimestampToJulianDate(tm.TestCase): def test_compare_1700(self): r = Timestamp('1700-06-23').to_julian_date() self.assertEqual(r, 2342145.5) def test_compare_2000(self): r = Timestamp('2000-04-12').to_julian_date() self.assertEqual(r, 2451646.5) def test_compare_...
class TestTimestampToJulianDate(tm.TestCase):
def test_compare_1700(self): r = Timestamp('1700-06-23').to_julian_date() self.assertEqual(r, 2342145.5) def test_compare_2000(self): r = Timestamp('2000-04-12').to_julian_date() self.assertEqual(r, 2451646.5) def test_compare_2100(self): r = Timestamp('2100-08-12')...
_array(test_array), expected_format ) format_for_string_of_nans = tools._guess_datetime_format_for_array( np.array([np.nan, np.nan, np.nan], dtype='O') ) self.assertTrue(format_for_string_of_nans is None) class TestTimestampToJulianDate(tm.TestCase):
69
69
231
11
58
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestTimestampToJulianDate
TestTimestampToJulianDate
4,720
4,740
4,720
4,721
b312e00bb6cb0fa89a72d5d1faa617cf146bd144
bigcode/the-stack
train
06b0c9266c0a84e0caa0cfbc
train
class
class TestSeriesDatetime64(tm.TestCase): def setUp(self): self.series = Series(date_range('1/1/2000', periods=10)) def test_auto_conversion(self): series = Series(list(date_range('1/1/2000', periods=10))) self.assertEqual(series.dtype, 'M8[ns]') def test_constructor_cant_cast_date...
class TestSeriesDatetime64(tm.TestCase):
def setUp(self): self.series = Series(date_range('1/1/2000', periods=10)) def test_auto_conversion(self): series = Series(list(date_range('1/1/2000', periods=10))) self.assertEqual(series.dtype, 'M8[ns]') def test_constructor_cant_cast_datetime64(self): self.assertRaises(Ty...
1,1,1,11):] expected = df.iloc[1:] assert_frame_equal(result,expected) result = df.ix['20010101 11':] assert_frame_equal(result,expected) # duplicates df = pd.DataFrame(np.arange(5.,dtype='float64'), index=[datetime(2001, 1, i, 10, 00) for i in ...
256
256
2,254
9
247
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestSeriesDatetime64
TestSeriesDatetime64
3,504
3,685
3,504
3,505
f91ad5cf435518b75c6264189ef10db0229a792d
bigcode/the-stack
train
164d3155e21fb0bb20eebd47
train
class
class TestGuessDatetimeFormat(tm.TestCase): def test_guess_datetime_format_with_parseable_formats(self): dt_string_to_format = ( ('20111230', '%Y%m%d'), ('2011-12-30', '%Y-%m-%d'), ('30-12-2011', '%d-%m-%Y'), ('2011-12-30 00:00:00', '%Y-%m-%d %H:%M:%S'), ...
class TestGuessDatetimeFormat(tm.TestCase):
def test_guess_datetime_format_with_parseable_formats(self): dt_string_to_format = ( ('20111230', '%Y%m%d'), ('2011-12-30', '%Y-%m-%d'), ('30-12-2011', '%d-%m-%Y'), ('2011-12-30 00:00:00', '%Y-%m-%d %H:%M:%S'), ('2011-12-30T00:00:00', '%Y-%m-%dT%H:...
_numpy_array_equal( pd.to_datetime(test_series, infer_datetime_format=False), pd.to_datetime(test_series, infer_datetime_format=True) ) def test_to_datetime_infer_datetime_format_series_with_nans(self): test_series = pd.Series( np.array([ '01/01/2...
256
256
956
9
247
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestGuessDatetimeFormat
TestGuessDatetimeFormat
4,617
4,717
4,617
4,617
450523cd58eabefa471ef0cc2250ce77fb41c601
bigcode/the-stack
train
e1ee5ee9ac1912d3c7a30d17
train
class
class TestSlicing(tm.TestCase): def test_slice_year(self): dti = DatetimeIndex(freq='B', start=datetime(2005, 1, 1), periods=500) s = Series(np.arange(len(dti)), index=dti) result = s['2005'] expected = s[s.index.year == 2005] assert_series_equal(result, expected) ...
class TestSlicing(tm.TestCase):
def test_slice_year(self): dti = DatetimeIndex(freq='B', start=datetime(2005, 1, 1), periods=500) s = Series(np.arange(len(dti)), index=dti) result = s['2005'] expected = s[s.index.year == 2005] assert_series_equal(result, expected) df = DataFrame(np.random.rand(len...
s[0] = pd.Timestamp('nat') s[3] = pd.Timestamp('nat') ops = {'lt': 'gt', 'le': 'ge', 'eq': 'eq', 'ne': 'ne'} for left, right in ops.items(): left_f = getattr(operator, left) right_f = getattr(operator, right) # no nats expected = left_f(s, Time...
256
256
3,577
8
248
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestSlicing
TestSlicing
4,059
4,398
4,059
4,060
840766b8501916d68188bedc25f5316b4ef2b8c1
bigcode/the-stack
train
971a466be6843cc3c3449a3a
train
class
class TestDaysInMonth(tm.TestCase): def test_coerce_deprecation(self): # deprecation of coerce with tm.assert_produces_warning(FutureWarning): to_datetime('2015-02-29', coerce=True) with tm.assert_produces_warning(FutureWarning): self.assertRaises(ValueError, lambda...
class TestDaysInMonth(tm.TestCase):
def test_coerce_deprecation(self): # deprecation of coerce with tm.assert_produces_warning(FutureWarning): to_datetime('2015-02-29', coerce=True) with tm.assert_produces_warning(FutureWarning): self.assertRaises(ValueError, lambda : to_datetime('2015-02-29', coerce=F...
ian_date() self.assertIsInstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_second(self): r1 = Float64Index([2451601.5, 2451601.500011574074074, 2451601.5000231481481481, 2451601.5000347222222222,...
162
162
540
9
153
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestDaysInMonth
TestDaysInMonth
4,804
4,836
4,804
4,805
0365bcedc5ad6e0960493eb4ef6f363d221c22c4
bigcode/the-stack
train
850b998ab21c3f26c3fb7485
train
class
class TestTimeSeriesDuplicates(tm.TestCase): _multiprocess_can_split_ = True def setUp(self): dates = [datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1,...
class TestTimeSeriesDuplicates(tm.TestCase):
_multiprocess_can_split_ = True def setUp(self): dates = [datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 4), datetime(2000, 1, 4), d...
etimeIndex, Int64Index, to_datetime, bdate_range, Float64Index, TimedeltaIndex, NaT) import pandas.core.datetools as datetools import pandas.tseries.offsets as offsets import pandas.tseries.tools as tools import pandas.tseries.frequencies as frequencies import pandas as pd from pandas.util.testing...
256
256
2,381
9
247
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestTimeSeriesDuplicates
TestTimeSeriesDuplicates
50
294
50
50
df8a93bceb3066f315ff55ccb4d6719a1dc80251
bigcode/the-stack
train
02989ddb8fded8ab5ae0b036
train
class
class TestDatetimeIndex(tm.TestCase): _multiprocess_can_split_ = True def test_hash_error(self): index = date_range('20010101', periods=10) with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % type(index).__name__): ...
class TestDatetimeIndex(tm.TestCase):
_multiprocess_can_split_ = True def test_hash_error(self): index = date_range('20010101', periods=10) with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % type(index).__name__): hash(index) def test_...
freq idx = date_range('1750-1-1', '2050-1-1', freq='7D') idx_p = self.round_trip_pickle(idx) tm.assert_index_equal(idx, idx_p) def test_timestamp_equality(self): # GH 11034 s = Series([Timestamp('2000-01-29 01:59:00'),'NaT']) result = s != s assert_series_e...
256
256
10,987
8
248
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestDatetimeIndex
TestDatetimeIndex
2,198
3,130
2,198
2,198
08b3794ed6d87756a6dab3cb86d3e275fddf436a
bigcode/the-stack
train
27ec403a44746af4513bbe12
train
class
class TestTimestamp(tm.TestCase): def test_class_ops_pytz(self): tm._skip_if_no_pytz() from pytz import timezone def compare(x, y): self.assertEqual(int(Timestamp(x).value / 1e9), int(Timestamp(y).value / 1e9)) compare(Timestamp.now(), datetime.now()) compare(T...
class TestTimestamp(tm.TestCase):
def test_class_ops_pytz(self): tm._skip_if_no_pytz() from pytz import timezone def compare(x, y): self.assertEqual(int(Timestamp(x).value / 1e9), int(Timestamp(y).value / 1e9)) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(t...
07 16:00', '2014-07-08 09:00', '2014-07-08 10:00', '2014-07-08 11:00', '2014-07-08 12:00', '2014-07-08 13:00', '2014-07-08 14:00', '2014-07-08 15:00', '2014-07-08 16:00'], freq='BH') rng = date_range('2014-07-04 09:00', '2014...
256
256
3,423
7
249
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestTimestamp
TestTimestamp
3,688
4,056
3,688
3,689
24b9711e8cc25a0cdc5fa45b8c0532aba7c53822
bigcode/the-stack
train
43c9014f96876120d9917849
train
function
def assert_range_equal(left, right): assert(left.equals(right)) assert(left.freq == right.freq) assert(left.tz == right.tz)
def assert_range_equal(left, right):
assert(left.equals(right)) assert(left.freq == right.freq) assert(left.tz == right.tz)
org = DatetimeIndex(start='2001/02/01 09:00', freq=f, tz='US/Pacific', periods=1) idx = DatetimeIndex(org, freq=f, tz='US/Pacific') self.assertTrue(idx.equals(org)) def assert_range_equal(left, right):
64
64
32
8
56
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
assert_range_equal
assert_range_equal
297
300
297
297
b7e74fb54c5327c624b1ce8fae4fd06844e3d04b
bigcode/the-stack
train
31855833c2866ba729feb7c5
train
function
def _simple_ts(start, end, freq='D'): rng = date_range(start, end, freq=freq) return Series(np.random.randn(len(rng)), index=rng)
def _simple_ts(start, end, freq='D'):
rng = date_range(start, end, freq=freq) return Series(np.random.randn(len(rng)), index=rng)
_equal(result, Series([True,False])) result = s == s[0] assert_series_equal(result, Series([True,False])) result = s == s[1] assert_series_equal(result, Series([False,False])) def _simple_ts(start, end, freq='D'):
63
64
39
12
51
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
_simple_ts
_simple_ts
2,193
2,195
2,193
2,193
81bbef9308fdad80fd69708567e7eaf3781f84e7
bigcode/the-stack
train
2fb5716908d456595664dedb
train
function
def _skip_if_has_locale(): import locale lang, _ = locale.getlocale() if lang is not None: raise nose.SkipTest("Specific locale is set {0}".format(lang))
def _skip_if_has_locale():
import locale lang, _ = locale.getlocale() if lang is not None: raise nose.SkipTest("Specific locale is set {0}".format(lang))
.random import rand from pandas.util.testing import assert_frame_equal from pandas.io.common import PerformanceWarning import pandas.compat as compat import pandas.core.common as com from pandas import concat from pandas import _np_version_under1p8 from numpy.testing.decorators import slow def _skip_if_has_locale():
64
64
43
7
56
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
_skip_if_has_locale
_skip_if_has_locale
43
47
43
43
591d16762219e8496b0781b6d058349d9138fdcb
bigcode/the-stack
train
8904da92e23151ddbbf49c1a
train
class
class TestToDatetimeInferFormat(tm.TestCase): def test_to_datetime_infer_datetime_format_consistent_format(self): time_series = pd.Series( pd.date_range('20000101', periods=50, freq='H') ) test_formats = [ '%m-%d-%Y', '%m/%d/%Y %H:%M:%S.%f', '...
class TestToDatetimeInferFormat(tm.TestCase):
def test_to_datetime_infer_datetime_format_consistent_format(self): time_series = pd.Series( pd.date_range('20000101', periods=50, freq='H') ) test_formats = [ '%m-%d-%Y', '%m/%d/%Y %H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S.%f', ] for ...
00:00.000001", "2012-01-01 09:00:00.001", "2012-01-01 09:00:00.001000", "2012-01-01 09:00:00.001000000", ]: expected = pd.to_datetime(v) result = pd.to_datetime(v, format="%Y-%m-%d %H:%M:%S.%f") self.assertEqual...
198
198
663
10
188
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestToDatetimeInferFormat
TestToDatetimeInferFormat
4,530
4,614
4,530
4,530
987c7d31f1781fa04b4425b45ba2e4086f2ff58c
bigcode/the-stack
train
90520f913c961c1227ad0c86
train
class
class TimeConversionFormats(tm.TestCase): def test_to_datetime_format(self): values = ['1/1/2000', '1/2/2000', '1/3/2000'] results1 = [ Timestamp('20000101'), Timestamp('20000201'), Timestamp('20000301') ] results2 = [ Timestamp('20000101'), Timestamp('20000102'), ...
class TimeConversionFormats(tm.TestCase):
def test_to_datetime_format(self): values = ['1/1/2000', '1/2/2000', '1/3/2000'] results1 = [ Timestamp('20000101'), Timestamp('20000201'), Timestamp('20000301') ] results2 = [ Timestamp('20000101'), Timestamp('20000102'), Timestamp('20000103') ] ...
, weekday=3, variation="nearest")) self.assertEqual(dr[0], Timestamp('2013-01-31')) self.assertEqual(dr[1], Timestamp('2014-01-30')) def test_partial_slice_doesnt_require_monotonicity(self): # For ...
255
256
1,510
8
248
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TimeConversionFormats
TimeConversionFormats
4,401
4,528
4,401
4,401
d4939c36533ee789eb4c808a24e698f65aaacfbc
bigcode/the-stack
train
37a48725050145b9fa43c9e6
train
class
class TestTimeSeries(tm.TestCase): _multiprocess_can_split_ = True def test_is_(self): dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') self.assertTrue(dti.is_(dti)) self.assertTrue(dti.is_(dti.view())) self.assertFalse(dti.is_(dti.copy())) def test_dti_slic...
class TestTimeSeries(tm.TestCase):
_multiprocess_can_split_ = True def test_is_(self): dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') self.assertTrue(dti.is_(dti)) self.assertTrue(dti.is_(dti.view())) self.assertFalse(dti.is_(dti.copy())) def test_dti_slicing(self): dti = DatetimeIn...
result = df['2012-01-02 18:01:02'] assert_frame_equal(result,expected) # this is a single date, so will raise self.assertRaises(KeyError, df.__getitem__, df.index[2],) def test_recreate_from_data(self): freqs = ['M', 'Q', 'A', 'D', 'B', 'BH', 'T', 'S', 'L', 'U', 'H', 'N', '...
256
256
18,271
8
248
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestTimeSeries
TestTimeSeries
303
2,189
303
303
7efd10667db14b0c5ad245f9066b398ff77d2089
bigcode/the-stack
train
cb32e3a74d9b0fcb3ac93366
train
class
class TestDateTimeIndexToJulianDate(tm.TestCase): def test_1700(self): r1 = Float64Index([2345897.5, 2345898.5, 2345899.5, 2345900.5, 2345901.5]) r2 = date_range(start=Timestamp('1710-10-01'),...
class TestDateTimeIndexToJulianDate(tm.TestCase):
def test_1700(self): r1 = Float64Index([2345897.5, 2345898.5, 2345899.5, 2345900.5, 2345901.5]) r2 = date_range(start=Timestamp('1710-10-01'), periods=5, ...
r = Timestamp('2000-04-12').to_julian_date() self.assertEqual(r, 2451646.5) def test_compare_2100(self): r = Timestamp('2100-08-12').to_julian_date() self.assertEqual(r, 2488292.5) def test_compare_hour01(self): r = Timestamp('2000-08-12T01:00:00').to_julian_date() sel...
183
183
612
13
170
ihuston/pandas
pandas/tseries/tests/test_timeseries.py
Python
TestDateTimeIndexToJulianDate
TestDateTimeIndexToJulianDate
4,743
4,802
4,743
4,743
0e14a00d452fa5618118e250e113d154e50d70c1
bigcode/the-stack
train
a963e5522915157896027450
train
function
def SearchAngleUnit(src,flist): for fcurr in flist: fread = open(src+'/'+fcurr).read() if 'sUnitAngle' in fread: angUnit = fread.split()[np.where(np.asarray(fread.split())=='sUnitAngle')[0][0]+1] return angUnit
def SearchAngleUnit(src,flist):
for fcurr in flist: fread = open(src+'/'+fcurr).read() if 'sUnitAngle' in fread: angUnit = fread.split()[np.where(np.asarray(fread.split())=='sUnitAngle')[0][0]+1] return angUnit
from __future__ import print_function import os import sys import subprocess as sb import numpy as np import re from IPython.core.debugger import Tracer import vspace_hyak import itertools as it import matplotlib.pyplot as plt def SearchAngleUnit(src,flist):
63
64
69
9
53
decaelus/vplanet
vspace/vspace/vspace.py
Python
SearchAngleUnit
SearchAngleUnit
12
18
12
12
93ea8b0e77ee2f9855055930d7e610fe919741fb
bigcode/the-stack
train
17f3d11f240124bda42cfff9
train
class
class XactionConsumerB: def __init__(self): self.consumer = KafkaConsumer('bank-customer-events-branch-B', bootstrap_servers=['localhost:9092'], # auto_offset_reset='earliest', value_deserializer=lambda m: loads(m.decode('ascii'))) ## These are two python dictiona...
class XactionConsumerB:
def __init__(self): self.consumer = KafkaConsumer('bank-customer-events-branch-B', bootstrap_servers=['localhost:9092'], # auto_offset_reset='earliest', value_deserializer=lambda m: loads(m.decode('ascii'))) ## These are two python dictionarys # Ledger is ...
from sqlalchemy.sql.ddl import CreateTable from kafka import KafkaConsumer, TopicPartition from json import loads from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database from sqlalchemy.orm import sessionmaker from contextlib import contextmanager # import yaml import psycopg...
69
132
441
6
62
keerthiballa/Kafka3-Data
phase3/XactionconsumerB-to-SQL.py
Python
XactionConsumerB
XactionConsumerB
13
53
13
13
f053c29148b635f47d08eb4e1db25c577cdad7e7
bigcode/the-stack
train
bf24723ea2b134d90245f29f
train
class
class ResidualBlock(nn.Module): def __init__(self, in_channels, out_channels, stride=1, downsample=None): super(ResidualBlock, self).__init__() self.conv1 = conv3x3(in_channels, out_channels, stride) self.bn1 = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inplace=True) se...
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, downsample=None): super(ResidualBlock, self).__init__() self.conv1 = conv3x3(in_channels, out_channels, stride) self.bn1 = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(out_channels,...
3x3 Convolution def conv3x3(in_channels, out_channels, stride=1): return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) # Residual Block class ResidualBlock(nn.Module):
64
64
195
7
56
NegatioN/pytorch-tutorial
tutorials/02-intermediate/deep_residual_network/main-gpu.py
Python
ResidualBlock
ResidualBlock
43
64
43
43
64b1c2066871de163771f518216892d88ae7037d
bigcode/the-stack
train
f442cc50219eea461050b51b
train
class
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=10): super(ResNet, self).__init__() self.in_channels = 16 self.conv = conv3x3(3, 16) self.bn = nn.BatchNorm2d(16) self.relu = nn.ReLU(inplace=True) self.layer1 = self.make_layer(block, 16, layers[0...
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=10): super(ResNet, self).__init__() self.in_channels = 16 self.conv = conv3x3(3, 16) self.bn = nn.BatchNorm2d(16) self.relu = nn.ReLU(inplace=True) self.layer1 = self.make_layer(block, 16, layers[0]) self.layer2 = ...
.bn2 = nn.BatchNorm2d(out_channels) self.downsample = downsample def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample: residual...
111
111
372
6
104
NegatioN/pytorch-tutorial
tutorials/02-intermediate/deep_residual_network/main-gpu.py
Python
ResNet
ResNet
67
103
67
67
85392be60827ecae1097a3c5cd305fb5fc890240
bigcode/the-stack
train
2e29feeaa37ad194d6746d77
train
function
def conv3x3(in_channels, out_channels, stride=1): return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
def conv3x3(in_channels, out_channels, stride=1):
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=100, ...
64
64
45
15
48
NegatioN/pytorch-tutorial
tutorials/02-intermediate/deep_residual_network/main-gpu.py
Python
conv3x3
conv3x3
38
40
38
38
4af8b652de69fb512dfb653cc2dda755297d19e1
bigcode/the-stack
train
367fddfd4c8c2f6d4d3a0e9a
train
function
def find_paths(path): """Return the number of paths from start to end.""" cave = path[-1] if cave == 'end': return 1 paths = 0 for neighbor in neighbors[cave]: if neighbor.isupper() or neighbor not in path: paths += find_paths(path + [neighbor]) return paths
def find_paths(path):
"""Return the number of paths from start to end.""" cave = path[-1] if cave == 'end': return 1 paths = 0 for neighbor in neighbors[cave]: if neighbor.isupper() or neighbor not in path: paths += find_paths(path + [neighbor]) return paths
import collections def make_map(connections): """Return the map of caves based on connections.""" neighbors = collections.defaultdict(list) for start, end in connections: neighbors[start].append(end) neighbors[end].append(start) return neighbors def find_paths(path):
59
64
76
5
53
mikkomaa/advent-of-code-2021
src/day12_1.py
Python
find_paths
find_paths
13
23
13
13
ee0bd34f52403a4f50dec97f7ba649b882381bf3
bigcode/the-stack
train
2c5344b7a91ca064dbc1c796
train
function
def make_map(connections): """Return the map of caves based on connections.""" neighbors = collections.defaultdict(list) for start, end in connections: neighbors[start].append(end) neighbors[end].append(start) return neighbors
def make_map(connections):
"""Return the map of caves based on connections.""" neighbors = collections.defaultdict(list) for start, end in connections: neighbors[start].append(end) neighbors[end].append(start) return neighbors
import collections def make_map(connections):
9
64
51
6
2
mikkomaa/advent-of-code-2021
src/day12_1.py
Python
make_map
make_map
4
10
4
4
74e8786f35f4ae38fe9dbf791877ca5fcf1702a9
bigcode/the-stack
train
abb81477cc64f89376dda1e6
train
class
class ClientToolClient(Client): def __init__(self, base_url=None, creds=None): super(ClientToolClient, self).__init__(base_url, creds) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Des...
class ClientToolClient(Client):
def __init__(self, base_url=None, creds=None): super(ClientToolClient, self).__init__(base_url, creds) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) re...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
69
120
403
6
62
doggy8088/azure-devops-cli-extension
azure-devops/azext_devops/dev/common/client_tool/client_tool_client.py
Python
ClientToolClient
ClientToolClient
12
50
12
12
524677373bc772a6dbacb2df06b4dc2e5a71802a
bigcode/the-stack
train
15ba62a155d1fb8df3e349c8
train
function
def unmounted(name, device, config='/etc/fstab', persist=False, user=None): ''' .. versionadded:: 0.17.0 Verify that a device is not mounted name The path to the location where the device is to be unmounted from .. versionadded:: 201...
def unmounted(name, device, config='/etc/fstab', persist=False, user=None):
''' .. versionadded:: 0.17.0 Verify that a device is not mounted name The path to the location where the device is to be unmounted from .. versionadded:: 2015.5.0 device The device to be unmounted. config Set an alternative location for the fstab, Default is ``/e...
device'] == name and \ fstab_data['none']['fstype'] != 'swap': return ret # present, new, change, bad config # Make sure the entry is in the fstab out = __salt__['mount.set_fstab']('none', name, ...
232
232
775
23
208
vamshi98/salt-formulas
salt/states/mount.py
Python
unmounted
unmounted
522
616
522
526
1f71f4e82a0bfcfe83411aa9654ae9a4785408a8
bigcode/the-stack
train
11d569c3cf51e68526143a3e
train
function
def mod_watch(name, user=None, **kwargs): ''' The mounted watcher, called to invoke the watch command. name The name of the mount point ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if kwargs['sfun'] == 'mounted': out =...
def mod_watch(name, user=None, **kwargs):
''' The mounted watcher, called to invoke the watch command. name The name of the mount point ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if kwargs['sfun'] == 'mounted': out = __salt__['mount.remount'](name, kwargs['d...
: ret['result'] = False ret['comment'] += '. Failed to persist purge' else: ret['comment'] += '. Removed target from fstab' ret['changes']['persist'] = 'purged' return ret def mod_watch(name, user=None, **kwargs):
64
64
189
11
52
vamshi98/salt-formulas
salt/states/mount.py
Python
mod_watch
mod_watch
619
641
619
619
a2d8bc03ba16dd69ca5311f0f6687c477b95e7b1
bigcode/the-stack
train
c7a7d005fffc8b8fc028d6aa
train
function
def mounted(name, device, fstype, mkmnt=False, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', persist=True, mount=True, user=None, match_on='auto'): ''' Verify that a de...
def mounted(name, device, fstype, mkmnt=False, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', persist=True, mount=True, user=None, match_on='auto'):
''' Verify that a device is mounted name The path to the location where the device is to be mounted device The device name, typically the device node, such as ``/dev/sdb1`` or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314`` or ``LABEL=DATA`` fstype The filesystem typ...
ounted: - device: /dev/sdb1 - fstype: ext4 - mkmnt: True - opts: - defaults /srv/bigdata: mount.mounted: - device: UUID=066e0200-2867-4ebe-b9e6-f30026ca2314 - fstype: xfs - opts: nobootwait,noatime,nodiratime,nobarrier,logbufs=8 - dump...
256
256
3,535
58
197
vamshi98/salt-formulas
salt/states/mount.py
Python
mounted
mounted
43
434
43
54
f751765b6fbbbe871e4c32dd5e4189c32e85bb54
bigcode/the-stack
train
eab739a6330c3f300ff8522c
train
function
def swap(name, persist=True, config='/etc/fstab'): ''' Activates a swap device .. code-block:: yaml /root/swapfile: mount.swap .. note:: ``swap`` does not currently support LABEL ''' ret = {'name': name, 'changes': {}, 'result': True, ...
def swap(name, persist=True, config='/etc/fstab'):
''' Activates a swap device .. code-block:: yaml /root/swapfile: mount.swap .. note:: ``swap`` does not currently support LABEL ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} on_ = __salt__['mount.swaps']()...
__salt__['mount.set_fstab'](name, device, fstype, opts, dump, pass_nu...
192
192
643
13
178
vamshi98/salt-formulas
salt/states/mount.py
Python
swap
swap
437
519
437
437
27935f0c7d9b4ee92bd7280d60a1be64b86e4958
bigcode/the-stack
train