query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Scans the given image for the 'ntraps' number of trap intensity peaks. Then extracts the 1dimensional gaussian profiles across the traps and returns a list of the amplitudes.
def guess_image(which_cam, image, ntraps): threshes = [0.5, 0.65] ## Image Conditioning ## margin = 10 threshold = np.max(image)*threshes[which_cam] im = image.transpose() x_len = len(im) peak_locs = np.zeros(x_len) peak_vals = np.zeros(x_len) ## Trap Peak Detection ## for i in range(x_len): if i < margin or x_len - i < margin: peak_locs[i] = 0 peak_vals[i] = 0 else: peak_locs[i] = np.argmax(im[i]) peak_vals[i] = max(im[i]) ## Trap Range Detection ## first = True pos_first, pos_last = 0, 0 left_pos = 0 for i, p in enumerate(peak_vals): if p > threshold: left_pos = i elif p < threshold and left_pos != 0: if first: pos_first = (left_pos + i) // 2 first = False pos_last = (left_pos + i) // 2 left_pos = 0 ## Separation Value ## separation = (pos_last - pos_first) / ntraps # In Pixels ## Initial Guesses ## means0 = np.linspace(pos_first, pos_last, ntraps).tolist() waists0 = (separation * np.ones(ntraps) / 2).tolist() ampls0 = (max(peak_vals) * 0.7 * np.ones(ntraps)).tolist() _params0 = [means0, waists0, ampls0, [0.06]] params0 = [item for sublist in _params0 for item in sublist] xdata = np.arange(x_len) plt.figure() plt.plot(xdata, peak_vals) plt.plot(xdata, wrapper_fit_func(xdata, ntraps, params0), '--r') # Initial Guess plt.xlim((pos_first - margin, pos_last + margin)) plt.legend(["Data", "Guess", "Fit"]) plt.show(block=False)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def analyze_image(which_cam, image, ntraps, iteration=0, verbose=False):\n threshes = [0.5, 0.6]\n margin = 10\n threshold = np.max(image) * threshes[which_cam]\n im = image.transpose()\n\n x_len = len(im)\n peak_locs = np.zeros(x_len)\n peak_vals = np.zeros(x_len)\n\n ## Trap Peak Detectio...
[ "0.5896619", "0.5877746", "0.52297366", "0.5136815", "0.50773364", "0.504893", "0.50198776", "0.4991051", "0.49902415", "0.4987427", "0.4953718", "0.4843196", "0.48095766", "0.48035288", "0.479248", "0.47632834", "0.4758519", "0.47351038", "0.47328326", "0.4723849", "0.470226...
0.52466863
2
Scans the given image for the 'ntraps' number of trap intensity peaks. Then extracts the 1dimensional gaussian profiles across the traps and returns a list of the amplitudes.
def analyze_image(which_cam, image, ntraps, iteration=0, verbose=False): threshes = [0.5, 0.6] margin = 10 threshold = np.max(image) * threshes[which_cam] im = image.transpose() x_len = len(im) peak_locs = np.zeros(x_len) peak_vals = np.zeros(x_len) ## Trap Peak Detection ## for i in range(x_len): if i < margin or x_len - i < margin: peak_locs[i] = 0 peak_vals[i] = 0 else: peak_locs[i] = np.argmax(im[i]) peak_vals[i] = max(im[i]) ## Trap Range Detection ## first = True pos_first, pos_last = 0, 0 left_pos = 0 for i, p in enumerate(peak_vals): if p > threshold: left_pos = i elif left_pos != 0: if first: pos_first = (left_pos + i) // 2 first = False pos_last = (left_pos + i) // 2 left_pos = 0 ## Separation Value ## separation = (pos_last - pos_first) / ntraps # In Pixels ## Initial Guesses ## means0 = np.linspace(pos_first, pos_last, ntraps).tolist() waists0 = (separation * np.ones(ntraps) / 2).tolist() ampls0 = (max(peak_vals) * 0.7 * np.ones(ntraps)).tolist() _params0 = [means0, waists0, ampls0, [0.06]] params0 = [item for sublist in _params0 for item in sublist] ## Fitting ## if verbose: print("Fitting...") xdata = np.arange(x_len) popt, pcov = curve_fit(lambda x, *params_0: wrapper_fit_func(x, ntraps, params_0), xdata, peak_vals, p0=params0) if verbose: print("Fit!") plt.figure() plt.plot(xdata, peak_vals) # Data if iteration: plt.plot(xdata, wrapper_fit_func(xdata, ntraps, params0), '--r') # Initial Guess plt.plot(xdata, wrapper_fit_func(xdata, ntraps, popt)) # Fit plt.title("Iteration: %d" % iteration) else: plt.title("Final Product") plt.xlim((pos_first - margin, pos_last + margin)) plt.legend(["Data", "Guess", "Fit"]) plt.show(block=False) print("Fig_Newton") trap_powers = np.frombuffer(popt[2 * ntraps:3 * ntraps]) return trap_powers
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def trapfilt_taps(N, phil, alfa):\n\n\n\n tt = arange(-N/2,N/2 + 1) # Time axis for h(t) \n # ***** Generate impulse response ht here *****\n ht = zeros(len(tt))\n ix = where(tt != 0)[0]\n if alfa != 0:\n ht[ix] = ((sin(2*pi*phil*tt[ix]))/(pi*tt[ix]))*((s...
[ "0.587632", "0.52485836", "0.5228704", "0.5138485", "0.5076651", "0.50504184", "0.5020896", "0.49921283", "0.49873865", "0.4987357", "0.49527085", "0.48427442", "0.48109403", "0.4805407", "0.47939897", "0.47633266", "0.47571003", "0.47376722", "0.47331765", "0.47273827", "0.4...
0.5898754
0
Given the opened camera object and the Slider object connected to the camera's exposure, adjusts the exposure to just below clipping. Binary Search
def fix_exposure(cam, slider, verbose=False): margin = 10 exp_t = MAX_EXP / 2 cam._set_exposure(exp_t * u.milliseconds) time.sleep(0.5) print("Fetching Frame") im = cam.latest_frame() x_len = len(im) right, left = MAX_EXP, 0 inc = right / 10 for _ in range(10): ## Determine if Clipping or Low-Exposure ## gap = 255 for i in range(x_len): if i < margin or x_len - i < margin: continue else: gap = min(255 - max(im[i]), gap) ## Make Appropriate Adjustment ## if gap == 0: if verbose: print("Clipping at: ", exp_t) right = exp_t elif gap > 50: if verbose: print("Closing gap: ", gap, " w/ exposure: ", exp_t) left = exp_t else: if verbose: print("Final Exposure: ", exp_t) return if inc < 0.01: exp_t -= inc if gap == 0 else -inc else: exp_t = (right + left) / 2 inc = (right - left) / 10 slider.set_val(exp_t) time.sleep(1) im = cam.latest_frame()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_exposure(self, expo):\n if expo == 0:\n self.exposure = 0\n elif expo == 1:\n self.exposure = min(9, self.exposure+1)\n elif expo == -1:\n self.exposure = max(-9, self.exposure-1)\n self.drone.set_exposure(self.exposure)\n log.info(f\"EXPO...
[ "0.59731835", "0.5947797", "0.5704381", "0.5572308", "0.5527399", "0.54456806", "0.54195607", "0.5414224", "0.5396532", "0.53867406", "0.5374971", "0.5353075", "0.52843153", "0.52828944", "0.52818215", "0.52474177", "0.5239085", "0.5233961", "0.52310765", "0.52299416", "0.522...
0.71824807
0
We specify the FNN based networks over here. A single network produce both s and t parts. Coupling Layer currently comprises of 1 full transform but this can be made more complex.
def coupling_layer_specifications(hyper_params): D = hyper_params['data_dim'] H = hyper_params['rnvp_num_hidden_units'] d_1 = np.int(D//2) if D%2 == 0 else np.int(D//2) + 1 d_2 = np.int(D - d_1) assert(d_1 + d_2 == D) coupling_layer_sizes = [] coupling_layer_sizes.append([d_1, H, H, 2*d_2]) coupling_layer_sizes.append([d_2, H, H, 2*d_1]) return coupling_layer_sizes
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, channel):\n super(CoarseFineFlownet, self).__init__()\n in_c = channel * 2\n conv1 = nn.Sequential(nn.Conv2d(in_c, 24, 5, 2, 2), nn.ReLU(True))\n conv2 = nn.Sequential(nn.Conv2d(24, 24, 3, 1, 1), nn.ReLU(True))\n conv3 = nn.Sequential(nn.Conv2d(24, 24, 5, 2, 2)...
[ "0.68114513", "0.6745461", "0.67398894", "0.67094636", "0.6685526", "0.6679833", "0.66453695", "0.6631616", "0.65937024", "0.65893584", "0.65746665", "0.6562869", "0.6550034", "0.6546586", "0.65442574", "0.6542558", "0.65119946", "0.64806116", "0.64779437", "0.64562774", "0.6...
0.0
-1
draw all beads in 3D
def draw_beads_3d(ax,beads): nslice,nptcl,ndim = beads.shape com = beads.mean(axis=0) # center of mass of each particle, used to label the particles only ptcls = [] for iptcl in range(nptcl): mypos = beads[:,iptcl,:] # all time slices for particle iptcl pos = np.insert(mypos,0,mypos[-1],axis=0) # close beads line = ax.plot(pos[:,0],pos[:,1],pos[:,2],marker='o') # draw particle text = ax.text(com[iptcl,0],com[iptcl,1],com[iptcl,2],'ptcl %d' % iptcl,fontsize=20) # label particle ptcls.append( (line,text) ) return ptcls
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def render_wireframe_3d(self, **kwds):\n wireframe = [];\n for l in self.lines:\n l_coords = self.coordinates_of(l)\n wireframe.append( line3d(l_coords, **kwds))\n for a in self.arrows:\n a_coords = self.coordinates_of(a)\n wireframe.append(arrow3d(a...
[ "0.67704284", "0.6621511", "0.6335428", "0.62092894", "0.612173", "0.6121571", "0.6106901", "0.60958236", "0.6095626", "0.6073754", "0.60695255", "0.60470665", "0.6022389", "0.60214126", "0.6004602", "0.5997901", "0.5991583", "0.5977998", "0.59440416", "0.59368646", "0.593158...
0.6539542
2
thermodynmic estimator of the kinetic energy
def thermodynamic_kinetic(paths,lam,tau): nslice,nptcl,ndim,nconf = paths.shape ke = ndim*nptcl/2./tau * np.ones(nconf) for islice in range(nslice): r2_arr = (paths[islice]-paths[(islice+1)%nslice])**2. # (nptcl,ndim,nconf) r2 = r2_arr.sum(axis=0).sum(axis=0) # (nconf,) ke -= r2/(4.*lam*tau**2.)/nslice return ke
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def price_heston_mc(kappa_,theta_,sigma_,rho_,r_,T_,L_,V0_,S0_,K0_,N_):\r\n esp_ = monte_carlo(kappa_,theta_,sigma_,rho_,r_,T_,L_,V0_,S0_,K0_,N_)\r\n return exp(-r_*T_)*esp_", "def kineticEnergy(self):\n return self.params['kinetic']", "def energyK(k):\r\n C1 = 9.7846113e-07\r\n C2 = 12.2638...
[ "0.685864", "0.6753086", "0.66774917", "0.65416646", "0.64236945", "0.6406966", "0.6316658", "0.6298241", "0.6277267", "0.6244753", "0.62259036", "0.62029636", "0.61880386", "0.61798847", "0.6175505", "0.6172549", "0.6145199", "0.6102385", "0.6071389", "0.6060328", "0.6001661...
0.6054048
20
Fetches prediction field from prediction byte array. After TensorRT inference, prediction data is saved in byte array and returned by object detection network. This byte array contains several pieces of data about prediction we call one such piece a prediction field. The prediction fields layout is described in TRT_PREDICTION_LAYOUT. This function, given prediction byte array returned by network, staring index of given prediction and field name of interest, returns prediction field data corresponding to given arguments.
def fetch_prediction_field(field_name, detection_out, pred_start_idx): return detection_out[pred_start_idx + TRT_PREDICTION_LAYOUT[field_name]]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_predict(path=MODEL_PATH, version=VERSION, namePredictor=DEFAULT_PREDICTOR):\n logging.info(\"trying to load {}\".format(path + namePredictor + version + '.npz'))\n return np.load(path + namePredictor + version + '.npz')['pred']", "async def predict(params: predict_text):\n tweet = params.text\n...
[ "0.55769396", "0.5293517", "0.52770144", "0.5273354", "0.5251776", "0.52444863", "0.522911", "0.51298296", "0.507966", "0.5062503", "0.50453293", "0.5021716", "0.5021298", "0.5006652", "0.5005181", "0.50023496", "0.49902007", "0.49683675", "0.4965189", "0.4964087", "0.4936551...
0.7810624
0
Parses command line arguments and adjusts internal data structures.
def parse_commandline_arguments(): # Define script command line arguments parser = argparse.ArgumentParser(description='Run object detection inference on input image.') parser.add_argument('input_img_path', metavar='INPUT_IMG_PATH', help='an image file to run inference on') parser.add_argument('-p', '--precision', type=int, choices=[32, 16], default=32, help='desired TensorRT float precision to build an engine with') parser.add_argument('-b', '--max_batch_size', type=int, default=1, help='max TensorRT engine batch size') parser.add_argument('-w', '--workspace_dir', help='sample workspace directory') parser.add_argument('-fc', '--flatten_concat', help='path of built FlattenConcat plugin') # Parse arguments passed args = parser.parse_args() # Set FlattenConcat TRT plugin path and # workspace dir path if passed by user if args.flatten_concat: PATHS.set_flatten_concat_plugin_path(args.flatten_concat) if args.workspace_dir: PATHS.set_workspace_dir_path(args.workspace_dir) if not os.path.exists(PATHS.get_workspace_dir_path()): os.makedirs(PATHS.get_workspace_dir_path()) # Verify Paths after adjustments. This also exits script if verification fails PATHS.verify_all_paths() # Fetch TensorRT engine path and datatype trt_engine_datatype = TRT_PRECISION_TO_DATATYPE[args.precision] trt_engine_path = PATHS.get_engine_path(trt_engine_datatype, args.max_batch_size) if not os.path.exists(os.path.dirname(trt_engine_path)): os.makedirs(os.path.dirname(trt_engine_path)) parsed = { 'input_img_path': args.input_img_path, 'max_batch_size': args.max_batch_size, 'trt_engine_datatype': trt_engine_datatype, 'trt_engine_path': trt_engine_path } return parsed
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_arguments(self):\n \n for arg in sys.argv[1:]:\n (key, sep, value) = arg.partition(\"=\")\n if sep != \"=\":\n raise ProcessorError(\"Illegal argument '%s'\" % arg)\n self.update_data(key, value)", "def parse_arguments(args):", "def __pars...
[ "0.7812506", "0.7636276", "0.7270536", "0.720011", "0.71367455", "0.712731", "0.6990735", "0.6976223", "0.69415474", "0.6897431", "0.6839291", "0.68086874", "0.67994547", "0.67840666", "0.6775619", "0.67488694", "0.6741559", "0.6727123", "0.67215323", "0.67038643", "0.6699622...
0.0
-1
Check if directories on the path, and create them if not.
def check_dir(path): if not os.path.exists(path): os.makedirs(path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _check_path(path):\n os.system(\"if [ ! -d \" + path + \" ]; then mkdir -p \" + path + \"; fi\")", "def _check_dirs(self):\r\n for dir in [self.papers_dir,\r\n self.buffer_dir]:\r\n if not os.path.exists(dir):\r\n message = f'Dir not exists: {dir}. M...
[ "0.7897075", "0.78796077", "0.7873436", "0.7844147", "0.7843228", "0.78394854", "0.7821767", "0.7799039", "0.77543813", "0.77469003", "0.77352756", "0.7700688", "0.7690964", "0.7684836", "0.7626432", "0.75970924", "0.7586215", "0.75739735", "0.75739735", "0.75736177", "0.7571...
0.78439754
4
Get a dictionary with the important tags for DAGMC geometries inputs
def get_dagmc_tags(my_core): dagmc_tags = {} dagmc_tags['geom_dim'] = my_core.tag_get_handle('GEOM_DIMENSION', size=1, tag_type=types.MB_TYPE_INTEGER, storage_type=types.MB_TAG_SPARSE, create_if_missing=True) # geometric dimension dagmc_tags['category'] = my_core.tag_get_handle('CATEGORY', size=32, tag_type=types.MB_TYPE_OPAQUE, storage_type=types.MB_TAG_SPARSE, create_if_missing=True) # the category dagmc_tags['global_id'] = my_core.tag_get_handle('GLOBAL_ID', size=1, tag_type=types.MB_TYPE_INTEGER, storage_type=types.MB_TAG_SPARSE, create_if_missing=True) # id return dagmc_tags
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getTag(self, inputs, tag):\n result = {}\n for into in inputs:\n for i in into:\n if i in self.sim.agents:\n agentTags = self.sim.agents[i].access[\"tags\"]\n if tag in agentTags:\n result[i] = agentTags[tag]\n...
[ "0.6049964", "0.5798417", "0.5783547", "0.56233895", "0.56191564", "0.5531968", "0.54956996", "0.5407354", "0.54043907", "0.5376861", "0.5376861", "0.53438914", "0.53383356", "0.5330779", "0.5323087", "0.5323087", "0.5323087", "0.5323087", "0.5323087", "0.5323087", "0.5323087...
0.6765775
0
Get a dictionary with MOAB ranges for each of the requested entity types inputs
def get_native_ranges(my_core, meshset, entity_types): native_ranges = {} for entity_type in entity_types: native_ranges[entity_type] = my_core.get_entities_by_type( meshset, entity_type) return native_ranges
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_entityset_ranges(my_core, meshset, geom_dim):\n\n entityset_ranges = {}\n entityset_types = ['Nodes', 'Curves', 'Surfaces', 'Volumes']\n for dimension, set_type in enumerate(entityset_types):\n entityset_ranges[set_type] = my_core.get_entities_by_type_and_tag(meshset, types.MBENTITYSET, geo...
[ "0.65154475", "0.600458", "0.5998008", "0.5853334", "0.5807972", "0.5797119", "0.562755", "0.562755", "0.55852807", "0.55669194", "0.5557111", "0.5455386", "0.54513985", "0.5441645", "0.53997433", "0.53997433", "0.5393903", "0.5376995", "0.5375735", "0.53752905", "0.5361025",...
0.6155824
1
Get a dictionary with MOAB Ranges that are specific to the types.MBENTITYSET type inputs
def get_entityset_ranges(my_core, meshset, geom_dim): entityset_ranges = {} entityset_types = ['Nodes', 'Curves', 'Surfaces', 'Volumes'] for dimension, set_type in enumerate(entityset_types): entityset_ranges[set_type] = my_core.get_entities_by_type_and_tag(meshset, types.MBENTITYSET, geom_dim, [dimension]) return entityset_ranges
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getRangeMM(self) -> float:\n ...", "def range_dic_(df_):\n range_dic = {}\n for man in df_['maneuver']:\n trial_indx = df_.index[df_['maneuver'] == man].tolist()\n range_ = (min(trial_indx), max(trial_indx))\n range_dic.update({man: range_})\n return range_dic", "def ra...
[ "0.59818125", "0.5639009", "0.5639009", "0.5624772", "0.5565236", "0.5513016", "0.5494546", "0.5442198", "0.54400784", "0.5380527", "0.5366019", "0.5358748", "0.5318177", "0.5313223", "0.52917475", "0.5266361", "0.5262664", "0.5223182", "0.5186198", "0.517666", "0.5118012", ...
0.6958238
0
This function will return data about the number of triangles on each vertex in a file inputs
def get_triangles_per_vertex(my_core, native_ranges): t_p_v_data = [] tri_dimension = 2 for vertex in native_ranges[types.MBVERTEX]: t_p_v_data.append(my_core.get_adjacencies(vertex, tri_dimension).size()) return np.array(t_p_v_data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def count_triangles(self, file):\n self.nibble(80)\n return struct.unpack(\"@i\", self.nibble(4))[0]", "def get_num_vertices(triangles):\n return numpy.amax(numpy.reshape(triangles, -1)) + 1", "def count_cells(fpath):\n cells = []\n for i in range(40):\n fname = f\"{fpath}/Mesh2d_...
[ "0.7772032", "0.68836695", "0.6398507", "0.6369426", "0.6362666", "0.6353974", "0.6323438", "0.6275137", "0.6170703", "0.6165812", "0.6144632", "0.613628", "0.61066425", "0.6011404", "0.59843576", "0.59520715", "0.5947087", "0.594126", "0.5935394", "0.59270984", "0.59270984",...
0.64086694
2
This function will return data about the number of triangles on each surface in a file inputs
def get_triangles_per_surface(my_core, entity_ranges): t_p_s = {} for surface in entity_ranges['Surfaces']: t_p_s[surface] = my_core.get_entities_by_type( surface, types.MBTRI).size() return t_p_s
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def count_triangles(self, file):\n self.nibble(80)\n return struct.unpack(\"@i\", self.nibble(4))[0]", "def get_num_vertices(triangles):\n return numpy.amax(numpy.reshape(triangles, -1)) + 1", "def count_cells(fpath):\n cells = []\n for i in range(40):\n fname = f\"{fpath}/Mesh2d_...
[ "0.78216827", "0.65307426", "0.64875203", "0.6224915", "0.6100354", "0.60187995", "0.59512895", "0.5924314", "0.59203315", "0.5906817", "0.59059787", "0.5882943", "0.5867339", "0.585497", "0.58549577", "0.5812365", "0.57997227", "0.57795846", "0.57746047", "0.57551175", "0.57...
0.6084134
5
Get the number of surfaces that each volume in a given file contains inputs
def get_surfaces_per_volume(my_core, entityset_ranges): s_p_v = {} for volumeset in entityset_ranges['Volumes']: s_p_v[volumeset] = my_core.get_child_meshsets(volumeset).size() return s_p_v
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def countsubcatchments(inputfilename=FileSettings.settingsdict['inputfilename']):\r\n global count\r\n with open(inputfilename, 'r') as swmmput:\r\n contents = swmmput.readlines()\r\n count = len(contents)\r\n return(count)", "def count_triangles(self, file):\n self.nibble(80)\n ...
[ "0.62458247", "0.6179542", "0.61321104", "0.59735066", "0.5963068", "0.5940635", "0.5933851", "0.58621955", "0.5853695", "0.58389825", "0.5696593", "0.569234", "0.56829655", "0.5678511", "0.56699306", "0.5660936", "0.5654335", "0.5653217", "0.5644729", "0.56445545", "0.562478...
0.613363
2
Get triangles of a volume if geom_dim is 3 Get triangles of a surface if geom_dim is 2 Else get all the triangles inputs
def get_tris(my_core, meshset, geom_dim): # get triangles of a volume if my_core.tag_get_data(geom_dim, meshset)[0][0] == 3: entities = my_core.create_meshset() for surface in my_core.get_child_meshsets(meshset): my_core.add_entities(entities, my_core.get_entities_by_type(surface, types.MBTRI)) tris = my_core.get_entities_by_type(entities, types.MBTRI) # get triangles of a surface elif my_core.tag_get_data(geom_dim, meshset)[0][0] == 2: entities = my_core.create_meshset() my_core.add_entities(entities, my_core.get_entities_by_type(meshset, types.MBTRI)) tris = my_core.get_entities_by_type(entities, types.MBTRI) else: # get all the triangles tris = my_core.get_entities_by_type(meshset, types.MBTRI) return tris
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def split_triangles(mesh):\n triangles = np.asarray(mesh.triangles).copy()\n vertices = np.asarray(mesh.vertices).copy()\n\n triangles_3 = np.zeros_like(triangles)\n vertices_3 = np.zeros((len(triangles) * 3, 3), dtype=vertices.dtype)\n\n for index_triangle, t in enumerate(triangles):\n index...
[ "0.6223683", "0.6053743", "0.6050365", "0.57075876", "0.5699507", "0.56639516", "0.563397", "0.56318665", "0.56237847", "0.5588242", "0.55818903", "0.54913247", "0.5476087", "0.5466476", "0.5459577", "0.54140794", "0.53891593", "0.5373516", "0.53725284", "0.5370129", "0.53510...
0.5960203
3
Get side lengths of triangle inputs
def get_tri_side_length(my_core, tri): side_lengths = [] s = 0 coord_list = [] verts = list(my_core.get_adjacencies(tri, 0)) for vert in verts: coords = my_core.get_coords(vert) coord_list.append(coords) for side in range(3): side_lengths.append(np.linalg.norm(coord_list[side]-coord_list[side-2])) # The indices of coord_list includes the "-2" because this way each side will be matched up with both # other sides of the triangle (IDs: (Side 0, Side 1), (Side 1, Side 2), (Side 2, Side 0)) return side_lengths
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calc_side_lengths(triangles):\n first_vec = [2, 0, 1]\n second_vec = [1, 2, 0]\n sides = triangles[:, first_vec] - triangles[:, second_vec]\n lengths = np.sqrt(np.sum(sides**2, axis=2))\n return lengths", "def get_edge_lengths(points: np.ndarray, triangles: np.ndarray) -> np.ndarray:\n edge...
[ "0.80329156", "0.73527324", "0.6605369", "0.6578953", "0.653027", "0.6457566", "0.6410448", "0.6380816", "0.6373851", "0.634458", "0.63425255", "0.62799424", "0.62611526", "0.62526083", "0.6235124", "0.6221507", "0.62141633", "0.61444443", "0.6128147", "0.61095893", "0.610488...
0.7491572
1
Get the coarseness of area. Coarseness is calculated by dividing surface area of a surface by number of triangles in that surface. inputs
def get_coarseness(my_core, meshset, entity_ranges, geom_dim): coarseness = [] for surface in entity_ranges: surf_area = get_area_triangle(my_core, surface, geom_dim) coarseness.append(len(surf_area)/sum(surf_area)) return coarseness
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_surface_area(self):\n return np.sum(self._find_triangle_areas())", "def compute_area(self):\r\n\r\n \"\"\"Косое произведение векторов\r\n A = (x2-x1; y2-y1; z2-z1)\r\n B = (x3-x1; y3-y1; z3-z1)\r\n S = 0.5*sqrt((Ay*Bz - Az*By)^2 + (Az*Bx - Ax*Bz)^2 + (Ax*By - Ay*Bx)...
[ "0.72606695", "0.69087756", "0.6878328", "0.6759182", "0.66357255", "0.662495", "0.6603431", "0.6533843", "0.65235794", "0.6498596", "0.64894485", "0.643404", "0.64310247", "0.63980806", "0.63846767", "0.6348388", "0.6340205", "0.63149506", "0.62920696", "0.62676907", "0.6259...
0.6548548
7
Cleans the line from geometrical shape characters and replaces these with space.
def clean_text_from_geometrical_shape_unicode(line): line = re.sub(r"([\u25A0-\u25FF])", " ", line) return line
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clean(line):\n line = line.strip('\\n').strip()\n line = line.replace('\\xe2\\x80\\x93', '-')\n line = line.replace('\\xe2\\x80\\x99', '\\'')\n\n return line", "def clean(line):\n line = line.lower().replace(\"\\n\",\" \").replace(\"\\r\",\"\").replace(',',\"\").replace(\">\",\"> \").replace(\...
[ "0.6750238", "0.6354936", "0.60908276", "0.60867965", "0.6052043", "0.5917007", "0.58838075", "0.58618855", "0.5852398", "0.58450764", "0.5843433", "0.584121", "0.5809004", "0.5809004", "0.5773769", "0.5744268", "0.573116", "0.57237", "0.56972486", "0.5695229", "0.5684892", ...
0.8284751
1
Cleans the line from private unicode characters and replaces these with space.
def clean_text_from_private_unicode(line): line = re.sub(r"([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])", " ", line) return line
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clean_text_from_geometrical_shape_unicode(line):\n line = re.sub(r\"([\\u25A0-\\u25FF])\", \" \", line)\n return line", "def clean_text_from_geometrical_shape_unicode(line):\n line = re.sub(r\"([\\u25A0-\\u25FF])\", \" \", line)\n return line", "def RemoveNonUtf8BadChars(line):\n return \"\"...
[ "0.6923628", "0.6923628", "0.6871189", "0.68013835", "0.6612186", "0.6590212", "0.643773", "0.6276485", "0.6224105", "0.6136164", "0.60882586", "0.6054826", "0.6043292", "0.60300654", "0.6018717", "0.6001594", "0.5968716", "0.59620196", "0.59620196", "0.5959176", "0.593358", ...
0.8404962
1
Clears the text from latin supplement unicodes.
def clean_text_from_latin_supplement_unicode(text): return re.sub(r"([\u0080-\u00FF])", " ", text)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def removeNonAsciiFromText(self, text):\n\t\treturn ''.join([i if ord(i) < 128 else '' for i in text])", "def remove_unicode(text):\n regex = r\"(\\\\u....)\"\n text = re.sub(regex, ' ', text)\n return text", "def removeUnicode(text):\n text = re.sub(r'(\\\\u[0-9A-Fa-f]+)',r'', text) \n te...
[ "0.69256425", "0.6896335", "0.68667537", "0.67069024", "0.66337216", "0.65545833", "0.6554385", "0.6529281", "0.6484313", "0.6460039", "0.6445077", "0.64252377", "0.64120406", "0.6407746", "0.6383768", "0.6383287", "0.6367802", "0.6363216", "0.6355911", "0.631609", "0.6307571...
0.6754026
4
Clears the text from general punctuation unicodes
def clean_text_from_general_punctuation_unicode(text): return re.sub(r"([\u2000-\u206F])", " ", text)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_punct(self,text):", "def clear_punctuation(document):\n return re.sub(r'\\D', '', str(document))", "def remove_punctuation(self, text):\n punct = string.punctuation\n trantab = str.maketrans(punct, len(punct) * ' ')\n return text.translate(trantab)", "def remove_punctuation...
[ "0.8042368", "0.7765066", "0.7309863", "0.729243", "0.72679365", "0.7266738", "0.7264455", "0.72357666", "0.7194123", "0.719088", "0.7137011", "0.7126668", "0.7068454", "0.7044288", "0.7034183", "0.70212454", "0.70147127", "0.6998983", "0.6979322", "0.69668394", "0.6941041", ...
0.7302177
4
Clear the text from any characters that would prevent matching words with regex. These include special punctuations, bullet points, new lines etc.
def clean_text_from_nonbasic_characters(text): text = re.sub(r"([^\u0000-\u007F])", " ", text) text = replace_newline_with_space(text).strip() text = text.replace("_", "") text = clean_text_from_multiple_consecutive_whitespaces(text) return text
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def CLEAN(text):\n return _control_char_re.sub('', text)", "def removeSpecialChars(self) -> None:\n self.text = re.sub('[^a-zA-z0-9\\n\\.\\s]', '', self.text)", "def remove_non_alphabetic_text(text):\n return RegexFilters.replace_non_alphabetic_text(text, \"\")", "def remove_punctations_fun(se...
[ "0.788221", "0.77547354", "0.76948416", "0.7690904", "0.76164234", "0.76150995", "0.76150995", "0.76150995", "0.76150995", "0.76150995", "0.76150995", "0.75909275", "0.7558085", "0.7538756", "0.75204813", "0.75020224", "0.74994344", "0.7429214", "0.73992103", "0.73870385", "0...
0.72454876
29
returns a scikitlearn style model/pipeline
def get_model(name): try: from .model_defs import get_model_from_def model = get_model_from_def(name) logger.info("Model {n} loaded from model_defs module".format(n=name)) except NameError: try: model = get_model_from_yaml(name) logger.info("Model {n} loaded from yaml".format(n=name)) except KeyError: try: from .model_defs import parse_model_name model = parse_model_name(name) logger.info("Model {n} parsed from name".format(n=name)) except NameError: sys.exit("Unknown model {n}".format(n=name)) if not hasattr(model, 'name'): model.name = name return model
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_pipeline():\n universe = TradableStocksUS('Real Estate') | TradableStocksUS('Utilities') | \\\n TradableStocksUS('Consumer Staples') | TradableStocksUS('Technology') | \\\n TradableStocksUS('Financials') | TradableStocksUS('Energy') | ...
[ "0.62133336", "0.619528", "0.6192642", "0.6129727", "0.60924697", "0.60888034", "0.60504484", "0.59715533", "0.59501135", "0.5866584", "0.58635634", "0.5856176", "0.57757", "0.5774506", "0.5752574", "0.5752574", "0.5741443", "0.5726265", "0.5723943", "0.5714648", "0.57145613"...
0.0
-1
return a model as defines in model_search.yaml
def get_model_from_yaml(name): filename = pkg_resources.resource_filename('empirical_lsm', 'data/model_search.yaml') with open(filename) as f: model_dict = yaml.load(f)[name] return get_model_from_dict(model_dict)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_model(model=gin.REQUIRED):\n return model", "def get_model(*args):\n return Model()", "def get_model(model):\n all_models = cmd.get_object_list()\n\n if len(all_models) == 0:\n logging.parser_error('No models are opened.')\n return\n\n model = model.lower()\n\n if mode...
[ "0.72097623", "0.6948634", "0.67616165", "0.67475533", "0.66909075", "0.66902417", "0.66678", "0.6573517", "0.65641904", "0.65121186", "0.651177", "0.6477959", "0.6459214", "0.6455929", "0.64499646", "0.6413741", "0.6407674", "0.64009804", "0.6380913", "0.6357358", "0.6337721...
0.6980467
1
Return a sklearn model pipeline from a model_dict
def get_model_from_dict(model_dict): pipe_list = [] if 'transforms' in model_dict: # For basic scikit-learn transforms transforms = model_dict['transforms'].copy() if 'scaler' in transforms: scaler = transforms.pop('scaler') pipe_list.append(get_scaler(scaler)) if 'pca' in transforms: transforms.pop('pca') pipe_list.append(get_pca()) if 'poly' in transforms: args = transforms.pop('poly') pipe_list.append(get_poly(args)) if len(transforms) > 0: raise Exception("unknown transforms: %s" % repr(transforms)) if 'args' in model_dict: model = get_model_class(model_dict['class'], model_dict['args']) else: model = get_model_class(model_dict['class']) if 'clusterregression' in model_dict: from empirical_lsm.clusterregression import ModelByCluster clusterer = model_dict['clusterregression']['class'] cluster_args = model_dict['clusterregression']['args'] model = ModelByCluster( get_clusterer(clusterer, cluster_args), model) pipe_list.append(model) pipe = make_pipeline(*pipe_list) if 'lag' in model_dict: params = model_dict['lag'] pipe = get_lagger(pipe, params) elif 'markov' in model_dict: params = model_dict['markov'] pipe = get_markov_wrapper(pipe, params) if 'forcing_vars' in model_dict: pipe.forcing_vars = model_dict['forcing_vars'] else: logger.warning("Warning: no forcing vars, using defaults (all)") pipe.forcing_vars = get_config(['vars', 'met']) if 'description' in model_dict: pipe.description = model_dict['description'] return pipe
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_pipeline(model):\n\n steps = [\n (\"imp\", SimpleImputer(strategy=\"most_frequent\")),\n (\"norm\", MinMaxScaler()),\n (\"reg\", model)\n ]\n pipeline = Pipeline(steps=steps)\n\n return pipeline", "def build_model():\n # Build ML pipeline using random forest classifie...
[ "0.6688918", "0.64640874", "0.64640874", "0.6416069", "0.6381701", "0.636211", "0.6302781", "0.62598276", "0.62242967", "0.6168712", "0.6149896", "0.6133813", "0.6130566", "0.61174124", "0.6096542", "0.6070486", "0.6065497", "0.60585046", "0.6046623", "0.6042597", "0.603112",...
0.771603
0
Return a Lag wrapper for a pipeline.
def get_lagger(pipe, kwargs): from .transforms import LagWrapper return LagWrapper(pipe, **kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pipeline(self) -> Pipeline:\n if self._to_pipeline is None:\n raise AttributeError(\n \"pipeline not available because `to_pipeline` was not set on __init__.\"\n )\n return self._to_pipeline(self)", "def get_pipeline(tag=None):\n\n\n data_science_pipeline...
[ "0.614468", "0.5957362", "0.59200114", "0.58368886", "0.5657546", "0.54006594", "0.53980225", "0.53207415", "0.53056926", "0.53035724", "0.5302075", "0.52976626", "0.5268746", "0.52655923", "0.5263156", "0.52361935", "0.52361935", "0.52285284", "0.52276915", "0.5182775", "0.5...
0.8226096
0
Return a markov wrapper for a pipeline.
def get_markov_wrapper(pipe, kwargs): from .transforms import MarkovWrapper return MarkovWrapper(pipe, **kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_own_pipeline() -> Pipeline:\n clf = svm.LinearSVC(C=2, loss='hinge')\n vect = TfidfVectorizer(ngram_range=(1, 2))\n\n pipeline = None\n ##### Write code here #######\n pipeline = Pipeline([\n ('vect', vect),\n ('tfidf', TfidfTransformer()),\n ('clf', clf)\n ])\n ...
[ "0.6571192", "0.6444065", "0.6408322", "0.60807306", "0.6047931", "0.5914984", "0.59031147", "0.58204484", "0.5804149", "0.5747107", "0.5725643", "0.5704614", "0.5703797", "0.56960964", "0.56624687", "0.56623226", "0.5654284", "0.562496", "0.5591383", "0.55484897", "0.5527152...
0.83327645
0
Return a scikitlearn clusterer from name and args.
def get_clusterer(name, kwargs): if name == 'KMeans': from sklearn.cluster import KMeans return KMeans(**kwargs) if name == 'MiniBatchKMeans': from sklearn.cluster import MiniBatchKMeans return MiniBatchKMeans(**kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show_cluster(name: str) -> Cluster:\n environment = EnvironmentProvider().environment\n return environment.clusters[name]", "def create_marker_cluster(name: str):\n return MarkerCluster(name=name)", "def launch_example_cluster_cmd(*args, **kwargs):\n return launch_example_cluster(*args, **k...
[ "0.5950856", "0.58060235", "0.5799281", "0.5795873", "0.5752199", "0.56631964", "0.55473256", "0.5533583", "0.5423363", "0.54131496", "0.53921217", "0.53843373", "0.53843373", "0.53843373", "0.5361153", "0.5359831", "0.53507227", "0.53416944", "0.5282299", "0.5266684", "0.526...
0.7380628
0
get a sklearn scaler from a scaler name
def get_scaler(scaler): if scaler == 'standard': from sklearn.preprocessing import StandardScaler return StandardScaler() if scaler == 'minmax': from sklearn.preprocessing import MinMaxScaler return MinMaxScaler()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __create_scaler_type(self):\n\n if self.scalertype == \"standard\":\n return StandardScaler()\n if self.scalertype == \"minmax\":\n return MinMaxScaler(feature_range=self.featureRange)\n assert True, \"An error occured when creating a scaler of type '{}'\".format(self...
[ "0.68367714", "0.63356686", "0.620714", "0.61540365", "0.58169883", "0.57977337", "0.57299215", "0.57015646", "0.56682044", "0.5622776", "0.5611353", "0.55854297", "0.5540283", "0.5517815", "0.5501262", "0.54594105", "0.5455747", "0.5352761", "0.5330781", "0.5323924", "0.5315...
0.81780565
0
get a PCA decomposition
def get_pca(): from sklearn.decomposition import PCA return PCA()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getPCA(data):\n #covM = np.cov(data.T) #note that np.cov define row as variables, col as observations\n #corM = np.corrcoef(data.T) # we will use correlation matrix instead of cov.\n covM = np.cov(data.T)\n eigvalue,eigvector = np.linalg.eig(covM) # each col of the eigvector matrix corresponds to o...
[ "0.76003706", "0.74183345", "0.73857856", "0.73070925", "0.7215321", "0.7163089", "0.7066037", "0.7064292", "0.7050474", "0.7049609", "0.70191026", "0.7006228", "0.6999517", "0.6968802", "0.6924137", "0.68874854", "0.6884852", "0.68622917", "0.67792535", "0.6774958", "0.67328...
0.84510195
0
get a PolynomialFeatures transform
def get_poly(kwargs): from sklearn.preprocessing import PolynomialFeatures return PolynomialFeatures(**kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_polynomial_features(self, X) :\n\n n,d = X.shape\n\n ### ========== TODO : START ========== ###\n # part b: modify to create matrix for simple linear model\n # part g: modify to create matrix for polynomial model\n Phi = X\n m = self.m_\n\n if m == 1:\n...
[ "0.7088703", "0.69679934", "0.66370046", "0.6578305", "0.6512583", "0.6453376", "0.63881963", "0.6234599", "0.6210643", "0.6198964", "0.61715096", "0.61595196", "0.6012623", "0.60067403", "0.595723", "0.5934394", "0.58879584", "0.5873344", "0.582992", "0.5797094", "0.57733417...
0.77433574
0
return a scikitlearn model class, and the required arguments
def get_model_class(class_name, kwargs={}): # , Perceptron, PassiveAggressiveRegressor # , NuSVR, LinearSVR if class_name == 'LinearRegression': from sklearn.linear_model import LinearRegression return LinearRegression(**kwargs) if class_name == 'SGDRegressor': from sklearn.linear_model import SGDRegressor return SGDRegressor(**kwargs) if class_name == 'SVR': from sklearn.svm import SVR return SVR(**kwargs) if class_name == 'DecisionTreeRegressor': from sklearn.tree import DecisionTreeRegressor return DecisionTreeRegressor(**kwargs) if class_name == 'ExtraTreesRegressor': from sklearn.ensemble import ExtraTreesRegressor return ExtraTreesRegressor(**kwargs) if class_name == 'KNeighborsRegressor': from sklearn.neighbors import KNeighborsRegressor return KNeighborsRegressor(**kwargs) if class_name == 'MLPRegressor': from sklearn.neural_network import MLPRegressor return MLPRegressor(**kwargs) raise Exception("Unknown Model class")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self):\n self.name = \"Schaffer\"\n objectives = [o_sh_1, o_sh_2]\n decisions = [Decision(-10 ** 5, 10 ** 5)]\n Model.__init__(self, objectives, None, decisions)", "def modelClass(self):\n raise NotImplementedError", "def __init__(self):\n self.name = \"Kursaw...
[ "0.6693503", "0.65363216", "0.6457696", "0.64020926", "0.6377376", "0.6377376", "0.6377376", "0.6377376", "0.6377376", "0.6333438", "0.6327423", "0.6295708", "0.60578156", "0.6057667", "0.6044534", "0.60367906", "0.5996065", "0.5984835", "0.5975537", "0.59328324", "0.59180677...
0.55198646
68
Initialize with normalized columns
def normc_init(std=1.0, axis=0): def _initializer(shape, dtype=None, partition_info=None): # pylint: disable=W0613 out = np.random.randn(*shape).astype(np.float32) out *= std / np.sqrt(np.square(out).sum(axis=axis, keepdims=True)) return tf.constant(out) return _initializer
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_normalized(self):\n for row, s in enumerate(self.S):\n for col, t in enumerate(self.T):\n\n if self.symmetric and row > col:\n pass\n\n elif self.symmetric and row == col:\n self.normalized_mat[row, col] = 1\n\n ...
[ "0.62527007", "0.61988616", "0.6170687", "0.6163979", "0.601633", "0.59947926", "0.5964604", "0.59518266", "0.5946991", "0.5934487", "0.5933899", "0.59310675", "0.59298176", "0.587819", "0.5838801", "0.5835919", "0.5826909", "0.5814432", "0.5814432", "0.5799486", "0.5779557",...
0.0
-1
Gated recurrent unit (GRU) with nunits cells.
def call(self, inputs, state): x, new = inputs while len(state.get_shape().as_list()) > len(new.get_shape().as_list()): new = tf.expand_dims(new,len(new.get_shape().as_list())) h = state * (1.0 - new) hx = tf.concat([h, x], axis=1) mr = tf.sigmoid(tf.matmul(hx, self.w1) + self.b1) # r: read strength. m: 'member strength m, r = tf.split(mr, 2, axis=1) rh_x = tf.concat([r * h, x], axis=1) htil = tf.tanh(tf.matmul(rh_x, self.w2) + self.b2) h = m * h + (1.0 - m) * htil return h, h
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_gru_cell(num_units, dropout):\n cell = tf.nn.rnn_cell.GRUCell(num_units)\n if dropout:\n result = tf.nn.rnn_cell.DropoutWrapper(cell,\n output_keep_prob=1-dropout)\n return result", "def _initialize_gru_cell(self, num_units):\n return gru_cell.Laye...
[ "0.721755", "0.66543376", "0.6298048", "0.62718433", "0.5896392", "0.5840149", "0.57050383", "0.5683324", "0.56716853", "0.5620621", "0.56158394", "0.56078464", "0.55852866", "0.5582799", "0.5549927", "0.55428386", "0.5535521", "0.551115", "0.5498461", "0.54404557", "0.538380...
0.0
-1
create base passwords for consumer threads to crypt
def generate_data(q, maxlen=2, minlen=1): alphabet = 'ab' alphabet = printable for l in range(minlen, maxlen+1): for s in product(alphabet, repeat=l): q.put( ''.join(s) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def passwordGen() :\n\treturn __randomString(12)", "def generate_password(c, user=\"root\"):\n passw = subprocess.run(\n [\n \"nix\",\n \"run\",\n \"--inputs-from\",\n \".#\",\n \"nixpkgs#xkcdpass\",\n \"--\",\n \"-d-\",\n ...
[ "0.68011814", "0.6634942", "0.65811294", "0.6548595", "0.6521094", "0.64116335", "0.6410874", "0.6394931", "0.63810545", "0.637443", "0.6355256", "0.63321126", "0.63251275", "0.6267523", "0.62596804", "0.62588465", "0.6251437", "0.62477094", "0.6220845", "0.62131107", "0.6190...
0.0
-1
pull data from the queue and add to database
def record_data(q): db = psycopg2.connect( dbname='rainbow', host='humpy', user='rainbow', password='bowrain', ); cur = db.cursor(); while True: vals = q.get() for val in vals: #print val['h'] try: cur.execute(""" INSERT INTO three_des (pass, hash) VALUES(%(p)s, %(h)s) """, val ) except: print "Failed to insert" db.commit() q.task_done()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def worker(self, queue):\n with sa.create_engine(dsn).connect() as dbcon:\n while True:\n if queue.qsize() == 0:\n sleep(1)\n if queue.qsize() == 0:\n break\n continue\n item = queue.get(...
[ "0.6866185", "0.6528412", "0.65014994", "0.6360959", "0.6359229", "0.6332785", "0.6331364", "0.63042796", "0.62166846", "0.621502", "0.6206312", "0.618142", "0.61665404", "0.6134651", "0.61273587", "0.61071765", "0.6074403", "0.60732526", "0.6055935", "0.6055481", "0.60451365...
0.0
-1
Check GMail E.g. messages,unseen = imap.check_gmail('username.com','password')
def check_gmail(username, password): i = imaplib.IMAP4_SSL('imap.gmail.com') try: i.login(username, password) x, y = i.status('INBOX', '(MESSAGES UNSEEN)') messages = int(re.search('MESSAGES\s+(\d+)', y[0]).group(1)) unseen = int(re.search('UNSEEN\s+(\d+)', y[0]).group(1)) return messages, unseen except: return False, 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def checkEmail():\n\tpop_conn = poplib.POP3_SSL('pop.gmail.com')\n\tpop_conn.user('')\n\tpop_conn.pass_('')\n\t#Get messages from server:\n\tmessages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]\n\t# Concat message pieces:\n\tmessages = [\"\\n\".join(mssg[1]) for mssg in messages]\n\t#Parse ...
[ "0.70329154", "0.6592309", "0.64842856", "0.636004", "0.6350439", "0.62164766", "0.6210396", "0.6174336", "0.60854125", "0.6038846", "0.6019747", "0.5920456", "0.58898234", "0.5836752", "0.5829357", "0.57975626", "0.57911247", "0.57865626", "0.5757906", "0.57237977", "0.56982...
0.8364727
0
Converts a raw packet to a dpkt packet regarding of link type.
def iplayer_from_raw(raw, linktype=1): if linktype == 1: # ethernet pkt = dpkt.ethernet.Ethernet(raw) ip = pkt.data elif linktype == 101: # raw ip = dpkt.ip.IP(raw) else: raise Exception("unknown PCAP linktype") return ip
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_packet(linktype, packet):\n link_layer = parse_Ethernet(packet) if linktype == pcapy.DLT_EN10MB else parse_Cooked(packet)\n if link_layer['payload_type'] in ['IPv4', 'IPv6']:\n network_layer = parse_IPv4(link_layer['payload']) if link_layer['payload_type'] == 'IPv4' else parse_IPv6(link_laye...
[ "0.68164754", "0.62622094", "0.5889911", "0.5856772", "0.5697665", "0.52689415", "0.5258935", "0.52217716", "0.5157317", "0.51023954", "0.5042225", "0.5041668", "0.49423012", "0.49230462", "0.4902196", "0.4897916", "0.4865398", "0.48552364", "0.4845798", "0.48386303", "0.4838...
0.63520455
1
Parse a packet from a pcap just enough to gain a flow description tuple
def flowtuple_from_raw(raw, linktype=1): ip = iplayer_from_raw(raw, linktype) if isinstance(ip, dpkt.ip.IP): sip, dip = socket.inet_ntoa(ip.src), socket.inet_ntoa(ip.dst) proto = ip.p sport, dport = 0, 0 l3 = ip.data # try to get the layer 3 source and destination port, but its ok if this fails, # which will happen when we get IP fragments or packets with invalid checksums try: sport, dport = l3.sport, l3.dport except AttributeError: pass else: sip, dip, proto = 0, 0, -1 sport, dport = 0, 0 flowtuple = (sip, dip, sport, dport, proto) return flowtuple
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_packet(packet, traffic_type, pkt_type, exp_dst, step):\n packet_count = 0\n if(traffic_type == \"encap\"):\n if(pkt_type == \"stp\"):\n for i in packet:\n if ((packet[i]['Ethernet']['IP']['src'] == DST_IP) and\n (packet[i]['Ethernet']['IP']['dst']...
[ "0.7090595", "0.7003652", "0.69936156", "0.66334194", "0.65440345", "0.65436566", "0.6405004", "0.63479155", "0.6322695", "0.628168", "0.62721276", "0.6175732", "0.60703814", "0.6070341", "0.60200423", "0.60150564", "0.5997884", "0.5978716", "0.5949455", "0.59455645", "0.5936...
0.573576
29
Get the payload from a packet, the data below TCP/UDP basically
def payload_from_raw(raw, linktype=1): ip = iplayer_from_raw(raw, linktype) try: return ip.data.data except: return ""
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_payload(packet):\n #payload_len = get_payload_length(packet)\n adaptation_field_len = TS.get_adaptation_field_length(packet)\n header_size = 4 + adaptation_field_len\n return packet[header_size:]", "def get_tcp_packet_payload(pkt: dpkt.ethernet.Ethernet) -> bytes:\n eth = dpkt.ethernet.Eth...
[ "0.8326517", "0.78962934", "0.7087218", "0.6683006", "0.6564376", "0.65308803", "0.6511432", "0.65108025", "0.6451101", "0.63990587", "0.6355475", "0.63496506", "0.6315682", "0.62409586", "0.62407076", "0.6233684", "0.62289816", "0.62234855", "0.61914325", "0.61500925", "0.61...
0.65222436
6
Extract all packets belonging to the same flow from a pcap packet iterator
def next_connection_packets(piter, linktype=1): first_ft = None for ts, raw in piter: ft = flowtuple_from_raw(raw, linktype) if not first_ft: first_ft = ft sip, dip, sport, dport, proto = ft if not (first_ft == ft or first_ft == (dip, sip, dport, sport, proto)): break yield { "src": sip, "dst": dip, "sport": sport, "dport": dport, "proto": proto, "raw": payload_from_raw(raw, linktype).encode("base64"), "direction": first_ft == ft, }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def filter(self):\n # outfile = open(self.newpcap, 'wb')\n # writer = dpkt.pcap.Writer(outfile)\n f = open(self.pcapfile, 'rb')\n packets = dpkt.pcap.Reader(f)\n\n for timestamp, buf in packets:\n eth = dpkt.ethernet.Ethernet(buf)\n if not isinstance(eth.dat...
[ "0.6305733", "0.6296941", "0.6157458", "0.5966342", "0.58530146", "0.58158106", "0.5761478", "0.5597372", "0.5591383", "0.5550107", "0.5509687", "0.5483427", "0.5468516", "0.54531425", "0.53616995", "0.52512836", "0.5180603", "0.51701915", "0.5169873", "0.5168804", "0.5165378...
0.67187
0
Open a PCAP, seek to a packet offset, then get all packets belonging to the same connection
def packets_for_stream(fobj, offset): pcap = dpkt.pcap.Reader(fobj) pcapiter = iter(pcap) ts, raw = pcapiter.next() fobj.seek(offset) for p in next_connection_packets(pcapiter, linktype=pcap.datalink()): yield p
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_packets(pcap):\n\n # For each packet in the pcap process the contents\n for timestamp, buf, hdr_len in pcap:\n \n # Unpack the Ethernet frame (mac src/dst, ethertype)\n eth = dpkt.ethernet.Ethernet(buf)\n # print('Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst), ...
[ "0.5710354", "0.5529603", "0.5436237", "0.5389503", "0.5370659", "0.5341635", "0.5319951", "0.5312948", "0.5296589", "0.52821374", "0.5232271", "0.5231817", "0.5208476", "0.52023923", "0.51755023", "0.5116855", "0.5112408", "0.5110333", "0.5092085", "0.5089987", "0.5086152", ...
0.69073343
0
batch sort helper with temporary files, supports sorting large stuff
def batch_sort(input_iterator, output_path, buffer_size=1024**2, output_class=None): if not output_class: output_class = input_iterator.__class__ chunks = [] try: while True: current_chunk = list(islice(input_iterator,buffer_size)) if not current_chunk: break current_chunk.sort() output_chunk_name = os.path.join(TMPD, "%06i" % len(chunks)) output_chunk = output_class(output_chunk_name) for elem in current_chunk: output_chunk.write(elem.obj) output_chunk.close() chunks.append(input_iterator.__class__(output_chunk_name)) output_file = output_class(output_path) for elem in heapq.merge(*chunks): output_file.write(elem.obj) output_file.close() except: raise finally: for chunk in chunks: try: chunk.close() os.remove(chunk.name) except Exception: pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def batchSort(input, output, key, buffer_size, tempdir):\n def merge(key=None, *iterables):\n if key is None:\n keyed_iterables = iterables\n else:\n Keyed = namedtuple(\"Keyed\", [\"key\", \"obj\"])\n keyed_iterables = [(Keyed(key(obj), obj) for obj in iterable)\n...
[ "0.72347873", "0.69368804", "0.66853625", "0.66780645", "0.6673519", "0.65403235", "0.6349198", "0.61560905", "0.60991603", "0.6048404", "0.60408694", "0.60184044", "0.6008325", "0.59858507", "0.59529555", "0.5915996", "0.5901437", "0.59011704", "0.58594245", "0.5847667", "0....
0.68566626
2
Use SortCap class together with batch_sort to sort a pcap
def sort_pcap(inpath, outpath): inc = SortCap(inpath) batch_sort(inc, outpath, output_class=lambda path: WriteCap(path, linktype=inc.linktype)) return 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def external_sort(input_file_name, block_size, output_file_name=None):\n if output_file_name is None:\n output_file_name = input_file_name\n sorter = ExternalSort(input_file_name, block_size, output_file_name)\n sorter.run()", "def step020():\n logger.logMessage('Begin: Sorting records')\n ...
[ "0.55296206", "0.5489133", "0.5482073", "0.5391432", "0.53850245", "0.53489995", "0.5328854", "0.52847326", "0.5241572", "0.5189761", "0.5177634", "0.51613575", "0.51465315", "0.5137804", "0.5135673", "0.51097757", "0.51089555", "0.51009786", "0.5096934", "0.5095022", "0.5090...
0.7660257
0
test that the StrainData.fetch_open_frame works as expected
def test_fetch_open_frame(self): import requests pesummary_data = StrainData.fetch_open_frame( "GW190412", IFO="L1", duration=32, sampling_rate=4096., channel="L1:GWOSC-4KHZ_R1_STRAIN", format="hdf5" ) N = len(pesummary_data) np.testing.assert_almost_equal(N * pesummary_data.dt.value, 32.) np.testing.assert_almost_equal(1. / pesummary_data.dt.value, 4096.) assert pesummary_data.IFO == "L1" _data = requests.get( "https://www.gw-openscience.org/eventapi/html/GWTC-2/GW190412/v3/" "L-L1_GWOSC_4KHZ_R1-1239082247-32.gwf" ) with open("L-L1_GWOSC_4KHZ_R1-1239082247-32.gwf", "wb") as f: f.write(_data.content) data2 = TimeSeries.read( "L-L1_GWOSC_4KHZ_R1-1239082247-32.gwf", channel="L1:GWOSC-4KHZ_R1_STRAIN" ) np.testing.assert_almost_equal(pesummary_data.value, data2.value) np.testing.assert_almost_equal( pesummary_data.times.value, data2.times.value )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_fetch_open_data(self):\n args = [\"L1\", 1126259446, 1126259478]\n pesummary_data = StrainData.fetch_open_data(*args)\n gwpy_data = TimeSeries.fetch_open_data(*args)\n np.testing.assert_almost_equal(pesummary_data.value, gwpy_data.value)\n np.testing.assert_almost_equal(...
[ "0.73446274", "0.65186745", "0.6414948", "0.6280164", "0.61943877", "0.6105646", "0.5987783", "0.596136", "0.5908009", "0.5907794", "0.59036356", "0.5877466", "0.5877377", "0.5873337", "0.5770271", "0.57309335", "0.57286495", "0.5710138", "0.569773", "0.56320137", "0.5627794"...
0.81294215
0
Test that the gwpy methods are still the same
def test_fetch_open_data(self): args = ["L1", 1126259446, 1126259478] pesummary_data = StrainData.fetch_open_data(*args) gwpy_data = TimeSeries.fetch_open_data(*args) np.testing.assert_almost_equal(pesummary_data.value, gwpy_data.value) np.testing.assert_almost_equal( pesummary_data.times.value, gwpy_data.times.value ) assert isinstance(pesummary_data.gwpy, TimeSeries) np.testing.assert_almost_equal( pesummary_data.gwpy.value, gwpy_data.value ) np.testing.assert_almost_equal( pesummary_data.gwpy.times.value, gwpy_data.times.value ) assert pesummary_data.IFO == "L1" assert list(pesummary_data.strain_dict.keys()) == ["L1"] np.testing.assert_almost_equal( pesummary_data.strain_dict["L1"].value, gwpy_data.value ) np.testing.assert_almost_equal( pesummary_data.strain_dict["L1"].times.value, gwpy_data.times.value )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_method(self):\n self.assertEqual(self.method, 'modified strong collision')", "def test_required_methods(self):", "def test_identical(self):\n write this test!", "def test_class_ne_method(self, test_instances):\n a, b, c = test_instances\n\n assert a != c\n assert b...
[ "0.68101746", "0.6541694", "0.65237844", "0.65063614", "0.6301085", "0.62971485", "0.61756206", "0.61576486", "0.6139045", "0.6088883", "0.6029623", "0.602739", "0.6020766", "0.60056776", "0.5970609", "0.5970609", "0.5970609", "0.5970609", "0.5970609", "0.5945786", "0.5943556...
0.0
-1
Test that the plotting methods work as expected
def test_plots(self): args = ["L1", 1126259446, 1126259478] pesummary_data = StrainData.fetch_open_data(*args) fig = pesummary_data.plot(type="td") assert isinstance(fig, matplotlib.figure.Figure) fig = pesummary_data.plot(type="fd") assert isinstance(fig, matplotlib.figure.Figure) fig = pesummary_data.plot(1126259446 + 20., type="omegascan") assert isinstance(fig, matplotlib.figure.Figure) fig = pesummary_data.plot(type="spectrogram") assert isinstance(fig, matplotlib.figure.Figure)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_plotting():\n specs = _read_schrodinger('tests/test_data/{}.inp'.format(PROBLEM))\n xint, yint = _interpolate(specs['interpolxydecs'][:, 0],\n specs['interpolxydecs'][:, 1], specs['xopt'])\n\n energies = np.loadtxt('tests/test_data/energies_{}.ref'.format(PROBLEM))\n ...
[ "0.7648768", "0.75122124", "0.72958684", "0.7275574", "0.72454226", "0.7222819", "0.7141116", "0.70794994", "0.7067178", "0.70542", "0.70453763", "0.7018102", "0.70058864", "0.6963196", "0.6957051", "0.6953664", "0.6890608", "0.6844756", "0.6818328", "0.67763114", "0.67755586...
0.6778257
19
Return elements e of s for which f(e) is true.
def filter_link(f, s): if s is Link.empty: return s else: filtered = filter_link(f, s.rest) if f(s.first): return Link(s.first, filtered) else: return filtered
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def selectElements(self, f, elements):\n if isinstance(elements, types.StringTypes):\n m = self.elementIndex(elements)\n return f[m]\n if elements:\n fs = []\n k = 0\n for s in elements:\n k = self.elementIndex(s)\n ...
[ "0.58423346", "0.57762986", "0.572943", "0.56309384", "0.55529606", "0.554871", "0.5516751", "0.54883784", "0.5471321", "0.54678047", "0.54397553", "0.5426767", "0.54211754", "0.5374095", "0.5334541", "0.5296604", "0.5284521", "0.52649575", "0.52402025", "0.51693165", "0.5168...
0.5204124
19
Return true if set s contains value v as an element. >>> s = Link(1, Link(3, Link(2))) >>> contains(s, 2) True >>> contains(s, 4) False
def contains(s, v): head = s while not empty(head): if head.first == v: return True head = head.rest return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __contains__(self, v):\n for i in self:\n if v in i:\n return True\n False", "def contains(s, v):\n if empty(s):\n return False\n elif s.first == v:\n return True\n else:\n return contains(s.rest, v)", "def has(self, v):\n return ...
[ "0.7584771", "0.7085561", "0.6912982", "0.6782562", "0.6782562", "0.6781164", "0.6648094", "0.6498835", "0.647441", "0.64625543", "0.6434304", "0.64121056", "0.6409181", "0.64012474", "0.63954437", "0.6387302", "0.63849604", "0.6380661", "0.634651", "0.63379276", "0.63075536"...
0.7024014
2
Return Set s adjoin v
def adjoin(s, v): if contains(s, v): return s else: return Link(v, s)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_join(self):\n s = djset()\n s.add([1, 2, 3])\n s.add([4, 5, 6])\n s.add([2, 5])\n self.assertEquals({1, 2, 3, 4, 5, 6}, s.data[1])\n self.assertFalse(2 in s.data)", "def getSets():", "def aspset(self):\n try:\n return pset([x.aspset() for x in self])\n...
[ "0.6154213", "0.60516834", "0.59407765", "0.58840305", "0.58840305", "0.582477", "0.57098496", "0.5630604", "0.5627058", "0.5624518", "0.5581384", "0.555813", "0.5543269", "0.5482053", "0.54482526", "0.544728", "0.54431444", "0.5377867", "0.5345894", "0.5336256", "0.5320816",...
0.5403839
17
Add v to a ordered set s and return s. >>> s = Link(1, Link(3, Link(5))) >>> add(s, 0) Link(0, Link(1, Link(3, Link(5)))) >>> add(s, 4) Link(0, Link(1, Link(3, Link(4, Link(5))))) >>> add(s, 6) Link(0, Link(1, Link(3, Link(4, Link(5, Link(6)))))) >>> t = Link(1) >>> add(t, 0) Link(0, Link(1))
def add(s, v): if empty(s): return Link(v) head = s if head.first > v: # s = Link(v, s) #error: assigment, then s will rebind to a new object # s.first, s.rest = v, s # error s.rest = s s.first, s.rest = v, Link(s.first, s.rest) return s # head.first <= v while not empty(head.rest) and head.rest.first <= v: head = head.rest if head.first == v: return s else: head.rest = Link(v, head.rest) return s
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add(s, v):\n if empty(s):\n return Link(v)\n if s.first > v:\n s.first, s.rest = v, Link(s.first, s.rest)\n elif s.first < v and empty(s.rest):\n s.rest = Link(v, s.rest)\n elif s.first < v:\n add(s.rest, v)\n return s", "def add(self, s):\n current = self.fi...
[ "0.7793301", "0.6587982", "0.6429319", "0.6309428", "0.61591506", "0.60639244", "0.5989767", "0.5989767", "0.58004624", "0.5777832", "0.5752884", "0.56904775", "0.56822777", "0.56809616", "0.56809616", "0.56750697", "0.5661514", "0.56589", "0.561813", "0.5617699", "0.55932224...
0.7641497
1
Tests models trained on segmented logmel spectrograms.
def test_wind_mel_model(preds_paths, data_val): # Load model predicitions - allowing for possibility of ensemble model_preds = np.stack([np.load(pred_path) for pred_path in preds_paths]) model_preds = np.mean(model_preds, axis=0) # Get ids and true labels labels = [] ids = [] for example in data_val: labels.append(example[1]) ids.append(example[2]) # Calculate accuracy and label-predication pairs num_examples = 0 num_correct = 0 current_id = None current_label = None c_matrix = np.zeros((50, 50)) for i in range(len(ids)): label = labels[i] id = ids[i] # Check to see if new example has entered if id != current_id: # Evaluate previous id fully - will not enter on first iteration if current_id: current_prediction_probs /= num_ids prediction = np.argmax(current_prediction_probs) # update lab_pred counts c_matrix[int(current_label), int(prediction)] += 1 # Increment correct prediction counter if prediction correct if prediction == current_label: num_correct += 1 # reset and increment variables num_examples += 1 current_id = id current_label = label num_ids = 1 current_prediction_probs = model_preds[i] else: num_ids += 1 current_prediction_probs += model_preds[i] accuracy = num_correct / num_examples print(f"{num_correct} / {num_examples} = {accuracy:.4f}") return accuracy, c_matrix
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_models(directorio=''):\r\n \r\n print('The trained models will be tested now')\r\n start = time.time()\r\n \r\n busqueda = \"ls \" + directorio + \"/*.h5 > model_names.txt\"\r\n\r\n os.system(busqueda)\r\n\r\n X = np.load(directorio + '/Xtest.npy')\r\n diccio = np.load(directorio +...
[ "0.6325506", "0.6192102", "0.6124805", "0.60204524", "0.6009529", "0.5962141", "0.59607697", "0.59232557", "0.589596", "0.58899426", "0.58750546", "0.58347756", "0.5821097", "0.58149606", "0.5804652", "0.578651", "0.5777658", "0.57776195", "0.5773679", "0.5771149", "0.575928"...
0.0
-1
Performs cross validation on a segmented logmel spectrogram trained model.
def cv(preds_path_stem, num_ensemble=1): fold_accs = [] fold_c_matricies = [] for fold in range(1, 6): data_val = load_dataset( f'Data/esc50_mel_wind_tfr/raw/fold_{fold}.tfrecords') pred_paths=[f'{preds_path_stem}preds_fold_{i}_{fold}.npy' for i in range(1, num_ensemble+1)] fold_acc, fold_c_matrix = test_wind_mel_model(pred_paths, data_val) fold_accs.append(fold_acc) fold_c_matricies.append(fold_c_matrix) cv_acc = np.mean(fold_accs) cv_acc_std = np.std(fold_accs) c_matrix = np.sum(fold_c_matricies, axis=0) / np.sum(fold_c_matricies) np.save(f'{preds_path_stem}cmatrix_{num_ensemble}.npy', c_matrix) print(f"The cross validation accuracy is {cv_acc:.4f} " f"+/- 1.96 * {cv_acc_std:.4f}")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run(self, df: pd.DataFrame, model: Any):\n print(f'Running cross validation with the following model:\\n{model}')\n\n df['timestamp'] = pd.to_datetime(df['timestamp'])\n\n date_1 = datetime.datetime(year=2016, month=1, day=1)\n date_2 = datetime.datetime(year=2016, month=4, day=1)\n...
[ "0.67092973", "0.6439459", "0.6373035", "0.63298774", "0.6288726", "0.61524415", "0.6071506", "0.6043888", "0.6030679", "0.60297436", "0.6009352", "0.5996283", "0.59651506", "0.5964834", "0.5883891", "0.5877334", "0.5846096", "0.57740736", "0.5755319", "0.5751334", "0.5747167...
0.0
-1
DO NOT CALL THIS FUNCTION UNLESS YOU HAVE DATA YOU WANT TO STORE IT DELETES THE CURRENT DATA.
def store_images(database): # image folder folder_path = os.getcwd() + '/Data/Test' img_width, img_height = 224, 224 images = [] label = [] for _, dirs, _ in os.walk(folder_path, topdown=True): for directory in dirs: sub_folder_path = os.path.join(folder_path, directory) for _, _, files in os.walk(sub_folder_path): for name in files: if name != '.DS_Store': img = os.path.join(sub_folder_path, name) img = image.load_img(img, target_size=(img_width, img_height)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) images.append(img) label.append(directory) images = np.vstack(images) model = Model() predictions = model.model.predict(images, batch_size=10) db_actions.reinitialize_table(database) for i in range(100): prediction = predictions[i, :] normalized_prediction = prediction / np.sum(prediction) db_actions.add_encoding(database, normalized_prediction, label[i]) print("Sum is: {}".format(np.sum(normalized_prediction)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clearData():\n Co8PersistentData.__dataDict.clear()", "def clear_data(self):\n if isinstance(self.data, DataManager):\n self.data._update_keys(clear=True)\n else:\n self.data = {}", "def clear_storage(self):\r\n raise NotImplementedError('override me')", ...
[ "0.69582635", "0.67999136", "0.67593694", "0.6599251", "0.6595057", "0.6536432", "0.6519219", "0.649931", "0.64161766", "0.6401068", "0.63972634", "0.6385674", "0.63851345", "0.6344443", "0.6343384", "0.63345444", "0.63222915", "0.63222915", "0.6261738", "0.62559605", "0.6239...
0.0
-1
Checks that household is in editing state.
def clean(self): cleaned_data = super().clean() if any(self.errors): # Don't bother validating unless each field is valid on its own return if not self.household.editing: raise forms.ValidationError("Household is not in editing mode.")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def can_edit(self):\n return self.state not in (\n 'scanning', 'resulted', 'cancelled', 'aborted')", "def is_edit(self):\n return self._tag == 'edit'", "def _check_is_editable(self, raise_error: bool = True) -> bool:", "def is_editable(self) -> bool | None:\n return self.check...
[ "0.7178205", "0.71516967", "0.7085395", "0.69433004", "0.6895201", "0.68161714", "0.68161714", "0.66513175", "0.6608026", "0.6533432", "0.6527401", "0.6448996", "0.6317548", "0.62204605", "0.6207848", "0.61636037", "0.6070379", "0.6058616", "0.5964224", "0.5950804", "0.593502...
0.66041714
9
Checks that total of all weights is 100. Weights may be negative.
def clean(self): if any(self.errors): # Don't bother validating unless each form is valid on its own return if self.get_total_weights() != 100: raise forms.ValidationError("Weights must sum to 100; try normalizing.")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_weight_is_positive(self):\n nt.assert_greater(self.herb.weight, 0)", "def test_weighted_total(self):\r\n self.weighted_setup()\r\n self.submit_question_answer('H1P1', {'2_1': 'Correct', '2_2': 'Correct'})\r\n self.submit_question_answer('FinalQuestion', {'2_1': 'Correct', '2_...
[ "0.65198725", "0.6382042", "0.63662297", "0.6255529", "0.62205875", "0.61262256", "0.6087317", "0.598844", "0.59880143", "0.5920109", "0.5900693", "0.5828325", "0.58246195", "0.5804198", "0.57612586", "0.5741681", "0.5738628", "0.5719216", "0.56939536", "0.56896657", "0.56883...
0.54984707
38
Returns area of a circle
def area(self): return math.pi * self._r ** 2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def circle_area(circle):\n return pi * circle.radius * circle.radius", "def area_of_circle(radius):\n return radius", "def circle_area(radius):\n area = radius ** 2 * math.pi\n return area", "def area(self):\n\t\t#print (self.radius*self.radius*math.pi)\n\t\tcircle_area = (self.radius*self.radius...
[ "0.9091267", "0.8981688", "0.87279946", "0.8713818", "0.8643989", "0.8638605", "0.85790324", "0.8510922", "0.84058666", "0.84058666", "0.8388797", "0.8306146", "0.82901704", "0.8135795", "0.8114081", "0.8105787", "0.8105787", "0.8066629", "0.8049314", "0.8016954", "0.80149436...
0.7715051
29
Alternate constructor using diameter rather than radius
def from_diameter(cls, val): if val < 0: raise ValueError('Diameter must be greater than 0') return cls(val / 2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, radius=1, thickness=1, inner_radius=0):\n\n super().__init__()\n self.radius = radius\n self.inner_radius = inner_radius\n self.thickness = thickness", "def diameter(self, diameter):\n self.radius = diameter / 2", "def __init__(self, radius):\n self....
[ "0.7655539", "0.7464638", "0.71278536", "0.7123325", "0.7113612", "0.71134126", "0.7005773", "0.69776356", "0.68636364", "0.67984104", "0.678745", "0.678745", "0.6740642", "0.6733681", "0.6701746", "0.6677398", "0.6677398", "0.66244286", "0.6590522", "0.6543615", "0.64221567"...
0.67468303
12
Returns the object data in serializable format
def serialize(self): return { 'username': self.username, 'email': self.email, 'joinedDate': self.joinedDate }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def GetDataAsObject(self):", "def serialize(self, obj):\n return obj", "def data(self):\n retval = copy.deepcopy(self.__dict__)\n retval[\"_Serializable_classname\"] = type(self).__name__\n retval[\"_Serializable_version\"] = \"1.0\"\n return retval", "def to_data(self):\n ...
[ "0.7632179", "0.74436677", "0.7407177", "0.7401359", "0.7355684", "0.73262495", "0.7152773", "0.71378213", "0.7084737", "0.70828056", "0.70691866", "0.7051947", "0.7041008", "0.7032165", "0.7026014", "0.701268", "0.70110273", "0.69258404", "0.6858589", "0.68336546", "0.682847...
0.0
-1
Generates an auth token for the given user id.
def generateAuthToken(self): try: payload = { 'exp': datetime.utcnow() + timedelta(days=0, minutes=30), 'iat': datetime.utcnow(), 'sub': self.id } return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256').decode() except Exception as error: print(error) return error
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def token_generate(self, user_id):\n try:\n payload = {\n 'exp': datetime.utcnow() + timedelta(minutes=200),\n 'iat': datetime.utcnow(),\n 'sub': user_id\n }\n encoded_token = jwt.encode(\n payload, current_app.conf...
[ "0.75365555", "0.7299488", "0.71115804", "0.710188", "0.690935", "0.685729", "0.6822128", "0.6820735", "0.68139696", "0.67837673", "0.67776555", "0.6730933", "0.66888976", "0.6683402", "0.6680387", "0.66462904", "0.66453385", "0.65843165", "0.6561365", "0.6530449", "0.6494656...
0.65751797
18
Decodes the auth token
def decodeAuthToken(authToken): try: return jwt.decode(authToken, current_app.config['SECRET_KEY'], algorithm='HS256')['sub'] except jwt.ExpiredSignatureError: return 'signature expired, Please login again' except jwt.InvalidTokenError: return 'Invalid token'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def decode_auth_token(auth_token):\n try:\n payload = jwt.decode(auth_token, Config.SECRET_KEY,algorithms='HS256')\n return payload\n except jwt.ExpiredSignatureError:\n return 'Signature expired. Please log in again.'\n except jwt.InvalidTokenError:\n ...
[ "0.78745645", "0.7660959", "0.76199704", "0.7532894", "0.7487862", "0.7487477", "0.74580514", "0.7387891", "0.73657256", "0.7325584", "0.7293769", "0.72489196", "0.72383934", "0.7121377", "0.7056912", "0.6959151", "0.6953844", "0.69251376", "0.6916667", "0.6878888", "0.686526...
0.7564726
3
Returns the Saved news object data in serializable format
def serialize(self): return { "id": self.id, "headline": self.headline, "url": self.url, "image": self.image, "shortDescription": self.shortDescription, "saved": True, "date": self.date, "savedDate": self.savedDate }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serialized_data(self):\n return {\n 'id': self.id,\n 'start_time': str(self.start_time),\n 'venue_id': self.venue_id,\n 'venue_name': self.venue.name,\n 'venue_image_link': self.venue.image_link,\n 'artist_id': self.artist_id,\n ...
[ "0.67177093", "0.67075676", "0.66094065", "0.6601732", "0.6585369", "0.6565495", "0.6531196", "0.649494", "0.64723766", "0.64716303", "0.64442974", "0.64352673", "0.6431501", "0.64202684", "0.64165074", "0.64140564", "0.64076835", "0.64070576", "0.6395844", "0.6394233", "0.63...
0.6998519
0
This method is responsible for getting the messages to respond with Also covers analytics events for those messages for e.g. click, view
def respond_to_message(self): MessageEventHandler(self.state, self.meta_data, self.message_data).handle_events(events=self.events) data = Converter(self.state).get_messages(meta_data=self.meta_data, message_data=self.message_data) outgoing_messages = data.get("messages", []) events_to_publish = data.get("publish_events", []) agent_messages = [message["message"] for message in outgoing_messages if message["sending_to"] == "AGENT"] user_messages = [message["message"] for message in outgoing_messages if message["sending_to"] == "USER"] agent_response = Util.send_messages(messages=agent_messages, sending_to="AGENT") user_response = Util.send_messages(messages=user_messages, sending_to="USER") if agent_response or user_response: Util.update_state(meta_data=self.meta_data, state=self.state) Util.log_events(meta_data=self.meta_data, state=self.state, events=events_to_publish) return 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_messages(self):\n pass", "def handle_message(self, message):", "def handle_messages():\n print(\"Handling Messages\")\n payload = request.get_data()\n for sender, incoming_message, payload in messaging_events(payload):\n # The following statements check which options the user...
[ "0.64154905", "0.63751894", "0.635842", "0.62978166", "0.6275776", "0.62662673", "0.6228096", "0.6210156", "0.6176662", "0.6156185", "0.6149644", "0.61168385", "0.60755175", "0.6055626", "0.6054083", "0.6031606", "0.6029565", "0.6019241", "0.5985364", "0.5980711", "0.59471154...
0.69531924
0
This method is responsible for responding to events hit on synchronous api
def respond_to_events(self): event_response = MessageEventHandler(self.state, self.meta_data, self.message_data).handle_events(events=self.events) if event_response == []: return {} return event_response[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def run(self):\n current_status = \"Init\"\n while self.expected_status != current_status:\n await asyncio.sleep(1)\n async with aiohttp.ClientSession() as session:\n async with session.get(self.url) as response:\n api_call_result = await ...
[ "0.7191567", "0.6846686", "0.6839081", "0.66729146", "0.66401607", "0.66307336", "0.6543804", "0.64999104", "0.6479456", "0.64707613", "0.64707613", "0.64252007", "0.6379528", "0.6327033", "0.6313674", "0.62806183", "0.6274699", "0.62721395", "0.62186", "0.621285", "0.6212222...
0.0
-1
Commence the update of a vm using the data read from the API
def update(vm_data: Dict[str, Any], span: Span) -> bool: vm_id = vm_data['id'] # Generate the necessary template data child_span = opentracing.tracer.start_span('generate_template_data', child_of=span) template_data = Windows._get_template_data(vm_data, child_span) child_span.finish() # Check that the data was successfully generated if template_data is None: error = f'Failed to retrieve template data for VM #{vm_id}.' Windows.logger.error(error) vm_data['errors'].append(error) span.set_tag('failed_reason', 'template_data_failed') return False # Check that all of the necessary keys are present if not all(template_data[key] is not None for key in Windows.template_keys): missing_keys = [ f'"{key}"' for key in Windows.template_keys if template_data[key] is None ] error_msg = f'Template Data Error, the following keys were missing from the VM update data: ' \ f'{", ".join(missing_keys)}.' Windows.logger.error(error_msg) vm_data['errors'].append(error_msg) span.set_tag('failed_reason', 'template_data_keys_missing') return False # If everything is okay, commence updating the VM host_name = template_data.pop('host_name') # Render the update command child_span = opentracing.tracer.start_span('generate_command', child_of=span) cmd = utils.JINJA_ENV.get_template('vm/hyperv/commands/update.j2').render(**template_data) child_span.finish() # Open a client and run the two necessary commands on the host updated = False try: child_span = opentracing.tracer.start_span('update_vm', child_of=span) response = Windows.deploy(cmd, host_name, child_span) span.set_tag('host', host_name) child_span.finish() except WinRMError as err: error = f'Exception occurred while attempting to update VM #{vm_id} on {host_name}.' Windows.logger.error(error, exc_info=True) vm_data['errors'].append(f'{error} Error: {err}') span.set_tag('failed_reason', 'winrm_error') else: # Check the stdout and stderr for messages if response.std_out: msg = response.std_out.strip() Windows.logger.debug(f'VM update command for VM #{vm_id} generated stdout\n{msg}') updated = 'VM Successfully Updated' in msg # Check if the error was parsed to ensure we're not logging invalid std_err output if response.std_err and '#< CLIXML\r\n' not in response.std_err: msg = response.std_err.strip() Windows.logger.error(f'VM update command for VM #{vm_id} generated stderr\n{msg}') # Check if we need to restart the VM as well if template_data['restart']: # Also render and deploy the restart_cmd template restart_cmd = utils.JINJA_ENV.get_template('vm/hyperv/commands/restart.j2').render(**template_data) # Attempt to execute the restart command Windows.logger.debug(f'Executing restart command for VM #{vm_id}') child_span = opentracing.tracer.start_span('restart_vm', child_of=span) response = Windows.deploy(restart_cmd, host_name, child_span) child_span.finish() if response.std_out: msg = response.std_out.strip() Windows.logger.debug(f'VM restart command for VM #{vm_id} generated stdout\n{msg}') # Check if the error was parsed to ensure we're not logging invalid std_err output if response.std_err and '#< CLIXML\r\n' not in response.std_err: msg = response.std_err.strip() error = f'VM restart command for VM #{vm_id} generated stderr\n{msg}' vm_data['errors'].append(error) Windows.logger.error(error) return updated
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update():\n return 'update api in put'", "def update(self, params):", "def _update_from_rest_data(self) -> None:", "def vm_update(args):\n ip1 = args.ip1\n flavor = args.flavor\n numcpus = args.numcpus\n memory = args.memory\n plan = args.plan\n autostart = args.autostart\n noauto...
[ "0.67325056", "0.65831465", "0.64099467", "0.6401777", "0.6338021", "0.62686175", "0.62686175", "0.62686175", "0.62686175", "0.62159324", "0.62159324", "0.61146724", "0.61023915", "0.60943973", "0.6088066", "0.60478616", "0.60464793", "0.60435563", "0.6035188", "0.6035188", "...
0.6388902
4
Given the vm data from the API, create a dictionary that contains all of the necessary keys for the template The keys will be checked in the update method and not here, this method is only concerned with fetching the data that it can.
def _get_template_data(vm_data: Dict[str, Any], span: Span) -> Optional[Dict[str, Any]]: vm_id = vm_data['id'] Windows.logger.debug(f'Compiling template data for VM #{vm_id}') data: Dict[str, Any] = {key: None for key in Windows.template_keys} data['vm_identifier'] = f'{vm_data["project"]["id"]}_{vm_id}' # changes changes: Dict[str, Any] = { 'ram': False, 'cpu': False, 'storages': False, } updates = vm_data['history'][0] try: if updates['ram_quantity'] is not None: # RAM is needed in MB for the updater but we take it in in GB (1024, not 1000) changes['ram'] = vm_data['ram'] * 1024 except KeyError: pass try: if updates['cpu_quantity'] is not None: changes['cpu'] = vm_data['cpu'] except KeyError: pass # Fetch the drive information for the update try: if len(updates['storage_histories']) != 0: Windows.logger.debug(f'Fetching drives for VM #{vm_id}') child_span = opentracing.tracer.start_span('fetch_drive_updates', child_of=span) changes['storages'] = Windows.fetch_drive_updates(vm_data) child_span.finish() except KeyError: pass # Add changes to data data['changes'] = changes data['storage_type'] = vm_data['storage_type'] data['vms_path'] = settings.HYPERV_VMS_PATH # Get the host name of the server host_name = None for interface in vm_data['server_data']['interfaces']: if interface['enabled'] is True and interface['ip_address'] is not None: if IPAddress(str(interface['ip_address'])).version == 6: host_name = interface['hostname'] break if host_name is None: error = f'Host ip address not found for the server # {vm_data["server_id"]}.' Windows.logger.error(error) vm_data['errors'].append(error) return None # Add the host information to the data data['host_name'] = host_name # Determine restart data['restart'] = vm_data['restart'] return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_template_data(vm_data: Dict[str, Any], span: Span) -> Optional[Dict[str, Any]]:\n vm_id = vm_data['id']\n Windows.logger.debug(f'Compiling template data for VM #{vm_id}')\n data: Dict[str, Any] = {key: None for key in Windows.template_keys}\n\n data['vm_identifier'] = f'{vm_dat...
[ "0.69213694", "0.6188512", "0.6179154", "0.6003007", "0.5900166", "0.58198947", "0.58040434", "0.5778774", "0.5772093", "0.5710987", "0.5700737", "0.56920326", "0.56712186", "0.566643", "0.564755", "0.56175077", "0.56043386", "0.5603194", "0.55743086", "0.5572557", "0.5553227...
0.7405127
0
This updates the view of the hand, between rounds it displays a message.
def update(self, player_index=0, num_players=1, visible_scards = []): self.visible_scards = visible_scards self.controller._state.player_index = player_index if self.num_players > num_players and self.controller._state.rules.Shared_Board \ and not self.need_updated_buttons: # A player has left the game after the round has begun -- make adjustments so game can continue. self.playerLeftGame(num_players) self.num_players = num_players if self.controller._state.round == -1: self.mesgBetweenRounds(self.help_text) if self.round_advance: self.round_index = self.round_index + 1 if self.round_index < len(self.Meld_Threshold): self.help_text[0] = 'This is the round of ' + str(self.Meld_Threshold[self.round_index]) + ' ! ' self.need_updated_buttons = True # used for Liverpool. else: self.help_text = ['Game has concluded. Scores for each round can be found in command window.'] self.round_advance = False else: if not self.round_index == self.controller._state.round: # Need this to true up round_index if a player joins mid-game. skipped_rounds = self.controller._state.round - self.round_index for idx in range(skipped_rounds): #todo: How to score latecomers should be moved to ruleset. score = 0 self.controller.lateJoinScores(score) self.round_index = self.controller._state.round self.round_advance = True # reset outline colors on ready buttons to what they need to be at the start of the "between rounds" state. self.ready_color_idx = 2 self.not_ready_color_idx = 6 self.last_hand = self.current_hand self.current_hand = self.controller.getHand() if len(self.current_hand) == 0: self.hand_info = [] elif not self.last_hand == self.current_hand: self.hand_info = HandManagement.WrapHand(self, self.current_hand, self.hand_info) HandManagement.ShowHolding(self, self.hand_info) # displays hand self.RuleSetsButtons.ButtonDisplay(self)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_display(self):\n self._clear_screen()\n print('Your score is {}'.format(self._roboc.score))\n print(self._roboc.currentmaze)\n print(\"Your viewpoint:\")\n print(self._roboc.get_hidden_game(4))", "def updateChat(self, ):\n self.__redrawChat()", "def viewUpda...
[ "0.60637283", "0.60512704", "0.6037003", "0.6004294", "0.5950593", "0.59421533", "0.59291905", "0.5891295", "0.5876253", "0.58727294", "0.584074", "0.5837629", "0.58247244", "0.58215046", "0.5802971", "0.5793627", "0.57535934", "0.57366675", "0.5722204", "0.5721105", "0.57205...
0.5553602
47
This runs instead of most of nextEvent when Shared_Board is True and there are ambiguous wild cards. It is looking for key strokes to designate ambiguous wild cards in runs. The mouse is ignored until you designate all the wilds (turn phase goes back to play).
def nextEventWildsOnBoard(self): if self.controller._state.rules.Shared_Board and self.num_wilds > 0: for self.event in pygame.event.get(): if self.event.type == pygame.QUIT: # The window crashed, we should handle this print("pygame crash, AAAHHH") pygame.quit() quit() else: # in Shared_Board games, check if there are wilds that need to be updated. # All other events are ignored until play is finished. HandManagement.wildsHiLoGetInput(self)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def nextEvent(self):\n\n if self.controller._state.rules.Shared_Board:\n self.num_wilds = len(self.controller.unassigned_wilds_dict.keys())\n if self.num_wilds > 0:\n self.nextEventWildsOnBoard()\n\n for self.event in pygame.event.get():\n if self.event...
[ "0.7081879", "0.6245746", "0.61995095", "0.61223036", "0.5956481", "0.58805364", "0.5852858", "0.5740237", "0.57229996", "0.57229334", "0.57194364", "0.571404", "0.5688867", "0.56664747", "0.5663727", "0.56603277", "0.56460625", "0.5638092", "0.5631298", "0.5616782", "0.56125...
0.7606982
0
This submits the next user input to the controller, In games with Shared_Board = False (e.g. HandAndFoot) key strokes don't do anything unless designating values for prepared wild cards, at which time the mouse is ignored unless you want to clear the prepared cards. In games with Shared_Board = True wilds on board might change designation upon other cards being played. IF designation cannot be handled automatically (= if wild can be at the beginning or end of a run) then it must be designated before play is completed. This is done in nextEvenWildsOnBoard. All other events are ignored until num_wilds == 0 OR play is canceled.
def nextEvent(self): if self.controller._state.rules.Shared_Board: self.num_wilds = len(self.controller.unassigned_wilds_dict.keys()) if self.num_wilds > 0: self.nextEventWildsOnBoard() for self.event in pygame.event.get(): if self.event.type == pygame.QUIT: # The window crashed, we should handle this print("pygame crash, AAAHHH") pygame.quit() quit() if not self.controller._state.rules.Shared_Board and self.num_wilds > 0: wild_instructions = 'Use the keyboard to designate your prepared wild cards \r\n ' wild_instructions = wild_instructions + '(use 0 for 10 and J, Q, or K for facecards).' self.controller.note = wild_instructions pos = pygame.mouse.get_pos() if self.event.type == pygame.MOUSEBUTTONDOWN: self.RuleSetsButtons.ClickedButton(self, pos) for element in self.hand_info: # cannot select prepared cards, so not included in logic below. if element.img_clickable.isOver(pos): if element.status == 1: element.status = 0 element.img_clickable.changeOutline(0) elif element.status == 0: element.status = 1 element.img_clickable.changeOutline(2) elif self.event.type == pygame.MOUSEMOTION: self.RuleSetsButtons.MouseHiLight(self, pos) HandManagement.MouseHiLight(self.hand_info, pos) elif self.event.type == pygame.KEYDOWN: if self.controller._state.rules.Buy_Option: if self.controller.buying_opportunity: if self.event.key == pygame.K_y: self.controller.wantTopCard(True) self.controller.note = 'You have signaled you want to buy the card.' elif self.event.key == pygame.K_n: self.controller.wantTopCard(False) self.controller.note = 'You have signaled you do not want to buy the card.' if not self.controller._state.rules.Shared_Board and self.num_wilds > 0: HandManagement.ManuallyAssign(self)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def nextEventWildsOnBoard(self):\n\n if self.controller._state.rules.Shared_Board and self.num_wilds > 0:\n for self.event in pygame.event.get():\n if self.event.type == pygame.QUIT:\n # The window crashed, we should handle this\n print(\"pygam...
[ "0.72409004", "0.64886266", "0.6171364", "0.59191036", "0.59139985", "0.5860547", "0.57915825", "0.5791442", "0.5777218", "0.57734597", "0.5769721", "0.5763385", "0.5751395", "0.5743939", "0.5728276", "0.5692042", "0.56845224", "0.5682954", "0.56781256", "0.56780386", "0.5671...
0.6859589
1
gathers selected cards in order to take action on selected cards (either discarding them or preparing them)
def gatherSelected(self): self.selected_list = [] for element in self.hand_info: if element.status == 1: self.selected_list.append(element) return self.selected_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pick(self, pack, cards_owned, draft_info):\n pass", "def card_sel(\n self, num=1, **kwargs\n ): # pylint: disable=too-many-locals, too-many-branches\n selectfrom = self.card_selSource(**kwargs)\n force = kwargs[\"force\"] if \"force\" in kwargs else False\n showdesc = k...
[ "0.6779038", "0.64504594", "0.6393454", "0.6248788", "0.6065166", "0.60555077", "0.60298246", "0.6014514", "0.6014514", "0.5978343", "0.5904059", "0.5888115", "0.5883593", "0.5855397", "0.58428776", "0.584109", "0.5830821", "0.582095", "0.5810005", "0.5807255", "0.5788884", ...
0.5896568
11
Confirm a user is sure about a discard and then perform it once confirmed.
def discardConfirmation(self, confirmed, wrapped_discards): discards = [] for element in wrapped_discards: discards.append(element.card) if self.discards != discards: confirmed = False self.discards = discards if not confirmed: self.controller.note = "Please confirm - discard " + "{0}".format(self.discards) return True # ask for confirmation else: # confirmed is True, performing discard and removing discarded wrapped cards from hand_info. if self.discard_confirm: controller_response = self.controller.discard(self.discards) if controller_response: for element in wrapped_discards: self.hand_info.remove(element) return False # now that this is done, we don't have anything waiting on confirmation
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def confirm_with_abort() -> None:\n\n click.confirm(\n \"Are you sure you want to drop the users table?\",\n abort=True\n )\n\n click.echo(\"We have gotten to this point, so the user has confirmed.\")", "def action_confirm(self):\n self.check_txt_ids()\n self.write({'state': ...
[ "0.6619172", "0.65421534", "0.63608795", "0.6252194", "0.62353194", "0.6222551", "0.61789745", "0.6149395", "0.61379594", "0.6117161", "0.6086858", "0.6077924", "0.6073165", "0.60582376", "0.60207057", "0.60002977", "0.59929824", "0.5937757", "0.593176", "0.59203535", "0.5888...
0.72036105
0
print message where cards usually displayed until Ready button is clicked for next round.
def mesgBetweenRounds(self, message): font = UIC.Medium_Text y_offset = (UIC.Disp_Height * (1 - (UIC.Hand_Row_Fraction * 0.8))) for message_string in message: text_surface = font.render(message_string, True, UIC.Black) text_rect = text_surface.get_rect() text_rect.center = ((UIC.Disp_Width * 0.5), y_offset) y_offset = y_offset + UIC.Medium_Text_Feed self.display.blit(text_surface, text_rect)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def progress_game(self):\r\n\r\n if self.actions == len(self.players):\r\n # Reveal the 3 first cards\r\n output_text = \"Dealing the flop...\"\r\n\r\n self.new_output.emit(output_text)\r\n self.community_cards.flop()\r\n\r\n if self.actions == 2 * len(self...
[ "0.66662335", "0.6361344", "0.6316823", "0.6280809", "0.6178084", "0.6174785", "0.6170106", "0.613654", "0.61161566", "0.61064357", "0.6105633", "0.60992396", "0.6090242", "0.6024819", "0.6020871", "0.5997386", "0.5983832", "0.59802616", "0.59356964", "0.593354", "0.5915386",...
0.0
-1
Test Category model data insertion/types/field attributes
def test_category_model_entry(self): # PRUEBA DE CARGAR LA INFORMACION EN LOS MODELOS A TESTEAR data = self.data1 self.assertTrue(isinstance(data, Category)) # REALIZA EL TESTEO
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_category_model_entry(self):\n data = self.data1\n self.assertTrue(isinstance(data, Category))\n self.assertEqual(str(data), 'django')", "def test_create_category(self):\n pass", "def test_category_has_access_to_model_data():\n category = Category()\n category_data = c...
[ "0.7511274", "0.74611753", "0.7387198", "0.7346792", "0.7272893", "0.721909", "0.6904485", "0.69011027", "0.6842334", "0.67509025", "0.67248386", "0.6717649", "0.6624068", "0.656367", "0.6542668", "0.6540674", "0.65404874", "0.6470544", "0.646362", "0.64630693", "0.64449406",...
0.80247825
0
Test Category model default name
def test_category_model_entry(self): data = self.data1 self.assertEqual(str(data), 'django')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __str__(self):\n return self.category_name", "def test_category_name_label(self):\n\n cat = Category.objects.get(id=1)\n label_name = cat._meta.get_field('name').verbose_name\n self.assertEqual(label_name, 'name')", "def make_test_category(self):\n\n c = Category(slug='te...
[ "0.69887996", "0.69840467", "0.6772042", "0.6648228", "0.6618688", "0.6510455", "0.6509711", "0.6475036", "0.64495313", "0.63525605", "0.6342909", "0.62700176", "0.6242026", "0.6151665", "0.61083674", "0.60542405", "0.6046889", "0.59698623", "0.5938677", "0.5932067", "0.59171...
0.0
-1
Test product model data insertion/types/field attributes
def test_products_model_entry(self): data = self.data1 self.assertTrue(isinstance(data, Product)) self.assertEqual(str(data), 'django beginners')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_product_fields(self):\n\n prd = Product.objects.get(id=1)\n\n # test the type of name field\n prd_type = prd._meta.get_field('name').get_internal_type()\n self.assertEqual(prd_type, 'CharField')\n # label name\n max_length = prd._meta.get_field('name').max_length\...
[ "0.76896816", "0.7435254", "0.74246174", "0.73524946", "0.71989226", "0.7134408", "0.6947085", "0.69248456", "0.68103576", "0.67975587", "0.67713046", "0.67241883", "0.6704033", "0.66982996", "0.6688978", "0.66654783", "0.66048956", "0.659939", "0.6586787", "0.6566571", "0.65...
0.7449101
1
Returns the number of lines of code
def get_line_count(blob): return len(blob.split('\n'))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _getNewCodeLength(self):\n nb_lines = 0\n for line in self.body.splitlines():\n if not line.startswith(\"-\"):\n nb_lines += 1\n return nb_lines", "def _getOldCodeLength(self):\n nb_lines = 0\n for line in self.body.splitlines():\n if not line.startswith(\"+\"):\n nb_li...
[ "0.7965521", "0.7897408", "0.75982934", "0.7581331", "0.74807435", "0.7371733", "0.7250094", "0.7241558", "0.72400385", "0.72222334", "0.7206555", "0.7148526", "0.71233124", "0.709178", "0.7083922", "0.70714384", "0.70620733", "0.70620733", "0.7023198", "0.7015476", "0.701469...
0.68328536
31
Removes docstrings from code
def strip_docstring(blob): docstring = True while docstring == True: match_docstring = re.search('\n\s*"""[^"""]*"""', blob) if not match_docstring: docstring = False else: blob = blob.replace(blob[match_docstring.span()[0]:match_docstring.span()[1]], '') return blob
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def docstring_hack():\n pass", "def main_docstring():", "def undoc(func):\n return func", "def remove_comments_and_docstrings(source):\n io_obj = StringIO(source)\n out = \"\"\n prev_toktype = tokenize.INDENT\n last_lineno = -1\n last_col = 0\n for tok in tokenize.generate_tokens(io_o...
[ "0.7418431", "0.70061356", "0.69807357", "0.697398", "0.692769", "0.6822503", "0.6774257", "0.6732609", "0.66039276", "0.64539397", "0.6381781", "0.63537943", "0.6343105", "0.62978303", "0.6271671", "0.6246473", "0.6230828", "0.6230828", "0.6230828", "0.62265724", "0.6169188"...
0.67054003
8
Strips blank lines from the code
def strip_blanklines(blob): lines = blob.split('\n') return '\n'.join([line for line in lines if line.strip() != ''])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_blank_lines(text):\n out_text = \"\"\n blank = True\n for line in text.splitlines(True):\n if line.isspace():\n if not blank:\n blank = True\n out_text = out_text + line\n else:\n blank = False\n out_text = out_text + ...
[ "0.7114437", "0.70919764", "0.7068101", "0.68381476", "0.6802601", "0.6799396", "0.6789069", "0.66894", "0.66618234", "0.66358346", "0.6598233", "0.6583519", "0.6565634", "0.6527385", "0.6515068", "0.6499719", "0.64757967", "0.64706796", "0.6467208", "0.6441668", "0.6440686",...
0.68966925
3
Strips comments from the code
def strip_comments(blob, delim='#'): lines = blob.split('\n') return '\n'.join([line for line in lines if line.strip()[0] != delim])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _removeComments(code):\r\n # remove all occurance streamed comments (/*COMMENT */) from string\r\n text = re.sub(re.compile('/\\*.*?\\*/', re.DOTALL), '', code)\r\n # remove all occurance singleline comments (//COMMENT\\n ) from string\r\n return re.sub(re.compile('//.*?\\n'), '', t...
[ "0.75588655", "0.75129175", "0.749204", "0.73860633", "0.73546356", "0.7324829", "0.72374445", "0.71416444", "0.711339", "0.6960461", "0.6960461", "0.6952356", "0.6892819", "0.68833077", "0.6868674", "0.6861091", "0.6856785", "0.676051", "0.67446506", "0.6728799", "0.6727674"...
0.6970854
9
Returns the total line count, nonblank line count, and net line count excluding comments and docstrings
def loc(blob, delim='#'): total = get_line_count(blob) blob = strip_blanklines(blob) nonblank = get_line_count(blob) blob = strip_docstring(blob) blob = strip_comments(blob, delim) net = get_line_count(blob) num_inputs = len([m.start() for m in re.finditer('input ?\(', blob)]) return { 'total': total, 'nonblank': nonblank, 'net': net, 'num_inputs': num_inputs}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_line_count(self):\n self.assertEqual(analyze_text(self.filename)[0], 11)", "def test_line_count(self):\n self.assertEqual(analyze_text(self.filename)[0], 4)", "def test_line_count(self):\n self.assertEqual(analyze_text(self.filename)[0], 4)", "def test_line_count(self):\n\t\tsel...
[ "0.7124473", "0.7070284", "0.7070284", "0.70378745", "0.68012744", "0.6775583", "0.6723244", "0.66507286", "0.6617019", "0.6589754", "0.6558442", "0.64918953", "0.6448747", "0.6290716", "0.6276412", "0.62674546", "0.62459767", "0.6210425", "0.61959755", "0.61630034", "0.60748...
0.0
-1
Returns the total, nonblank and net loc for all the python files in a directory
def get_folder_total(path): files = os.listdir(path) pythonfiles = ['%s/%s' % (path, filename) for filename in files if filename[-3:] == '.py'] total = { 'net': 0, 'total': 0, 'nonblank': 0, 'num_inputs':0 } for filename in pythonfiles: with open(filename, 'r') as thisfile: blob = thisfile.read() # print filename thisloc = loc(blob) for k, v in thisloc.items(): total[k] += v return total
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loc():\n file_types = (\n ['Python', 'py', '#']\n )\n\n click.echo('Lines of code\\n-------------')\n\n click.echo(\"{0}: {1}\".format(file_types[0], count_locs(file_types[1],\n file_types[2])))\n\n return None", "def analyze_file...
[ "0.63941246", "0.6148792", "0.5896523", "0.5792946", "0.56846035", "0.5674842", "0.56738776", "0.56557024", "0.5595728", "0.55465335", "0.55265635", "0.5509024", "0.5490125", "0.54562646", "0.53724253", "0.53600603", "0.53305817", "0.5296591", "0.52905095", "0.52354455", "0.5...
0.6992177
0
Returns the total, nonblank and net loc for all the python files in a directory
def get_num_unique_programs_and_users(path, scenarios): unique_programs = set() valid_u_ids = set() for scenario in scenarios: valid_u_ids.add(scenario[0]["UniqueId"]) for filename in glob.iglob(path + 'PythonTutor_Input_Data_Sessions_20*/**/*.py', recursive=True): print(filename) x = filename[filename.rfind('/') + 1:filename.rfind('_')] if x not in valid_u_ids: continue with open(filename, 'r') as thisfile: blob = thisfile.read() unique_programs.add(blob) valid_ips = set() not_valid_ips = set() count = 0 for filename in glob.iglob(path + 'PythonTutor_Input_Data_Sessions_20*/**/*.json', recursive=True): x = filename[filename.rfind('/') + 1:filename.rfind('_a')] if x not in valid_u_ids: continue with open(filename, 'r') as thisfile: blob = json.load(thisfile) if blob["ip"] in not_valid_ips: pass elif blob["ip"] in valid_ips: valid_ips.remove(blob["ip"]) count += 1 not_valid_ips.add(blob["ip"]) else: valid_ips.add(blob["ip"]) print(count) print(len(valid_ips)) return unique_programs
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_folder_total(path):\n files = os.listdir(path)\n pythonfiles = ['%s/%s' % (path, filename) for filename in files if filename[-3:] == '.py']\n total = { 'net': 0, 'total': 0, 'nonblank': 0, 'num_inputs':0 }\n for filename in pythonfiles:\n with open(filename, 'r') as thisfile:\n ...
[ "0.6993405", "0.6395879", "0.614925", "0.5898231", "0.57934844", "0.5683392", "0.56749487", "0.56739736", "0.56560665", "0.559616", "0.55468976", "0.5527279", "0.55094504", "0.5491219", "0.54559195", "0.5373519", "0.5360052", "0.53304", "0.5296416", "0.5291369", "0.5234145", ...
0.0
-1
Just return the version number
def _sendVersion_result (self, (code, data)) : assert code == "REPLY_HELLO" return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def version_number() -> int:\n return 0", "def get_version():\n return '%d.%d.%d' % version_info", "def get_version():\n return 1", "def get_version(self):\r\n\r\n return self.versions[0].number", "def version(self):\n a = re.search('(?<=_V)\\d{1,2}', self.fname)\n if a is Non...
[ "0.8984848", "0.8674616", "0.83636147", "0.82080185", "0.81788445", "0.8116403", "0.81144017", "0.81124747", "0.8100697", "0.79934955", "0.79558516", "0.79138756", "0.790076", "0.78910106", "0.7832687", "0.7817467", "0.7802331", "0.7774403", "0.77695936", "0.77678406", "0.776...
0.0
-1
Get the process status
def queryStatus (self) : return self.sendCommand("CMD_IN_QUERY_STATUS", "")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def status( self ):\n duration = datetime.datetime.now() - self.startTime\n status = {\n 'start': self.startTime.isoformat(),\n 'now': datetime.datetime.now().isoformat(),\n 'duration': duration.total_seconds(),\n 'bookmark': 0,\n 'events': 0,\n ...
[ "0.751286", "0.7507033", "0.71039456", "0.7082734", "0.70624167", "0.7023819", "0.69908047", "0.6980245", "0.69734716", "0.6922125", "0.69144756", "0.69109225", "0.6907264", "0.685191", "0.6851395", "0.68222255", "0.68154085", "0.68061125", "0.6799114", "0.6755627", "0.675542...
0.0
-1
Attempt to start the process
def sendStart (self, args) : data = streamModule.WriteBuffer() data.writeStruct('B', len(args)) for arg in args : data.writeVarLen('B', arg) return self.sendCommand("CMD_IN_DO_START", data.getvalue()).addCallback(self._sendStart_result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Start(self):\n\n\n\n assert not self._process, 'Start() can only be called once'\n self._process = subprocess.Popen(self._args)", "def start(self):\n self._proc = self._get_subprocess()\n self._pid = self._proc.pid\n self._return_code = None", "def start(self):\r\n return ...
[ "0.79140174", "0.7580194", "0.73277956", "0.7258669", "0.724767", "0.7187015", "0.7183471", "0.7030207", "0.7023982", "0.70187926", "0.7007485", "0.69129544", "0.6842755", "0.6826997", "0.68093807", "0.672955", "0.66865253", "0.6634776", "0.6593981", "0.6587125", "0.6586577",...
0.0
-1
Just return the REPLY_SUCCESS
def _sendStart_result (self, (code, data)) : assert code == "REPLY_SUCCESS" return code
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _tunnel_success(tunnel_returncode):\n return tunnel_returncode < 0", "def execute_success(self, *args, **kwargs):\n return 0, self.shell_output, None", "def action_success(self, resp):\n return resp[0] in SUCCESS_CODES", "def action_success(self, resp):\n return resp[0] in SUCCESS...
[ "0.63443524", "0.58786947", "0.58400226", "0.58400226", "0.58263105", "0.58013785", "0.57647425", "0.57602125", "0.5742646", "0.57332826", "0.5728719", "0.5713388", "0.5706354", "0.5559924", "0.5558752", "0.5544535", "0.55265385", "0.55088335", "0.5459527", "0.5437543", "0.54...
0.56434834
13
Send data to the process's stdin
def sendData (self, data) : assert len(data) <= 255 return self.sendCommand("CMD_IN_DATA_STDIN", data).addCallback(self._sendData_result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write( self, data ):\n os.write( self.stdin.fileno(), data )", "def stdin_read(self, data):\n self.write_master(data)", "def send_data(sock):\n while True:\n data = sys.stdin.readline()\n sock.send(data.encode())", "def send_msg(self, msg):\n self.proc.stdin.write(ms...
[ "0.7741889", "0.7658585", "0.76509887", "0.75933856", "0.7503921", "0.7494124", "0.7365971", "0.7141076", "0.7000852", "0.6967747", "0.6881967", "0.68283165", "0.67600954", "0.6745928", "0.6668038", "0.6605815", "0.6481066", "0.64001137", "0.63949114", "0.6270043", "0.6255672...
0.65630895
16
Send a signal to the process
def sendSignal (self, signal) : data = streamModule.WriteBuffer() data.writeStruct('B', signal) return self.sendCommand("CMD_IN_DO_KILL", data.getvalue()).addCallback(self._sendSignal_result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def send_signal(self, sig):\n os.kill(self.pid, sig)", "def send_signal(self, signal):\n self.kill()", "def send_signal(self, sig):\n if self.thread.is_alive():\n self.process.send_signal(sig)\n else:\n lg.warning(\"Couldn't deliver signal \"\n ...
[ "0.83821654", "0.82537395", "0.78793293", "0.7300469", "0.7116897", "0.7112409", "0.7100441", "0.7099212", "0.68905115", "0.6861185", "0.6853869", "0.68038225", "0.67226195", "0.6577294", "0.65427446", "0.65303904", "0.6520947", "0.64594877", "0.6416063", "0.6404712", "0.6392...
0.7512397
3
update self boexes with new frame's boxes
def update(self, new_boxes): if len(self.lengths) > self.n_frames: # delete oldest if exceed capacity del self.boxes[0:self.lengths[0]] del self.lengths[0] self.lengths.append(len(new_boxes)) self.boxes.extend(new_boxes)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def changement_frame(self):\n\n for widget in self.fenetre_scores.winfo_children():\n widget.pack_forget()\n\n for widget in self.fenetre_regles.winfo_children():\n widget.pack_forget()\n\n for widget in self.frame_jeu.winfo_children():\n widget.pack_forget()\n...
[ "0.6689228", "0.66155696", "0.65819746", "0.6271218", "0.6260631", "0.6133513", "0.6128093", "0.611145", "0.60912585", "0.6082675", "0.6053892", "0.6053803", "0.6029776", "0.6003047", "0.596538", "0.5959297", "0.5884809", "0.58832145", "0.5862301", "0.5841208", "0.58308303", ...
0.62919223
3
detect cars on image using historical information and heatmap
def detect(self, img, thresh_hold, show=False): heat = np.zeros_like(img[:,:,0]).astype(np.float) # heatmap for all boxes found in last n_frames frame heat = add_heat(heat,self.boxes) # threshold for multiple frames thresh = thresh_hold*len(self.lengths) # initialization if len(self.lengths) == 0: thresh = thresh_hold heat = apply_threshold(heat,thresh) # Visualize the heatmap when displaying heatmap = np.clip(heat, 0, 255) # Find final boxes from heatmap using label function labels = label(heatmap) draw_img = draw_labeled_bboxes(np.copy(img), labels) if show: plot_dual(draw_img, heatmap,'Car positions','Heat Map',cm2='hot') return draw_img
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_cars(img, scale):\n img_boxes = [] # Clears img_boxes so we don't keep unwanted heatmap history\n count = 0\n draw_img = np.copy(img)\n\n # Make a heatmap of zeros\n heatmap = np.zeros_like(img[:, :, 0])\n\n # IMPORTANT : reading *.jpeg's (scaled 0-255, aka scaling needed), but\n # #...
[ "0.7544776", "0.751789", "0.69776064", "0.68778455", "0.6797643", "0.6754273", "0.6741402", "0.6733516", "0.6707194", "0.669984", "0.66010076", "0.65580624", "0.65305924", "0.6255979", "0.6248127", "0.62139523", "0.6213312", "0.6186227", "0.6084384", "0.6077522", "0.6051025",...
0.6223624
15
pipeline for new frame image
def process_image(self, img): show = False # draw_image = np.copy(img) # search all scale windows and return cars' windows hots = search_scales(img,self.svc, self.X_scaler, self.orient, self.pix_per_cell, self.cell_per_block, self.spatial_size, self.hist_bins) # update the self boxes self.update(hots) # detect cars using threshold window_image = self.detect(img, 2) if show: plt.imshow(window_image) plt.show() return window_image
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run_frame(self, image):\n self.frame_idx += 1\n # run main pipeline\n t0 = datetime.now()\n disp = self.main_pipeline(image)\n t1 = datetime.now()\n logging.info('main pipeline: {}'.format(get_tdiff(t0, t1)))\n \n # prepare image sequence of 3 for trajectory pipeline\n t0 = datetime....
[ "0.70714897", "0.68649685", "0.67296463", "0.6588955", "0.65738624", "0.65543723", "0.65153533", "0.6485808", "0.6470367", "0.6332151", "0.62973356", "0.6296194", "0.62521416", "0.62226206", "0.62107146", "0.62040466", "0.6200719", "0.61632663", "0.6150653", "0.6135857", "0.6...
0.0
-1
Add axes to a subfigure.
def add_axes(self, i, j, rect, **kw): # Get image offset in figure coordinates irev = self.nrows - 1 - i subfig = self.pad + self.image offset = self.margin.bottom_left + irev*subfig.ybox + j*subfig.xbox + self.pad.bottom_left # Convert image rect to figure rect imstart = Box(rect[0], rect[1]) imshape = Box(rect[2], rect[3]) figstart = (offset + imstart * self.image) / self.fig figshape = imshape * self.image / self.fig figrect = [figstart.x, figstart.y, figshape.x, figshape.y] return self.figure.add_axes(figrect, **kw)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_subplot_axes(self, ax, rect, axis_bgcolor=None):\r\n # Modified from\r\n # https://stackoverflow.com/questions/17458580/\r\n box = ax.get_position()\r\n width, height = box.width, box.height\r\n subaxes_box = [(rect[0], rect[1]),\r\n (rect[0] + rect[...
[ "0.75483835", "0.69776756", "0.6920952", "0.6792715", "0.6734505", "0.67272097", "0.6658397", "0.65871996", "0.6570815", "0.6514838", "0.64744306", "0.6344331", "0.6338495", "0.6338495", "0.6338495", "0.6302795", "0.6281416", "0.6270343", "0.6264229", "0.62637293", "0.6255154...
0.6709672
6
Construct quadrilateral mesh arrays from two grids. Intended for use with e.g. plt.pcolor.
def quad_mesh(x, y, cut_x_edges=False, cut_y_edges=False): # Get 1d vertex vectors xvert = get_1d_vertices(x, cut_edges=cut_x_edges) yvert = get_1d_vertices(y, cut_edges=cut_y_edges) # Reshape as multidimensional vectors xvert = reshape_vector(xvert, dim=2, axis=1) yvert = reshape_vector(yvert, dim=2, axis=0) # Broadcast up to arrays xmesh = xvert * np.ones_like(yvert) ymesh = yvert * np.ones_like(xvert) return xmesh, ymesh
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def meshgrid(x,y):\n x = asarray(x)\n y = asarray(y)\n numRows, numCols = len(y), len(x) # yes, reversed\n x = x.reshape(1,numCols)\n X = x.repeat(numRows, axis=0)\n\n y = y.reshape(numRows,1)\n Y = y.repeat(numCols, axis=1)\n return X, Y", "def make_meshgrid(x, y, h=.02):\r\n x_min, ...
[ "0.72705615", "0.6971521", "0.6954679", "0.694505", "0.694505", "0.6930976", "0.6930976", "0.6930976", "0.6930976", "0.6908422", "0.6903842", "0.69015664", "0.6880629", "0.6800234", "0.6800234", "0.6661612", "0.6625001", "0.66245806", "0.63171464", "0.62140924", "0.6175486", ...
0.56618655
43
Get vertices dividing a 1d grid.
def get_1d_vertices(grid, cut_edges=False): if len(grid.shape) > 1: raise ValueError("grid must be 1d array.") diff = np.diff(grid) vert = np.zeros(grid.size+1) # Interior vertices: halfway between points vert[1:-1] = grid[0:-1] + diff/2 # Edge vertices: tight or reflect if cut_edges: vert[0] = grid[0] vert[-1] = grid[-1] else: vert[0] = grid[0] - diff[0]/2 vert[-1] = grid[-1] + diff[-1]/2 return vert
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def vertices(self):\n try:\n return self._vertices\n except:\n self._vertices = [list(x) for x in self.vertex_generator()]\n return self._vertices", "def vertices(self):\n\n if self._faces is None:\n if self._vertices is None:\n retu...
[ "0.6591957", "0.65517676", "0.6523746", "0.6520511", "0.64833", "0.64833", "0.64218307", "0.6383808", "0.6376488", "0.63350326", "0.6328131", "0.63177186", "0.6316762", "0.6278034", "0.6251261", "0.6179584", "0.61629945", "0.6152223", "0.61260945", "0.6122966", "0.6108887", ...
0.76482964
0
Compute padded image limits for x and y grids.
def pad_limits(xgrid, ygrid, xpad=0., ypad=0., square=None): xmin, xmax = xgrid.min(), xgrid.max() ymin, ymax = ygrid.min(), ygrid.max() dx = xmax - xmin dy = ymax - ymin x0 = xmin - xpad*dx x1 = xmax + xpad*dx y0 = ymin - ypad*dy y1 = ymax + ypad*dy if square: axis = square ax_position = axis.get_position() ax_height = ax_position.height * axis.figure.get_figheight() ax_width = ax_position.width * axis.figure.get_figwidth() ax_aspect = ax_height / ax_width im_height = y1 - y0 im_width = x1 - x0 im_aspect = im_height / im_width if (im_height/im_width) > (ax_height/ax_width): # Image too tall extra_w = im_height/ax_aspect - im_width x0 -= extra_w / 2 x1 += extra_w / 2 else: # Image too wide extra_h = im_width*ax_aspect - im_height y0 -= extra_h / 2 y1 += extra_h / 2 return [x0, x1, y0, y1]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_image_bounds(pixel_meter_size, frame, beam_width_data, additional_pixel_padding_x=0, additional_pixel_padding_y=0):\n\n # Compute the projected locations of all samples so that we can get the extent\n all_bl = []\n all_br = []\n all_fr = []\n all_fl = []\n\n for beam_num in [0, frame....
[ "0.6500194", "0.6199433", "0.6105291", "0.60281", "0.59161913", "0.5894251", "0.585068", "0.58396924", "0.5810349", "0.5791982", "0.57880354", "0.5763434", "0.57571024", "0.57165116", "0.57111406", "0.5668063", "0.56606424", "0.565698", "0.56563175", "0.5641682", "0.5641682",...
0.7511422
0
Select plane from dataset. Intended for use with e.g. plt.pcolor.
def get_plane(dset, xaxis, yaxis, slices, **kw): # Build quad meshes from sorted grids xgrid = dset.dims[xaxis][0][indices[xaxis]] ygrid = dset.dims[yaxis][0][indices[yaxis]] xorder = np.argsort(xgrid) yorder = np.argsort(ygrid) xmesh, ymesh = quad_mesh(xgrid[xorder], ygrid[yorder], **kw) # Select and arrange data data = dset[slices] if xi < yi: data = data.T data = data[yorder] data = data[:, xorder] return xmesh, ymesh, data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def GetPlane(plane):\r\n pass", "def plane(self):\n return plane(self.N, self.o)", "def get_plane(self, scalar, plane, pval):\n\n if plane == 'yz' or plane == 'zy':\n # z along rows, y along columns\n return scalar[:, pval, :]\n elif plane == 'xz' or plane == '...
[ "0.63480055", "0.62466025", "0.6210041", "0.6181447", "0.60752785", "0.59501004", "0.5885949", "0.5844385", "0.5806675", "0.57641417", "0.5717144", "0.5657449", "0.5650415", "0.5615462", "0.5605463", "0.55464685", "0.55369604", "0.5516311", "0.5514092", "0.5510669", "0.551001...
0.5889004
6
Identity function for string extraction.
def _(x): return x
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def intern(string): # real signature unknown; restored from __doc__\n return \"\"", "def identity_tokenizer(text):\n return text", "def identity( arg ):\n return arg", "def identification(self):\n return remove_whitespace(self.str_without_type())", "def test_identity(self):\n\n s = r...
[ "0.6034306", "0.5799975", "0.5765744", "0.57460624", "0.5699749", "0.5639867", "0.5598918", "0.5493786", "0.5481133", "0.54755294", "0.54505527", "0.5449481", "0.5441116", "0.5371032", "0.5352636", "0.5330441", "0.5291735", "0.5242051", "0.52288747", "0.52288747", "0.52288747...
0.0
-1
Generate a object formatter for links..
def link(text, link_func): def object_formatter(v, c, m, p): """Format object view link.""" return Markup('<a href="{0}">{1}</a>'.format( link_func(m), text)) return object_formatter
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def object_formatter(v, c, m, p):\n return Markup('<a href=\"{0}\">{1}</a>'.format(\n link_func(m), text))", "def __repr__(self):\n if self.rest:\n rest_repr = ', ' + repr(self.rest)\n else:\n rest_repr = ''\n return 'Link({0}{1})'.format(self.first, r...
[ "0.784745", "0.6504912", "0.64552146", "0.6426217", "0.62232155", "0.6217698", "0.60861593", "0.60861593", "0.60610193", "0.60496616", "0.5940354", "0.59321237", "0.5914688", "0.58717525", "0.5870953", "0.5845969", "0.5824419", "0.58027077", "0.57641745", "0.57560444", "0.573...
0.72780514
1
Format object view link.
def object_formatter(v, c, m, p): return Markup('<a href="{0}">{1}</a>'.format( link_func(m), text))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def link(text, link_func):\n def object_formatter(v, c, m, p):\n \"\"\"Format object view link.\"\"\"\n return Markup('<a href=\"{0}\">{1}</a>'.format(\n link_func(m), text))\n return object_formatter", "def link(self, obj):\n return format_html(\n '<a href=\"{url...
[ "0.73224676", "0.7216829", "0.7124374", "0.68019325", "0.65847546", "0.64726907", "0.64016116", "0.63936055", "0.6361755", "0.635381", "0.63412184", "0.63111347", "0.6248648", "0.6244252", "0.61723745", "0.61185104", "0.6079688", "0.6079688", "0.60349536", "0.6026926", "0.601...
0.75110674
0