content
stringlengths
22
815k
id
int64
0
4.91M
def create_border_mask(input_data, target, max_dist, background_label,axis=0): """ Overlay a border mask with background_label onto input data. A pixel is part of a border if one of its 4-neighbors has different label. Parameters ---------- input_data : h5py.Dataset or numpy.ndarray - Input data containing neuron ids target : h5py.Datset or numpy.ndarray - Target which input data overlayed with border mask is written into. max_dist : int or float - Maximum distance from border for pixels to be included into the mask. background_label : int - Border mask will be overlayed using this label. axis : int - Axis of iteration (perpendicular to 2d images for which mask will be generated) """ sl = [slice(None) for d in xrange(len(target.shape))] for z in xrange(target.shape[axis]): sl[ axis ] = z border = create_border_mask_2d(input_data[tuple(sl)], max_dist) target_slice = input_data[tuple(sl)] if isinstance(input_data,h5py.Dataset) else np.copy(input_data[tuple(sl)]) target_slice[border] = background_label target[tuple(sl)] = target_slice
25,000
def femda_estimator(X, labels, eps = 1e-5, max_iter = 20): """ Estimates the matrix of means and the tensor of scatter matrix of the dataset using MLE estimator. To tackle singular matrix issues, we use regularization. Parameters ---------- X : 2-d array of size n*m matrix of all the samples generated labels : 1-d array of size n vector of the label of each sample eps : float > 0 criterion of termination when solving the fixed-point equation max_iter : integer > 1 number of maximum iterations to solve the fixed-point equation Returns ------- means : 2-d array of size K*m matrix of the robust estimation of the mean of the K clusters shapes : 3-d array of size K*m*m tensor of the robust estimation of shape matrix of the K clusters """ n, m = X.shape K = int(max(set(labels)) + 1) n_clusters = np.zeros(K) + 1e-5 for i in range(n): n_clusters[int(labels[i])] = n_clusters[int(labels[i])] + 1 means, shapes = classic_estimator(X, labels) for k in range(K): convergence = False ite = 1 while (not convergence) and ite<max_iter: ite = ite + 1 mean = np.zeros(m) shape = np.zeros([m,m]) sum_mean_weights = 1e-5 for i in range(n): if labels[i] == k: mean_weight = min([[0.5]], 1 / np.dot(np.array([X[i]-means[k]]), np.dot(np.linalg.inv(regularize(shapes[k])), np.array([X[i]-means[k]]).T)))[0][0] #print(mean_weight) mean = mean + mean_weight * X[i] sum_mean_weights = sum_mean_weights + mean_weight shape = shape + np.dot(np.array([X[i]-means[k]]).T, np.array([X[i]-means[k]])) * mean_weight delta_mean = mean / sum_mean_weights - means[k] delta_shape = shape * m / n_clusters[k] - shapes[k] means[k] = means[k] + delta_mean shapes[k] = shapes[k] + delta_shape print("trace at", ite, np.trace(shapes[k])) convergence = sum(abs(delta_mean)) + sum(sum(abs(delta_shape))) < eps shapes[k] = regularize(shapes[k]) return means, shapes
25,001
def get_collections(): """read .db file, return raw collection""" col = {} f = open(collection_db, "rb") version = nextint(f) ncol = nextint(f) for i in range(ncol): colname = nextstr(f) col[colname] = [] for j in range(nextint(f)): f.read(2) col[colname].append(f.read(32).decode("utf-8")) f.close() return (col, version)
25,002
def ot_has_small_bandgap(cp2k_input, cp2k_output, bandgap_thr_ev): """ Returns True if the calculation used OT and had a smaller bandgap then the guess needed for the OT. (NOTE: It has been observed also negative bandgap with OT in CP2K!) cp2k_input: dict cp2k_output: dict bandgap_thr_ev: float [eV] """ list_true = [True, 'T', 't', '.TRUE.', 'True', 'true'] #add more? try: ot_settings = cp2k_input['FORCE_EVAL']['DFT']['SCF']['OT'] if '_' not in ot_settings.keys() or ot_settings['_'] in list_true: #pylint: disable=simplifiable-if-statement using_ot = True else: using_ot = False except KeyError: using_ot = False min_bandgap_ev = min(cp2k_output["bandgap_spin1_au"], cp2k_output["bandgap_spin2_au"]) * HARTREE2EV is_bandgap_small = (min_bandgap_ev < bandgap_thr_ev) return using_ot and is_bandgap_small
25,003
def _run(top_narr_dir_name, top_front_line_dir_name, top_wpc_bulletin_dir_name, first_time_string, last_time_string, pressure_level_mb, thermal_field_name, thermal_colour_map_name, max_thermal_prctile_for_colours, first_letter_label, letter_interval, output_dir_name): """Plots predictors on full NARR grid. This is effectively the main method. :param top_narr_dir_name: See documentation at top of file. :param top_front_line_dir_name: Same. :param top_wpc_bulletin_dir_name: Same. :param first_time_string: Same. :param last_time_string: Same. :param pressure_level_mb: Same. :param thermal_field_name: Same. :param thermal_colour_map_name: Same. :param max_thermal_prctile_for_colours: Same. :param first_letter_label: Same. :param letter_interval: Same. :param output_dir_name: Same. :raises: ValueError: if `thermal_field_name not in VALID_THERMAL_FIELD_NAMES`. """ # Check input args. if top_wpc_bulletin_dir_name in ['', 'None']: top_wpc_bulletin_dir_name = None if first_letter_label in ['', 'None']: first_letter_label = None if thermal_field_name not in VALID_THERMAL_FIELD_NAMES: error_string = ( '\n{0:s}\nValid thermal fields (listed above) do not include ' '"{1:s}".' ).format(str(VALID_THERMAL_FIELD_NAMES), thermal_field_name) raise ValueError(error_string) thermal_colour_map_object = pyplot.cm.get_cmap(thermal_colour_map_name) file_system_utils.mkdir_recursive_if_necessary( directory_name=output_dir_name) first_time_unix_sec = time_conversion.string_to_unix_sec( first_time_string, DEFAULT_TIME_FORMAT) last_time_unix_sec = time_conversion.string_to_unix_sec( last_time_string, DEFAULT_TIME_FORMAT) valid_times_unix_sec = time_periods.range_and_interval_to_list( start_time_unix_sec=first_time_unix_sec, end_time_unix_sec=last_time_unix_sec, time_interval_sec=NARR_TIME_INTERVAL_SEC, include_endpoint=True) # Read metadata for NARR grid. narr_latitude_matrix_deg, narr_longitude_matrix_deg = ( nwp_model_utils.get_latlng_grid_point_matrices( model_name=nwp_model_utils.NARR_MODEL_NAME) ) narr_rotation_cos_matrix, narr_rotation_sin_matrix = ( nwp_model_utils.get_wind_rotation_angles( latitudes_deg=narr_latitude_matrix_deg, longitudes_deg=narr_longitude_matrix_deg, model_name=nwp_model_utils.NARR_MODEL_NAME) ) narr_row_limits, narr_column_limits = ( nwp_plotting.latlng_limits_to_rowcol_limits( min_latitude_deg=MIN_LATITUDE_DEG, max_latitude_deg=MAX_LATITUDE_DEG, min_longitude_deg=MIN_LONGITUDE_DEG, max_longitude_deg=MAX_LONGITUDE_DEG, model_name=nwp_model_utils.NARR_MODEL_NAME) ) narr_rotation_cos_matrix = narr_rotation_cos_matrix[ narr_row_limits[0]:(narr_row_limits[1] + 1), narr_column_limits[0]:(narr_column_limits[1] + 1) ] narr_rotation_sin_matrix = narr_rotation_sin_matrix[ narr_row_limits[0]:(narr_row_limits[1] + 1), narr_column_limits[0]:(narr_column_limits[1] + 1) ] # Do plotting. narr_field_names = [ processed_narr_io.U_WIND_GRID_RELATIVE_NAME, processed_narr_io.V_WIND_GRID_RELATIVE_NAME, thermal_field_name ] this_letter_label = None for this_time_unix_sec in valid_times_unix_sec: this_file_name = fronts_io.find_file_for_one_time( top_directory_name=top_front_line_dir_name, file_type=fronts_io.POLYLINE_FILE_TYPE, valid_time_unix_sec=this_time_unix_sec) print 'Reading data from: "{0:s}"...'.format(this_file_name) this_polyline_table = fronts_io.read_polylines_from_file(this_file_name) if top_wpc_bulletin_dir_name is None: this_high_low_table = None else: this_file_name = wpc_bulletin_io.find_file( top_directory_name=top_wpc_bulletin_dir_name, valid_time_unix_sec=this_time_unix_sec) print 'Reading data from: "{0:s}"...'.format(this_file_name) this_high_low_table = wpc_bulletin_io.read_highs_and_lows( this_file_name) this_predictor_matrix = None for this_field_name in narr_field_names: this_file_name = processed_narr_io.find_file_for_one_time( top_directory_name=top_narr_dir_name, field_name=this_field_name, pressure_level_mb=pressure_level_mb, valid_time_unix_sec=this_time_unix_sec) print 'Reading data from: "{0:s}"...'.format(this_file_name) this_field_matrix = processed_narr_io.read_fields_from_file( this_file_name )[0][0, ...] this_field_matrix = utils.fill_nans(this_field_matrix) this_field_matrix = this_field_matrix[ narr_row_limits[0]:(narr_row_limits[1] + 1), narr_column_limits[0]:(narr_column_limits[1] + 1) ] if this_field_name in [processed_narr_io.TEMPERATURE_NAME, processed_narr_io.WET_BULB_THETA_NAME]: this_field_matrix -= ZERO_CELSIUS_IN_KELVINS if this_field_name == processed_narr_io.SPECIFIC_HUMIDITY_NAME: this_field_matrix = this_field_matrix * KG_TO_GRAMS this_field_matrix = numpy.expand_dims(this_field_matrix, axis=-1) if this_predictor_matrix is None: this_predictor_matrix = this_field_matrix + 0. else: this_predictor_matrix = numpy.concatenate( (this_predictor_matrix, this_field_matrix), axis=-1) u_wind_index = narr_field_names.index( processed_narr_io.U_WIND_GRID_RELATIVE_NAME) v_wind_index = narr_field_names.index( processed_narr_io.V_WIND_GRID_RELATIVE_NAME) (this_predictor_matrix[..., u_wind_index], this_predictor_matrix[..., v_wind_index] ) = nwp_model_utils.rotate_winds_to_earth_relative( u_winds_grid_relative_m_s01=this_predictor_matrix[ ..., u_wind_index], v_winds_grid_relative_m_s01=this_predictor_matrix[ ..., v_wind_index], rotation_angle_cosines=narr_rotation_cos_matrix, rotation_angle_sines=narr_rotation_sin_matrix) this_title_string = time_conversion.unix_sec_to_string( this_time_unix_sec, NICE_TIME_FORMAT) if pressure_level_mb == 1013: this_title_string += ' at surface' else: this_title_string += ' at {0:d} mb'.format(pressure_level_mb) this_default_time_string = time_conversion.unix_sec_to_string( this_time_unix_sec, DEFAULT_TIME_FORMAT) this_output_file_name = '{0:s}/predictors_{1:s}.jpg'.format( output_dir_name, this_default_time_string) if first_letter_label is not None: if this_letter_label is None: this_letter_label = first_letter_label else: this_letter_label = chr( ord(this_letter_label) + letter_interval ) _plot_one_time( predictor_matrix=this_predictor_matrix, predictor_names=narr_field_names, front_polyline_table=this_polyline_table, high_low_table=this_high_low_table, thermal_colour_map_object=thermal_colour_map_object, max_thermal_prctile_for_colours=max_thermal_prctile_for_colours, narr_row_limits=narr_row_limits, narr_column_limits=narr_column_limits, title_string=this_title_string, letter_label=this_letter_label, output_file_name=this_output_file_name) print '\n'
25,004
def fuzz_and_reduce_bug( active_device: str, seed: int, check_result: Callable[[], None], settings: Optional[Settings] = None, ignored_signatures: Optional[List[str]] = None, ) -> None: """ Fuzz, find a bug, reduce it. Linux only. """ # Test only works on Linux. if util.get_platform() != "Linux": return here = util.norm_path(Path(__file__).absolute()).parent temp_dir: Path = here.parent / "temp" assert temp_dir.is_dir() os.chdir(temp_dir) # Create ROOT file in temp/ if needed. fuzz.try_get_root_file() work_dir = temp_dir / fuzz.get_random_name()[:8] util.mkdir_p_new(work_dir) os.chdir(work_dir) log(f"Changed to {str(work_dir)}") if settings is None: settings = Settings() settings.CopyFrom(settings_util.DEFAULT_SETTINGS) settings.device_list.CopyFrom( DeviceList( active_device_names=[active_device], devices=[ Device( name="amdllpc", shader_compiler=DeviceShaderCompiler( binary="amdllpc", args=["-gfxip=9.0.0", "-verify-ir", "-auto-layout-desc"], ), binaries=[ Binary( name="amdllpc", tags=["Release"], version="c21d76dceaf26361f9b6b3838a955ec3301506b5", ), ], ), Device( name="swift_shader", swift_shader=DeviceSwiftShader(), binaries=[ Binary( name="swift_shader_icd", tags=["Release"], version="6d69aae0e1ab49190ea46cd1c999fd3d02e016b9", ), ], ignored_crash_signatures=ignored_signatures, ), ], ) ) spirv_tools_version = "983b5b4fccea17cab053de24d51403efb4829158" settings.latest_binary_versions.extend( [ Binary( name="glslangValidator", tags=["Release"], version="1afa2b8cc57b92c6b769eb44a6854510b6921a0b", ), Binary(name="spirv-opt", tags=["Release"], version=spirv_tools_version), Binary(name="spirv-dis", tags=["Release"], version=spirv_tools_version), Binary(name="spirv-as", tags=["Release"], version=spirv_tools_version), Binary(name="spirv-val", tags=["Release"], version=spirv_tools_version), Binary(name="spirv-fuzz", tags=["Release"], version=spirv_tools_version), Binary(name="spirv-reduce", tags=["Release"], version=spirv_tools_version), Binary( name="graphicsfuzz-tool", tags=[], version="7b143bcb3ad38b64ddc17d132886636b229b6684", ), ] ) # Add default binaries; the ones above have priority. settings.latest_binary_versions.extend(binaries_util.DEFAULT_BINARIES) settings.extra_graphics_fuzz_generate_args.append("--small") settings.extra_graphics_fuzz_generate_args.append("--single-pass") settings.extra_graphics_fuzz_reduce_args.append("--max-steps") settings.extra_graphics_fuzz_reduce_args.append("2") settings_util.write(settings, settings_util.DEFAULT_SETTINGS_FILE_PATH) # Add shaders. binary_manager = binaries_util.get_default_binary_manager(settings) graphicsfuzz_tool = binary_manager.get_binary_path_by_name("graphicsfuzz-tool") sample_shaders_path: Path = graphicsfuzz_tool.path.parent.parent.parent / "shaders" / "samples" / "310es" util.copy_dir(sample_shaders_path, Path() / fuzz.REFERENCES_DIR) util.copy_dir(sample_shaders_path, Path() / fuzz.DONORS_DIR) fuzz.main_helper( settings_path=settings_util.DEFAULT_SETTINGS_FILE_PATH, iteration_seed_override=seed, override_sigint=False, use_amber_vulkan_loader=True, ) check_result() os.chdir(here) shutil.rmtree(work_dir)
25,005
def test_generate_ticket(user): """Test a ticket from a valid user and a spam bot.""" ticket = generate_ticket(user) assert ticket == user.expected_output
25,006
def profile(): """Checking if user is already logged_in""" if 'logged_in' in session: '''getting all the account info for the user for displaying it on the profile page''' cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = %s', (session['employee_uname'],)) account = cursor.fetchone() '''Showing profile page with account info to the employee''' return render_template('profile.html', acc=account) '''if User is not logged_in redirect to login page''' return redirect(url_for('login'))
25,007
def gather_metrics(config, worker_output, endpoint_output, container_names): """Process the raw output to lists of dicts Args: config (dict): Parsed configuration worker_output (list(list(str))): Output of each container ran on the edge endpoint_output (list(list(str))): Output of each endpoint container container_names (list(str)): Names of docker containers launched Returns: 2x list(dict): Metrics of worker nodes and endpoints """ logging.debug('Print raw output from subscribers and publishers') if config['mode'] == 'cloud' or config['mode'] == 'edge': logging.debug('------------------------------------') logging.debug('%s OUTPUT' % (config['mode'].upper())) logging.debug('------------------------------------') for out in worker_output: for line in out: logging.debug(line) logging.debug('------------------------------------') logging.debug('------------------------------------') logging.debug('ENDPOINT OUTPUT') logging.debug('------------------------------------') for out in endpoint_output: for line in out: logging.debug(line) logging.debug('------------------------------------') worker_metrics = gather_worker_metrics(worker_output) endpoint_metrics = gather_endpoint_metrics(config, endpoint_output, container_names) return worker_metrics, endpoint_metrics
25,008
async def ping(ws): """Send a ping request on an established websocket connection. :param ws: an established websocket connection :return: the ping response """ ping_request = { 'emit': "ping", 'payload': { 'timestamp': int(time.time()) } } await ws.send(json.dumps(ping_request)) return json.loads(await ws.recv())
25,009
def split_files_each_proc(file_arr,nprocs): """ Returns array that distributes samples across all processors. """ ntot = len(file_arr) post_proc_file_arr = [] for i in range(0,nprocs): each_proc_arr = [] ib,ie = split_array_old(ntot,nprocs,i) if i == 0: max_no = (ie-ib)+1 for j in range(ib,ie+1): each_proc_arr.append(j) if len(each_proc_arr) > max_no: max_no = len(each_proc_arr) elif len(each_proc_arr) < max_no : for k in range(0,max_no-(len(each_proc_arr))): each_proc_arr.append("no file") max_no = len(each_proc_arr) post_proc_file_arr.append(each_proc_arr) return post_proc_file_arr
25,010
def get_data_generators_for_output(output): """ Get the data generators involved in an output Args: output (:obj:`Output`): report or plot Returns: :obj:`set` of :obj:`DataGenerator`: data generators involved in the output """ data_generators = set() if isinstance(output, Report): for data_set in output.data_sets: data_generators.add(data_set.data_generator) elif isinstance(output, Plot2D): for curve in output.curves: data_generators.add(curve.x_data_generator) data_generators.add(curve.y_data_generator) elif isinstance(output, Plot3D): for surface in output.surfaces: data_generators.add(surface.x_data_generator) data_generators.add(surface.y_data_generator) data_generators.add(surface.z_data_generator) else: raise NotImplementedError('Output of type {} is not supported.'.format(output.__class__.__name__)) if None in data_generators: data_generators.remove(None) return data_generators
25,011
def MarkovChainFunction(data, bins): """ Data should be numpy array; bins is an integer """ #Normalize data datMin = min(data) datMax = max(data) datNorm = (data - datMin)/(datMax - datMin) # Create Markov Transition Table: mesh = np.linspace(0, 1, bins) meshReal = (mesh*(datMax - datMin) + datMin) dmesh = mesh[1] - mesh[0] dmeshReal = meshReal[1] - meshReal[0] markovArray = np.zeros((len(mesh), len(mesh))) cumMarkovArray = np.zeros((len(mesh), len(mesh))) # Populate Markov Transition Table: for i in range(1,(len(data)-1)): datNow = datNorm[i] datBefore = datNorm[i-1] dn = np.floor(datNow / dmesh) # Get index....TODO: DO WE NOT WANT TO ROUND DOWN**? Ask Aaron db = np.floor(datBefore / dmesh) # Get index markovArray[int(db), int(dn)] = markovArray[int(db), int(dn)] + 1; #Update MTT # Transform data in transition table to probability: markovArray = markovArray/np.sum(markovArray, axis=1, keepdims = True) #? from https://stackoverflow.com/questions/16202348/numpy-divide-row-by-row-sum cumMarkovArray = np.cumsum(markovArray, axis=1) # Eliminate potential NaNs from potential /0: ind = np.isnan(markovArray) markovArray[ind] = 0 cumMarkovArray[ind] = 0 return markovArray, cumMarkovArray, datMin, datMax, dmeshReal
25,012
def clustering_report(y_true, y_pred) -> pd.DataFrame: """ Generate cluster evaluation metrics. Args: y_true: Array of actual labels y_pred: Array of predicted clusters Returns: Pandas DataFrame with metrics. """ return pd.DataFrame( { "Homogeneity": M.homogeneity_score(y_true, y_pred), "Completeness": M.completeness_score(y_true, y_pred), "V-Measure": M.v_measure_score(y_true, y_pred), "Adjusted Rand Index": M.adjusted_rand_score(y_true, y_pred), "Adjusted Mutual Information": M.adjusted_mutual_info_score(y_true, y_pred), }, index=["value"], ).T
25,013
def _create_sampler_data( datastores: List[Datastore], variables: Sequence[Variable], preconditions: Set[LiftedAtom], add_effects: Set[LiftedAtom], delete_effects: Set[LiftedAtom], param_option: ParameterizedOption, datastore_idx: int ) -> Tuple[List[SamplerDatapoint], List[SamplerDatapoint]]: """Generate positive and negative data for training a sampler.""" # Populate all positive data. positive_data: List[SamplerDatapoint] = [] for (segment, var_to_obj) in datastores[datastore_idx]: option = segment.get_option() state = segment.states[0] if CFG.sampler_learning_use_goals: # Right now, we're making the assumption that all data is # demonstration data when we're learning samplers with goals. # In the future, we may weaken this assumption. goal = segment.get_goal() else: goal = None assert all( pre.predicate.holds(state, [var_to_obj[v] for v in pre.variables]) for pre in preconditions) positive_data.append((state, var_to_obj, option, goal)) # Populate all negative data. negative_data: List[SamplerDatapoint] = [] if CFG.sampler_disable_classifier: # If we disable the classifier, then we never provide # negative examples, so that it always outputs 1. return positive_data, negative_data for idx, datastore in enumerate(datastores): for (segment, var_to_obj) in datastore: option = segment.get_option() state = segment.states[0] if CFG.sampler_learning_use_goals: # Right now, we're making the assumption that all data is # demonstration data when we're learning samplers with goals. # In the future, we may weaken this assumption. goal = segment.get_goal() else: goal = None trans_add_effects = segment.add_effects trans_delete_effects = segment.delete_effects if option.parent != param_option: continue var_types = [var.type for var in variables] objects = list(state) for grounding in utils.get_object_combinations(objects, var_types): if len(negative_data ) >= CFG.sampler_learning_max_negative_data: # If we already have more negative examples # than the maximum specified in the config, # we don't add any more negative examples. return positive_data, negative_data # If we are currently at the datastore that we're learning a # sampler for, and this datapoint matches the positive # grounding, this was already added to the positive data, so # we can continue. if idx == datastore_idx: positive_grounding = [var_to_obj[var] for var in variables] if grounding == positive_grounding: continue sub = dict(zip(variables, grounding)) # When building data for a datastore with effects X, if we # encounter a transition with effects Y, and if Y is a superset # of X, then we do not want to include the transition as a # negative example, because if Y was achieved, then X was also # achieved. So for now, we just filter out such examples. ground_add_effects = {e.ground(sub) for e in add_effects} ground_delete_effects = {e.ground(sub) for e in delete_effects} if ground_add_effects.issubset(trans_add_effects) and \ ground_delete_effects.issubset(trans_delete_effects): continue # Add this datapoint to the negative data. negative_data.append((state, sub, option, goal)) return positive_data, negative_data
25,014
def call_assign_job(job_id, mex_id): """ Function to send an update to the MEx Sentinel to assign a Job to an MEx. """ try: rospy.wait_for_service('/mex_sentinel/assign_job_to_mex', rospy.Duration(1)) try: assign_job = rospy.ServiceProxy('mex_sentinel/assign_job_to_mex', AssignJobToMex) req = AssignJobToMexRequest() req.job_id = job_id req.mex_id = mex_id result = assign_job(req) return result except rospy.ServiceException as e: print(NAME + "Service call failed: %s"%e) except rospy.ROSException: pass
25,015
def full( coords, nodata=np.nan, dtype=np.float32, name=None, attrs={}, crs=None, lazy=False ): """Return a full DataArray based on a geospatial coords dictionary. Arguments --------- coords: sequence or dict of array_like, optional Coordinates (tick labels) to use for indexing along each dimension (max 3). The coordinate sequence should be (dim0, y, x) of which the first is optional. nodata: float, int, optional Fill value for new DataArray, defaults to other.nodata or if not set np.nan dtype: numpy.dtype, optional Data type name: str, optional DataArray name attrs : dict, optional additional attributes crs: int, dict, or str, optional Coordinate Reference System. Accepts EPSG codes (int or str); proj (str or dict) lazy: bool, optional If True return DataArray with a dask rather than numpy array. Returns ------- da: DataArray Filled DataArray """ f = dask.array.empty if lazy else np.full dims = tuple([d for d in coords]) shape = tuple([coords[dim].size for dim in dims]) data = f(shape, nodata, dtype=dtype) da = xr.DataArray(data, coords, dims, name, attrs) da.raster.set_nodata(nodata) da.raster.set_crs(crs) return da
25,016
def calculate_alignment( sequences, mode, matrix, gapopen, gapextend, hash=uuid4().hex): """ 1 - remove modifications 2 - convert sequence 3 - muscle - msa 4 - revert sequences 5 - add original modifications """ new_file_lines = [] for i, element in enumerate(sequences): name, sequence, structure = element unmodified_sequence = remove_modifications(sequence) converted_sequence = convert_sequence( unmodified_sequence, structure, mode) new_file_lines.append('>{}'.format(str(i))) new_file_lines.append('{}'.format(converted_sequence)) new_file_content = "\n".join(new_file_lines) temp_name_in = os.path.join( os.getcwd(), 'temp_1_{}'.format(hash)) temp_name_out = os.path.join( os.getcwd(), 'temp_2_{}'.format(hash)) with open(temp_name_in, 'w') as f: f.write(new_file_content) command = 'muscle -in {} -out {} -matrix {} -gapopen {} ' \ '-gapextend {} -center 0.0'.format( temp_name_in, temp_name_out, matrix, gapopen, gapextend) os.system(command) new_sequences = [] with open(temp_name_out, 'r') as f: counter = 0 name = None sequence = '' for line in f.readlines(): if line.startswith('>'): if counter != 0 and len(line.strip()) > 0: my_id = int(name.replace('>', '')) original_sequence = sequences[my_id][1] original_name = sequences[my_id][0] new_sequence, new_structure = revert_sequence( sequence, original_sequence, mode) new_sequence = add_original_modifications( new_sequence, original_sequence) new_sequences.append( (original_name, new_sequence, new_structure)) sequence = '' name = line.strip() else: sequence += line.strip() counter += 1 my_id = int(name.replace('>', '')) original_sequence = sequences[my_id][1] original_name = sequences[my_id][0] new_sequence, new_structure = revert_sequence( sequence, original_sequence, mode) new_sequence = add_original_modifications( new_sequence, original_sequence) new_sequences.append((original_name, new_sequence, new_structure)) os.remove(temp_name_in) os.remove(temp_name_out) return new_sequences
25,017
def add_weight_decay( model: nn.Module, weight_decay: float = 1e-5, skip_list: Union[List, Tuple] = () ) -> List[Dict]: """Helper function to not decay weights in BatchNorm layers Source: https://discuss.pytorch.org/t/weight-decay-in-the-optimizers-is-a-bad-idea-especially-with-batchnorm/16994/3 """ decay = [] no_decay = [] for name, param in model.named_parameters(): if not param.requires_grad: continue if len(param.shape) == 1 or name in skip_list: no_decay.append(param) else: decay.append(param) return [ {"params": no_decay, "weight_decay": 0.0}, {"params": decay, "weight_decay": weight_decay}, ]
25,018
def find_bands_hdu(hdu_list, hdu): """Discover the extension name of the BANDS HDU. Parameters ---------- hdu_list : `~astropy.io.fits.HDUList` hdu : `~astropy.io.fits.BinTableHDU` or `~astropy.io.fits.ImageHDU` Returns ------- hduname : str Extension name of the BANDS HDU. None if no BANDS HDU was found. """ if "BANDSHDU" in hdu.header: return hdu.header["BANDSHDU"] has_cube_data = False if ( isinstance(hdu, (fits.ImageHDU, fits.PrimaryHDU)) and hdu.header.get("NAXIS", None) == 3 ): has_cube_data = True elif isinstance(hdu, fits.BinTableHDU): if ( hdu.header.get("INDXSCHM", "") in ["EXPLICIT", "IMPLICIT", ""] and len(hdu.columns) > 1 ): has_cube_data = True if has_cube_data: if "EBOUNDS" in hdu_list: return "EBOUNDS" elif "ENERGIES" in hdu_list: return "ENERGIES" return None
25,019
def read_raw_binary_file(file_path): """can actually be any file""" with open(file_path, 'rb') as f: return f.read()
25,020
def encode_cl_value(entity: CLValue) -> dict: """Encodes a CL value. """ def _encode_parsed(type_info: CLType) -> str: if type_info.typeof in TYPES_NUMERIC: return str(int(entity.parsed)) elif type_info.typeof == CLTypeKey.BYTE_ARRAY: return entity.parsed.hex() elif type_info.typeof == CLTypeKey.PUBLIC_KEY: return entity.parsed.account_key.hex() elif type_info.typeof == CLTypeKey.UREF: return entity.parsed.as_string() elif type_info.typeof == CLTypeKey.OPTION: return _encode_parsed(type_info.inner_type) else: return str(entity.parsed) return { "bytes": serialisation.to_bytes(entity).hex(), "cl_type": encode_cl_type(entity.cl_type), "parsed": _encode_parsed(entity.cl_type), }
25,021
def escape(string): """ Escape a passed string so that we can send it to the regular expressions engine. """ ret = None def replfunc(m): if ( m[0] == "\\" ): return("\\\\\\\\") else: return("\\\\" + m[0]) # @note - I had an issue getting replfunc to be called in # javascript correctly when I didn't use this pragma # not sure if I was just doing it wrong or what __pragma__( 'js', '{}', ''' var r = /[^A-Za-z:;\d]/g; ret = string.replace(r, replfunc); ''') if ( ret is not None ): return(ret) else: raise Exception("Failed to escape the passed string")
25,022
def batch_apply(fn, inputs): """Folds time into the batch dimension, runs fn() and unfolds the result. Args: fn: Function that takes as input the n tensors of the tf.nest structure, with shape [time*batch, <remaining shape>], and returns a tf.nest structure of batched tensors. inputs: tf.nest structure of n [time, batch, <remaining shape>] tensors. Returns: tf.nest structure of [time, batch, <fn output shape>]. Structure is determined by the output of fn. """ time_to_batch_fn = lambda t: tf.reshape(t, [-1] + t.shape[2:].as_list()) batched = tf.nest.map_structure(time_to_batch_fn, inputs) output = fn(*batched) prefix = [int(tf.nest.flatten(inputs)[0].shape[0]), -1] batch_to_time_fn = lambda t: tf.reshape(t, prefix + t.shape[1:].as_list()) return tf.nest.map_structure(batch_to_time_fn, output)
25,023
def grab_haul_list(creep: Creep, roomName, totalStructures, add_storage=False): """ μœ„μ— ν—ˆμšΈλŸ¬κ°€ μ—λ„ˆμ§€λ₯Ό μ±„μšΈ λͺ©λ‘ 확인. :param creep: :param roomName: 방이름. :param totalStructures: λ³Έλ¬Έ all_structures 와 동일 :param add_storage: μŠ€ν† λ¦¬μ§€λ₯Ό 포함할 것인가? priority == 0 인 상황 μ•„λ‹ˆλ©΄ 포함할일이 μ—†μŒ. :return: ν—ˆμšΈλŸ¬μ˜ μ—λ„ˆμ§€ μ±„μšΈ λŒ€μƒλͺ©λ‘ """ # defining structures to fill the energy on. originally above of this spot but replaced for cpu eff. # towers only fills 80% since it's gonna repair here and there all the time. structures = totalStructures.filter(lambda s: ((s.structureType == STRUCTURE_SPAWN or s.structureType == STRUCTURE_EXTENSION) and s.energy < s.energyCapacity) or (s.structureType == STRUCTURE_TOWER and s.energy < s.energyCapacity * 0.8) or (s.structureType == STRUCTURE_TERMINAL and s.store[RESOURCE_ENERGY] < 10000)) # μŠ€ν† λ¦¬μ§€μ— 넣을 양이 μžˆμ„λ•Œ μΆ”κ°€ν•˜λŠ”κ±°μž„. # κΈ°μ€€: μŠ€ν† λ¦¬μ§€μ— 남은 양이 max_energy κ°’ 이상일 경우 # λ³€κ²½: μŠ€ν† λ¦¬μ§€μ— 남은 양이 μžˆλŠ” 경우 if add_storage: structures.extend(totalStructures.filter (lambda s: s.structureType == STRUCTURE_STORAGE # and s.storeCapacity - _.sum(s.store) >= Game.rooms[roomName].memory.structure_type[max_energy])) and s.storeCapacity - _.sum(s.store) > 0)) # 핡에 μ—λ„ˆμ§€ λ„£λŠ”κ±Έλ‘œ 함? if Memory.rooms[roomName].options and Memory.rooms[roomName].options.fill_nuke: nuke_structure_add = totalStructures.filter(lambda s: s.structureType == STRUCTURE_NUKER and s.energy < s.energyCapacity) structures.extend(nuke_structure_add) # μ—°κ΅¬μ†Œμ— μ—λ„ˆμ§€ λ„£λŠ”κ±Έλ‘œ 함? if Memory.rooms[roomName].options and Memory.rooms[roomName].options.fill_labs: structure_add = totalStructures \ .filter(lambda s: s.structureType == STRUCTURE_LAB and s.energy < s.energyCapacity) structures.extend(structure_add) container = [] # for_upgrade :μŠ€ν† λ¦¬μ§€κ°€ μ»¨νŠΈλ‘€λŸ¬μ—μ„œ 많이 λ–¨μ–΄μ Έ μžˆμ„λ•Œ λŒ€λΉ„ν•΄ λ‘λŠ” μ»¨ν…Œμ΄λ„ˆ. # λ ™ 8μ΄ν•˜μ— μ—λ„ˆμ§€κ°€ μžˆμ„λ•Œλ§Œ μ°ΎλŠ”λ‹€ if Game.rooms[roomName].controller.level < 8 and creep.store.getCapacity(RESOURCE_ENERGY): for rcont in Game.rooms[roomName].memory[STRUCTURE_CONTAINER]: cont_obj = Game.getObjectById(rcont.id) if not cont_obj: continue # μ—…κΈ€μš© μ»¨ν…Œμ΄λ„ˆκ³  μˆ˜ν™•μ €μž₯μš©λ„κ°€ μ•„λ‹Œκ°€? 그러면 ν—ˆμšΈλŸ¬κ°€ λ„£λŠ”λ‹€. 2/3 μ΄ν•˜λ‘œ μ°¨μžˆμ„λ•Œλ§Œ. if rcont.for_upgrade and not rcont.for_harvest \ and cont_obj.store.getUsedCapacity() < cont_obj.store.getCapacity() * 2 / 3: # 단, μŠ€ν† λ¦¬μ§€λ₯Ό λ§Œλ“€ λ ™(4이상)이고 μŠ€ν† λ¦¬μ§€κ°€ μ—†μœΌλ©΄ μ•ˆλ„£λŠ”λ‹€. # λ°© λ‚΄ μ—λ„ˆμ§€κ°€ μ•ˆ μ°Όμ„λ•Œλ„ 톡과 if 4 <= creep.room.controller.level \ and not Game.getObjectById(creep.memory.upgrade_target).room.storage \ or creep.room.energyAvailable < creep.room.energyCapacityAvailable * .95: continue container.append(Game.getObjectById(rcont.id)) structures.extend(container) return structures
25,024
def data_static(filename): """ Get files :param filename: :return: """ _p, _f = os.path.split(filename) # print(_p, _f) return flask.send_from_directory(os.path.join(config['path']['path_data'], _p), _f)
25,025
def target(x, seed, instance): """A target function for dummy testing of TA perform x^2 for easy result calculations in checks. """ # Return x[i] (with brackets) so we pass the value, not the # np array element return x[0] ** 2, {'key': seed, 'instance': instance}
25,026
def generate(fspec, count, _fuel=None): """Generate <count> number of random passwords/passphrases. The passphrases are formated according to <fspec>. Returned value is (list, json_data), where list is a <count>-element sequence of pair of (password, reading hint for password). json_data is a dict at least containing the following keys: key 'diag': (str) message for diagnostics, key 'entropy': (float) estimated entropy of generated passphrases, key 'elements': list of sequences of elements of generated passphrases. Raises BadFormatError if fspec is either bad or not able to be satisfied. """ diag = [] fspec, entropy = _parse_fspec(fspec, diag=diag, _fuel=_fuel) if count < 1: raise BadFormatError('bad count of passwords specified') fspec, entropy = _resolve_entropy(fspec, entropy, diag=diag, _fuel=_fuel) elements = [] result = [] for ncount in range(count): o = [] def elem(e, f, o, h, c=None, ct=1): d = {'entropy': e, 'separator': f, 'password': o, 'hint': h} if c != None: d['corpus_source'] = str(c) if not f: d['repeat_count'] = ct return d def proc(filling, i, sep, wl, ct): initial = not filling and i == 0 e1 = wl.entropy() if wl.is_words: intersep = sep if sep != None else " " presep = "" if initial else sep if sep != None else " " for c in range(0, ct): w = wl.get_randomly() s = presep if c == 0 else intersep sh = " " if (s == "" and c != 0) else s if sh: o.append(elem(0.0, True, s, sh, None)) o.append(elem(e1, False, w.word, w.hint, wl)) else: if ct != 0: intersep = "" presep = "" if initial else sep if presep: o.append(elem(0.0, True, presep, presep, None)) ow = [] oh = [] for c in range(0, ct): w = wl.get_randomly() ow.append(w.word) oh.append(w.hint) o.append(elem(ct * e1, False, "".join(ow), "".join(oh), wl, ct=ct)) for i, s in enumerate(fspec): proc(False, i, *s) o_word = "".join(x['password'] for x in o) o_hint = "".join(x['hint'] for x in o) elements.append(o) result.append((o_word, o_hint)) return result, {'passwords': result, 'elements': elements, 'diag': "\n".join(diag), 'entropy': entropy}
25,027
def convert_to_valid_einsum_chars(einsum_str): """Convert the str ``einsum_str`` to contain only the alphabetic characters valid for numpy einsum. """ # partition into valid and invalid sets valid, invalid = set(), set() for x in einsum_str: (valid if is_valid_einsum_char(x) else invalid).add(x) # get replacements for invalid chars that are not already used available = gen_unused_symbols(valid, len(invalid)) # map invalid to available and replace in the inputs replacer = dict(zip(invalid, available)) return "".join(replacer.get(x, x) for x in einsum_str)
25,028
def prop_GAC(csp, newVar=None): """ Do GAC propagation. If newVar is None we do initial GAC enforce processing all constraints. Otherwise we do GAC enforce with constraints containing newVar on GAC Queue """ constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons() pruned = [] # NOTE: although <constraints> is a list, the order is unimportant and acts like a set. # See page 209 of RN textbook while constraints != []: constraint = constraints.pop(0) # grab the first constraint for var in constraint.get_unasgn_vars(): # get_scope()? for val in var.cur_domain(): if not constraint.has_support(var, val): # Check if we have already pruned (var, val) if (var, val) not in pruned: var.prune_value(val) pruned.append((var, val)) # We have modified var's domain, so add back all constraints # that have var in it's scope for c in csp.get_cons_with_var(var): if c not in constraints: constraints.append(c) # Check if var's domain is empty if var.cur_domain_size() == 0: return False, pruned return True, pruned
25,029
def clone( # pylint: disable=R0913,R0912,R0914 source, target, branch="main", depth=None, delete_git_dir=False, username=None, password=None, key_filename=None, key_data=None, track_branch_upstream=True, ): """ Clone repository """ # Prepare auth args auth_args = dict() if username is not None: auth_args["username"] = username if password is not None: auth_args["password"] = password if key_filename is not None: auth_args["key_filename"] = key_filename if key_data is not None: key_obj = io.StringIO(key_data.replace("|", "\n")) pkey = paramiko.RSAKey.from_private_key(key_obj) auth_args["key_filename"] = pkey # Clone repository log.info("Cloning repository %s into %s", source, target) repository = porcelain.clone( source, target, checkout=False, depth=depth, errstream=log.DebugLogStream(), **auth_args ) # Get current HEAD tree (default branch) try: head_tree = repository[b"HEAD"] except: # pylint: disable=W0702 head_tree = None # Get target tree (requested branch) branch_b = branch.encode("utf-8") try: target_tree = repository[b"refs/remotes/origin/" + branch_b] except: # pylint: disable=W0702 target_tree = None # Checkout branch branch_to_track = None if target_tree is not None: log.info("Checking out branch %s", branch) repository[b"refs/heads/" + branch_b] = repository[b"refs/remotes/origin/" + branch_b] repository.refs.set_symbolic_ref(b"HEAD", b"refs/heads/" + branch_b) repository.reset_index(repository[b"HEAD"].tree) # branch_to_track = branch elif head_tree is not None: try: default_branch_name = repository.refs.follow(b"HEAD")[0][1] if default_branch_name.startswith(refs.LOCAL_BRANCH_PREFIX): default_branch_name = default_branch_name[len(refs.LOCAL_BRANCH_PREFIX):] default_branch_name = default_branch_name.decode("utf-8") # log.warning( "Branch %s was not found. Checking out default branch %s", branch, default_branch_name ) # branch_to_track = default_branch_name except: # pylint: disable=W0702 log.warning("Branch %s was not found. Trying to check out default branch", branch) # try: repository.reset_index(repository[b"HEAD"].tree) except: # pylint: disable=W0702 log.exception("Failed to checkout default branch") else: log.error("Branch %s was not found and default branch is not set. Skipping checkout") # Add remote tracking if track_branch_upstream and branch_to_track is not None: log.info("Setting '%s' to track upstream branch", branch_to_track) # branch_to_track_b = branch_to_track.encode("utf-8") # config = repository.get_config() config.set( (b"branch", branch_to_track_b), b"remote", b"origin", ) config.set( (b"branch", branch_to_track_b), b"merge", b"refs/heads/" + branch_to_track_b, ) config.write_to_path() # Delete .git if requested if delete_git_dir: log.info("Deleting .git directory") shutil.rmtree(os.path.join(target, ".git")) # Return repo object return repository
25,030
def submit_only_kwargs(kwargs): """Strip out kwargs that are not used in submit""" kwargs = kwargs.copy() for key in ['patience', 'min_freq', 'max_freq', 'validation', "max_epochs", "epoch_boost", "train_size", "valid_size"]: _ = kwargs.pop(key, None) return kwargs
25,031
def make_simple_boundary(outline_edge_group: UniqueEdgeList, all_edges: UniqueEdgeList): """ Step 3 recursive :param outline_edge_group: A list of edges, grouped by connectivity between edges. :param all_edges: :return: ??? """ while len(all_edges.edge_list) > 0: current_edge = all_edges.edge_list[0] work = False neighbors = all_edges.get_neighbor_indices_for_edge(current_edge) # Loop against all neighboring edges, gobble up the neighbors. for neighbor in neighbors: neighbor_edge = all_edges.edge_list[neighbor] if not Edge.same_edge(current_edge, neighbor_edge): shared_vertex = Edge.has_shared_vertex(current_edge, neighbor_edge) parallel = Edge.are_parallel_or_anti_parallel(current_edge, neighbor_edge) if shared_vertex is not None and parallel: # Case 1. start_vertex = [neighbor_edge.x1, neighbor_edge.y1, neighbor_edge.z1] # Case 2. if (neighbor_edge.x1 == shared_vertex[0] and neighbor_edge.y1 == shared_vertex[1] and neighbor_edge.z1 == shared_vertex[2]): start_vertex = [neighbor_edge.x2, neighbor_edge.y2, neighbor_edge.z2] # Case 3. end_vertex = [current_edge.x1, current_edge.y1, current_edge.z1] # Case 4. if (current_edge.x1 == shared_vertex[0] and current_edge.y1 == shared_vertex[1] and current_edge.z1 == shared_vertex[2]): end_vertex = [current_edge.x2, current_edge.y2, current_edge.z2] new_edge = Edge(start_vertex[0], start_vertex[1], start_vertex[2], # Edge Start end_vertex[0], end_vertex[1], end_vertex[2]) # Edge end all_edges.remove(current_edge) all_edges.remove(neighbor_edge) all_edges.add(new_edge) work = True break if not work and len(all_edges.edge_list) > 0: outline_edge_group.add(current_edge) all_edges.remove(current_edge) return outline_edge_group
25,032
def convert_rscape_svg_to_one_line(rscape_svg, destination): """ Convert R-scape SVG into SVG with 1 line per element. """ output = os.path.join(destination, 'rscape-one-line.svg') cmd = (r"perl -0777 -pe 's/\n +fill/ fill/g' {rscape_svg} | " r"perl -0777 -pe 's/\n d=/ d=/g' | " r"perl -0777 -pe 's/\n +<tspan/ <tspan/g' | " r"perl -0777 -pe 's/\n<\/text>/<\/text>/g' " r"> {output}").format(rscape_svg=rscape_svg, output=output) os.system(cmd) return output
25,033
def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs): """ Download Digitized Sky Survey images https://archive.stsci.edu/cgi-bin/dss_form https://archive.stsci.edu/cgi-bin/dss_search Image is in celestial orientation (RA increases to the right) https://archive.stsci.edu/dss/script_usage.html ra (r) - right ascension dec (d) - declination equinox (e) - equinox (B1950 or J2000; default: J2000) height (h) - height of image (arcminutes; default: 15.0) width (w) - width of image (arcminutes; default: 15.0) format (f) - image format (FITS or GIF; default: FITS) compression (c) - compression (UNIX, GZIP, or NONE; default: NONE; compression applies to FITS only) version (v) - Which version of the survey to use: 1 - First Generation survey (garden variety) 2 - Second generation survey (incomplete) 3 - Check the 2nd generation; if no image is available, then go to the 1st generation. 4 - The Quick V survey (whence came the Guide Stars Catalog; used mostly for Phase II proposal submission) save (s) - Save the file to disk instead of trying to display. (ON (or anything) or not defined; default: not defined.) """ import subprocess import tempfile url="https://archive.stsci.edu/cgi-bin/dss_search?" scale = 2.0 * radius * 60. params=dict(ra='%.3f'%ra,dec='%.3f'%dec,width=scale,height=scale, format='gif',version=1) #v='poss2ukstu_red' query='&'.join("%s=%s"%(k,v) for k,v in params.items()) tmp = tempfile.NamedTemporaryFile(suffix='.gif') cmd='wget --progress=dot:mega -O %s "%s"'%(tmp.name,url+query) subprocess.call(cmd,shell=True) im = pylab.imread(tmp.name) tmp.close() if xsize: im = scipy.misc.imresize(im,size=(xsize,xsize)) return im
25,034
async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" job = HassJob(action) if config[CONF_TYPE] == "turn_on": entity_id = config[CONF_ENTITY_ID] @callback def _handle_event(event: Event): if event.data[ATTR_ENTITY_ID] == entity_id: hass.async_run_hass_job( job, {"trigger": {**config, "description": f"{DOMAIN} - {entity_id}"}}, event.context, ) return hass.bus.async_listen(EVENT_TURN_ON, _handle_event) return lambda: None
25,035
def imread(image_path, as_uint8=True): """Read an image as numpy array. Args: image_path (str or pathlib.Path): File path (including extension) to read image. as_uint8 (bool): Read an image in uint8 format. Returns: :class:`numpy.ndarray`: Image array of dtype uint8, MxNx3. Examples: >>> from tiatoolbox import utils >>> img = utils.misc.imread('ImagePath.jpg') """ if isinstance(image_path, pathlib.Path): image_path = str(image_path) if pathlib.Path(image_path).suffix == ".npy": image = np.load(image_path) else: image = cv2.imread(image_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if as_uint8: return image.astype(np.uint8) return image
25,036
async def _update_listener(opp: OpenPeerPower, entry: ConfigEntry): """Handle options update.""" await opp.config_entries.async_reload(entry.entry_id)
25,037
def pk(obj): """ A helper that gets the primary key of a model instance if one is passed in. If not, this returns the parameter itself. This allows functions to have parameters that accept either a primary key or model instance. For example: ``` python def get_translations(target_locale): return Translation.objects.filter(target_locale=pk(target_locale)) # Both of these would be valid calls get_translations(Locale.objects.get(id=1)) get_translations(1) ``` Args: obj (Model | any): A model instance or primary key value. Returns: any: The primary key of the model instance, or value of `obj` parameter. """ if isinstance(obj, models.Model): return obj.pk else: return obj
25,038
def auto_link(elements: Iterable[Gst.Element]): """ Automatically link a *linear* Iterable of elements together (no tees or other branching). note: Won't link sometimes/request pads (for now), but link() could be patched to so. If you want to submit a PR, this would be a welcome addition. Warning: it's not an easy task, with a lot of edge cases. :arg elements: an Iterable of Gst.Element to link together :raises: LinkError if a link fails """ prev = None for element in elements: # type: Gst.Element if prev is not None: link(prev, element) prev = element
25,039
def get_dataset(id): """Query for existence of dataset by ID.""" uu = UrlUtils() es_url = uu.rest_url #es_index = "{}_{}_s1-ifg".format(uu.grq_index_prefix, version) es_index = "grq" # query query = { "query": { "wildcard": { "_id": id } } } logger.info(query) if es_url.endswith('/'): search_url = '%s%s/_search' % (es_url, es_index) else: search_url = '%s/%s/_search' % (es_url, es_index) logger.info("search_url : %s" %search_url) r = requests.post(search_url, data=json.dumps(query)) if r.status_code != 200: logger.info("Failed to query %s:\n%s" % (es_url, r.text)) logger.info("query: %s" % json.dumps(query, indent=2)) logger.info("returned: %s" % r.text) r.raise_for_status() result = r.json() logger.info(result['hits']['total']) return result
25,040
def bags_with_gold( parents_of, _ ): """ Starting from leaf = 'gold', find recursively its parents upto the root and add them to a set Number of bags that could contain gold = length of the set """ contains_gold = set() def find_roots( bag ): for outer_bag in parents_of[ bag ]: contains_gold.add( outer_bag ) find_roots( outer_bag ) find_roots('shiny gold') return len(contains_gold)
25,041
def buildCon(filter, testhost): """Load the config file and build the connections, then check connecting to the testHost if defined """ global adc adc.setFilter(filter) adc.collectInstanceData() adc.loadConfig() adc.buildConnections(debug=True) if ( testhost is not None): found = False for host in adc.getHosts(running=True): if host.name == testhost: found = True try: adc.log.info("Listing containers on host({})".format(testhost)) adc.listContainers(host.connection) except IndexError: adc.log.error("No connection created for host {}",format(testhost)) break if not found: adc.log.error("Host {} is not known".format(testhost))
25,042
def send_mail(sending_email, sending_password, list_emails, subject, html_file): """ Send a mail to a list of emails. The body is an html formated file template. """ # Creating the server, and handling all connections steps server = smtplib.SMTP('smtp.gmail.com', 587) server.connect("smtp.gmail.com",587) server.ehlo() server.starttls() server.ehlo() server.login(sending_email, sending_password) # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sending_email with open(html_file, 'r') as myfile: html_data = myfile.read() # Adding the html core template html_email = MIMEText(html_data, 'html') msg.attach(html_email) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. for email in list_emails : msg['To'] = email server.sendmail(sending_email, email, msg.as_string()) server.quit()
25,043
def test_director_exception(): """Test handling of an exception raised in a director. """ db = setup_database() query = xapian.Query('it') enq = xapian.Enquire(db) enq.set_query(query) class TestException(Exception): def __init__(self, a, b): Exception.__init__(self, a + b) rset = xapian.RSet() rset.add_document(1) class EDecider(xapian.ExpandDecider): def __call__(self, term): raise TestException("foo", "bar") edecider = EDecider() expect_exception(TestException, "foobar", edecider, "foo") expect_exception(TestException, "foobar", enq.get_eset, 10, rset, edecider) class MDecider(xapian.MatchDecider): def __call__(self, doc): raise TestException("foo", "bar") mdecider = MDecider() expect_exception(TestException, "foobar", mdecider, xapian.Document()) expect_exception(TestException, "foobar", enq.get_mset, 0, 10, None, mdecider)
25,044
def create(project, schema, roles): """Create system DB schema, if not exists.""" engine, _ = project_engine(project) DB.ensure_schema_exists(engine, schema, grant_roles=roles)
25,045
def process_file(file_path): """ This function processes the submitted file :return: A dictionary of errors found in the file. If there are no errors, then only the error report headers will in the results. """ enc = detect_bom_encoding(file_path) if enc is None: with open(file_path, 'r') as f: result = run_checks(file_path, f) else: with open(file_path, 'r', encoding=enc) as f: result = run_checks(file_path, f) print('Finished processing %s\n' % file_path) return result
25,046
def setup_package(): """Setup the environment for testing diff_local.""" global TEST_WORKSPACE TEST_WORKSPACE = env.get_workspace('diff_local') # Set the TEST_WORKSPACE used by the tests. os.environ['TEST_WORKSPACE'] = TEST_WORKSPACE test_config = {} test_project = 'cpp' project_info = project.get_info(test_project) # Copy the test project to the workspace. The tests should # work only on this test project. test_proj_path_base = os.path.join(TEST_WORKSPACE, "test_proj_base") shutil.copytree(project.path(test_project), test_proj_path_base) # Copy the test project to the workspace. The tests should # work only on this test project. test_proj_path_new = os.path.join(TEST_WORKSPACE, "test_proj_new") shutil.copytree(project.path(test_project), test_proj_path_new) project_info['project_path_base'] = test_proj_path_base project_info['project_path_new'] = test_proj_path_new test_config['test_project'] = project_info # Suppress file should be set here if needed by the tests. suppress_file = None # Skip list file should be set here if needed by the tests. skip_list_file = None # Get an environment which should be used by the tests. test_env = env.test_env(TEST_WORKSPACE) # Create a basic CodeChecker config for the tests, this should # be imported by the tests and they should only depend on these # configuration options. codechecker_cfg = { 'suppress_file': suppress_file, 'skip_list_file': skip_list_file, 'check_env': test_env, 'workspace': TEST_WORKSPACE, 'checkers': [] } # Base analysis codechecker_cfg['reportdir'] = os.path.join(test_proj_path_base, 'reports') codechecker_cfg['checkers'] = ['-e', 'core.CallAndMessage', '-d', 'core.NullDereference'] ret = codechecker.log_and_analyze(codechecker_cfg, test_proj_path_base) if ret: sys.exit(1) # New analysis codechecker_cfg['reportdir'] = os.path.join(test_proj_path_new, 'reports') codechecker_cfg['checkers'] = ['-d', 'core.CallAndMessage', '-e', 'core.NullDereference'] ret = codechecker.log_and_analyze(codechecker_cfg, test_proj_path_new) if ret: sys.exit(1) codechecker_cfg['reportdir_base'] = os.path.join(test_proj_path_base, 'reports') codechecker_cfg['reportdir_new'] = os.path.join(test_proj_path_new, 'reports') test_config['codechecker_cfg'] = codechecker_cfg # Export the test configuration to the workspace. env.export_test_cfg(TEST_WORKSPACE, test_config)
25,047
def get_request_body(text, api_key, *args): """ send a request and return the response body parsed as dictionary @param text: target text that you want to detect its language @type text: str @type api_key: str @param api_key: your private API key """ if not api_key: raise Exception("you need to get an API_KEY for this to work. " "Get one for free here: https://detectlanguage.com/documentation") if not text: raise Exception("Please provide an input text") else: try: headers = config['headers'] headers['Authorization'] = headers['Authorization'].format(api_key) response = requests.post(config['url'], json={'q': text}, headers=headers) body = response.json().get('data') return body except HTTPError as e: print("Error occured while requesting from server: ", e.args) raise e
25,048
def generate_sample_task(project): """ Generate task example for upload and check it with serializer validation :param project: project with label config :return: task dict """ task = generate_sample_task_without_check(project.label_config) # check generated task '''if project: try: TaskSerializer.check_data(project, task) except ValidationError as e: raise ValidationError(str(e) + ': task example = ' + json.dumps(task) + ', project config = ' + project.label_config + ', project data_types = ' + json.dumps(project.data_types))''' return task
25,049
def entry_point(): """Basic entrypoint for cortex subcommands""" pass
25,050
async def test_sensor_registry( hass, mqtt_client_mock, mqtt_mock, mock_phoniebox, config ): """Test that a new sensor is created""" entity_registry = er.async_get(hass) er_items_before = er.async_entries_for_config_entry( entity_registry, mock_phoniebox.entry_id ) async_fire_mqtt_message(hass, "test_phoniebox/attribute/version", MOCK_VERSION) await hass.async_block_till_done() er_items_after = er.async_entries_for_config_entry( entity_registry, mock_phoniebox.entry_id ) assert len(er_items_after) == len(er_items_before) + 1 # now added the sensor entry: RegistryEntry = entity_registry.async_get( "sensor.phoniebox_test_box_version" ) assert entry assert entry.unique_id == "test_box-sensor.phoniebox_test_box_version" version_sensor_state = hass.states.get("sensor.phoniebox_test_box_version") assert version_sensor_state is not None assert version_sensor_state.state == MOCK_VERSION
25,051
def serializable_value(self, field_name): """ Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly. Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method. """ try: field = self._admin_opts.get_field_by_name(field_name)[0] except FieldDoesNotExist: return getattr(self, field_name) return getattr(self, field.name)
25,052
def fetch_fi2010(normalization=None) -> pandas.DataFrame: """ Load the FI2010 dataset with no auction. Benchmark Dataset for Mid-Price Forecasting of Limit Order Book Data with Machine Learning Methods. A Ntakaris, M Magris, J Kanniainen, M Gabbouj, A Iosifidis. arXiv:1705.03233 [cs.CE]. https://arxiv.org/abs/1705.03233 Parameters ---------- normalization : {"zscore", None} Normalization method. """ if normalization is None: url = "https://raw.githubusercontent.com/simaki/fi2010/main/data/data.csv" return pandas.read_csv(url, index_col=0) if normalization == "zscore": url1 = "https://raw.githubusercontent.com/simaki/fi2010/main/data/data_zscore1.csv" url2 = "https://raw.githubusercontent.com/simaki/fi2010/main/data/data_zscore2.csv" return pandas.concat([pandas.read_csv(url1, index_col=0), pandas.read_csv(url2, index_col=0)])
25,053
def get_netcdf_filename(batch_idx: int) -> str: """Generate full filename, excluding path.""" assert 0 <= batch_idx < 1e6 return f"{batch_idx:06d}.nc"
25,054
def CreateBoardConfigs(site_config, boards_dict, ge_build_config): """Create mixin templates for each board.""" # Extract the full list of board names from GE data. separate_board_names = set(config_lib.GeBuildConfigAllBoards(ge_build_config)) unified_builds = config_lib.GetUnifiedBuildConfigAllBuilds(ge_build_config) unified_board_names = set([b[config_lib.CONFIG_TEMPLATE_REFERENCE_BOARD_NAME] for b in unified_builds]) board_names = separate_board_names | unified_board_names # TODO(crbug.com/648473): Remove these, after GE adds them to their data set. board_names = board_names.union(boards_dict['all_boards']) result = dict() for board in board_names: board_config = config_lib.BuildConfig(boards=[board]) if board in _brillo_boards: board_config.apply(site_config.templates.brillo) if board in _lakitu_boards: board_config.apply(site_config.templates.lakitu) if board in _lassen_boards: board_config.apply(site_config.templates.lassen) if board in ['x30evb']: board_config.apply(site_config.templates.x30evb) if board in _loonix_boards: board_config.apply(site_config.templates.loonix) if board in _moblab_boards: board_config.apply(site_config.templates.moblab) if board in _accelerator_boards: board_config.apply(site_config.templates.accelerator) if board in _termina_boards: board_config.apply(site_config.templates.termina) if board in _nofactory_boards: board_config.apply(factory=False, factory_toolkit=False, factory_install_netboot=False, images=remove_images(['factory_install'])) if board in _toolchains_from_source: board_config.apply(usepkg_toolchain=False) if board in _noimagetest_boards: board_config.apply(image_test=False) if board in _nohwqual_boards: board_config.apply(hwqual=False) if board in _norootfs_verification_boards: board_config.apply(rootfs_verification=False) if board in _base_layout_boards: board_config.apply(disk_layout='base') if board in _no_unittest_boards: board_config.apply(site_config.templates.no_unittest_builder) if board in _beaglebone_boards: board_config.apply(site_config.templates.beaglebone) if board == 'moblab-generic-vm': board_config.apply(site_config.templates.moblab_vm_tests) result[board] = board_config return result
25,055
def area_calc(radius, point_in, total_points): """Calculates the partial area of ball :param radius: radius of ball :param point_in: points of the total points to include :param total_points: number of sampled points :return: area """ return (4 * pi * radius ** 2) * (point_in / total_points)
25,056
def results_framework_export(request, program): """Returns .XLSX containing program's results framework""" program = Program.rf_aware_objects.get(pk=program) wb = openpyxl.Workbook() wb.remove(wb.active) ws = wb.create_sheet(gettext("Results Framework")) get_font = lambda attrs: styles.Font(**{**{'name': 'Calibri', 'size': 12}, **attrs}) ws.cell(row=2, column=2).value = gettext("Results Framework") ws.cell(row=2, column=2).font = get_font({'size': 18, 'bold': True}) ws.cell(row=3, column=2).value = program.name ws.cell(row=3, column=2).font = get_font({'size': 18}) level_span_style = styles.NamedStyle(name='level_span') level_span_style.font = get_font({}) level_span_style.alignment = styles.Alignment(wrap_text=True, vertical='center', horizontal='center') level_span_style.fill = styles.PatternFill('solid', 'E5E5E5') wb.add_named_style(level_span_style) level_single_style = styles.NamedStyle(name='level_no_span') level_single_style.font = get_font({}) level_single_style.alignment = styles.Alignment(wrap_text=True, vertical='top', horizontal='left') level_single_style.fill = styles.PatternFill('solid', 'E5E5E5') wb.add_named_style(level_single_style) bottom_tier = program.level_tiers.count() def row_height_getter(cell): lines_of_text = str(cell.value).splitlines() row = cell.row def get_row_height_decorated(w): lines = sum([math.ceil(len(s)/w) or 1 for s in lines_of_text]) height = 26 + lines * 15 if lines == 1: height = 30 return max(height, ws.row_dimensions[row].height or 0, 30) return get_row_height_decorated def write_level(parent, start_row, start_column): levels = program.levels.filter(parent=parent).order_by('customsort') column = start_column row = start_row if not levels: return column + 2 for level in levels: current_column = column cell = ws.cell(row=row, column=column) cell.value = level.display_name get_row_height = row_height_getter(cell) if level.level_depth == bottom_tier: cell.style = 'level_no_span' row = row + 2 ws.row_dimensions[cell.row].height = get_row_height(24) else: column = write_level(level, row+2, column) if column - 2 <= current_column: cell.style = 'level_no_span' ws.row_dimensions[cell.row].height = get_row_height(24) else: cell.style = 'level_span' ws.merge_cells(start_row=row, end_row=row, start_column=current_column, end_column=column-2) width = 24 + 29 * ((column - 2 - current_column) / 2) ws.row_dimensions[cell.row].height = get_row_height(width) if parent and parent.level_depth == bottom_tier-1: column = column + 2 if parent is None: for column in range(column): width = 24.5 if (column + 1) % 2 == 0 else 3 ws.column_dimensions[utils.get_column_letter(column + 1)].width = width for r in range(3, ws.max_row+2): if r % 2 == 0: ws.row_dimensions[r].height = 10 return column write_level(None, 5, 2) filename = "Results Framework.xlsx" response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) wb.save(response) return response
25,057
def generate_subwindow(pc, sample_bb, scale, offset=2, oriented=True): """ generating the search area using the sample_bb :param pc: :param sample_bb: :param scale: :param offset: :param oriented: use oriented or axis-aligned cropping :return: """ rot_mat = np.transpose(sample_bb.rotation_matrix) trans = -sample_bb.center if oriented: new_pc = PointCloud(pc.points.copy()) box_tmp = copy.deepcopy(sample_bb) # transform to the coordinate system of sample_bb new_pc.translate(trans) box_tmp.translate(trans) new_pc.rotate(rot_mat) box_tmp.rotate(Quaternion(matrix=rot_mat)) new_pc = crop_pc_axis_aligned(new_pc, box_tmp, scale=scale, offset=offset) else: new_pc = crop_pc_axis_aligned(pc, sample_bb, scale=scale, offset=offset) # transform to the coordinate system of sample_bb new_pc.translate(trans) new_pc.rotate(rot_mat) return new_pc
25,058
def save_agent(agent, algorithm, policy, run_name): """ Saves the state dict of an agent to file """ if algorithm in ["mcts", "lfd", "lfd-mcts"] and policy == "nn" and agent is not None: filename = f"./data/runs/{run_name}/model.pty" logger.info(f"Saving model at {filename}") torch.save(agent.state_dict(), filename) ex.add_artifact(filename) else: logger.debug(f"No model weights need to be saved for algorithm {algorithm} and policy {policy}")
25,059
def augmented_print(text, file, flush=False): """Print to both the standard output and the given file.""" assert isinstance(text, str) print(text) file.write(text + "\n") if flush: sys.stdout.flush() file.flush()
25,060
def close_swift_conn(src): """ Force close the http connection to the backend. :param src: the response from the backend """ try: # Since the backends set "Connection: close" in their response # headers, the response object (src) is solely responsible for the # socket. The connection object (src.swift_conn) has no references # to the socket, so calling its close() method does nothing, and # therefore we don't do it. # # Also, since calling the response's close() method might not # close the underlying socket but only decrement some # reference-counter, we have a special method here that really, # really kills the underlying socket with a close() syscall. src.nuke_from_orbit() # it's the only way to be sure except Exception: pass
25,061
def tsfigure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, subplotpars=None, FigureClass=TSFigure): """ Creates a new :class:`TimeSeriesFigure` object. Parameters ---------- num : {None, int}, optional Number of the figure. If None, a new figure is created and ``num`` is incremented. %(figsize)s %(dpi)s %(facecolor)s %(edgecolor)s %(frameon)s %(subplotpars)s FigureClass : FigureClass Class of the figure to create """ figargs = dict(num=num, figsize=figsize, dpi=dpi, facecolor=facecolor, frameon=frameon, FigureClass=FigureClass, subplotpars=subplotpars) fig = pylab.figure(**figargs) return fig
25,062
def load_predict_result(predict_filename): """Loads the file to be predicted""" predict_result = {} ret_code = SUCCESS try: predict_file_zip = zipfile.ZipFile(predict_filename) except: ret_code = FILE_ERROR return predict_result, ret_code for predict_file in predict_file_zip.namelist(): for line in predict_file_zip.open(predict_file): try: line = line.decode('utf8').strip() except: ret_code = ENCODING_ERROR return predict_result, ret_code try: json_info = json.loads(line) except: ret_code = JSON_ERROR return predict_result, ret_code if 'text' not in json_info or 'spo_list' not in json_info: ret_code = SCHEMA_ERROR return predict_result, ret_code sent = json_info['text'] spo_set = set() for spo_item in json_info['spo_list']: if type(spo_item) is not dict or 'subject' not in spo_item \ or 'predicate' not in spo_item \ or 'object' not in spo_item or \ not isinstance(spo_item['subject'], basestring) or \ not isinstance(spo_item['object'], basestring): ret_code = SCHEMA_ERROR return predict_result, ret_code s = del_bookname(spo_item['subject'].lower()) o = del_bookname(spo_item['object'].lower()) spo_set.add((s, spo_item['predicate'], o)) predict_result[sent] = spo_set return predict_result, ret_code
25,063
def localize_all(roi, ignore_exception=True, **kwargs): """ localize all variable local sources in the roi, make TSmaps and associations if requested ignore if extended -- has 'spatial_model' kwargs can have prefix to select subset with name starting with the prefix, e.g. 'SEED' """ tsmin = kwargs.pop('tsmin',10) prefix = kwargs.pop('prefix', None) source_name = kwargs.pop('source_name', None) update = kwargs.pop('update', False) def filt(s): ok = s.skydir is not None\ and isinstance(s, sources.PointSource) \ and np.any(s.spectral_model.free) if not ok: return False if not hasattr(s,'ts'): s.ts = roi.TS(s.name) return ok and s.ts>tsmin if source_name is not None: vpsources=[roi.get_source(source_name)] else: vpsources = filter(filt, roi.sources) tsmap_dir = kwargs.pop('tsmap_dir', None) if tsmap_dir is not None: if tsmap_dir[0]=='$': tsmap_dir = os.path.expandvars(tsmap_dir) if not os.path.exists(tsmap_dir): os.makedirs(tsmap_dir) associator = kwargs.pop('associator', None) tsfits = kwargs.pop('tsfits', True) if len(kwargs.keys())>0: print ('Warning: unrecognized args to localize_all: %s' %kwargs) initw = roi.log_like() for source in vpsources: if prefix is not None and not source.name.startswith(prefix): continue full_localization(roi, source.name, ignore_exception=ignore_exception, update=update, associator=associator, tsmap_dir=tsmap_dir, tsfits=tsfits) curw= roi.log_like() if abs(initw-curw)>1.0 and not update: print ('localize_all: unexpected change in roi state after localization, from %.1f to %.1f (%+.1f)'\ %(initw, curw, curw-initw)) return False else: return True
25,064
def test_map_lambda_as_element(): """Test that a map lambda is held as a single element""" stack = run_vyxal("⁽ƛ1+;M", inputs=[[[1, 2], [3, 4]]]) assert stack[-1] == [[2, 3], [4, 5]]
25,065
def convert_post_to_VERB(request, verb): """ Force Django to process the VERB. """ if request.method == verb: if hasattr(request, '_post'): del(request._post) del(request._files) try: request.method = "POST" request._load_post_and_files() request.method = verb except AttributeError: request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = verb setattr(request, verb, request.POST) return request
25,066
def close(x, y, rtol, atol): """Returns True if x and y are sufficiently close. Parameters ---------- rtol The relative tolerance. atol The absolute tolerance. """ # assumes finite weights return abs(x-y) <= atol + rtol * abs(y)
25,067
def add_unknown_words(word_vecs, vocab, min_df=1, k=300): """ For words that occur in at least min_df sentences, create a separate word vector. 0.25 is chosen so the unknown vectors have (approximately) same variance as pre-trained ones """ for word in vocab: if word not in word_vecs and vocab[word] >= min_df: word_vecs[word] = np.random.uniform(-0.25,0.25,k)
25,068
def plot_precip_field( precip, ptype="intensity", ax=None, geodata=None, units="mm/h", bbox=None, colorscale="pysteps", probthr=None, title=None, colorbar=True, axis="on", cax=None, map_kwargs=None, **kwargs, ): """ Function to plot a precipitation intensity or probability field with a colorbar. .. _Axes: https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes .. _SubplotSpec: https://matplotlib.org/api/_as_gen/matplotlib.gridspec.SubplotSpec.html Parameters ---------- precip: array-like Two-dimensional array containing the input precipitation field or an exceedance probability map. ptype: {'intensity', 'depth', 'prob'}, optional Type of the map to plot: 'intensity' = precipitation intensity field, 'depth' = precipitation depth (accumulation) field, 'prob' = exceedance probability field. geodata: dictionary or None, optional Optional dictionary containing geographical information about the field. Required is map is not None. If geodata is not None, it must contain the following key-value pairs: .. tabularcolumns:: |p{1.5cm}|L| +-----------------+---------------------------------------------------+ | Key | Value | +=================+===================================================+ | projection | PROJ.4-compatible projection definition | +-----------------+---------------------------------------------------+ | x1 | x-coordinate of the lower-left corner of the data | | | raster | +-----------------+---------------------------------------------------+ | y1 | y-coordinate of the lower-left corner of the data | | | raster | +-----------------+---------------------------------------------------+ | x2 | x-coordinate of the upper-right corner of the | | | data raster | +-----------------+---------------------------------------------------+ | y2 | y-coordinate of the upper-right corner of the | | | data raster | +-----------------+---------------------------------------------------+ | yorigin | a string specifying the location of the first | | | element in the data raster w.r.t. y-axis: | | | 'upper' = upper border, 'lower' = lower border | +-----------------+---------------------------------------------------+ units : {'mm/h', 'mm', 'dBZ'}, optional Units of the input array. If ptype is 'prob', this specifies the unit of the intensity threshold. bbox : tuple, optional Four-element tuple specifying the coordinates of the bounding box. Use this for plotting a subdomain inside the input grid. The coordinates are of the form (lower left x, lower left y ,upper right x, upper right y). If 'geodata' is not None, the bbox is in map coordinates, otherwise it represents image pixels. colorscale : {'pysteps', 'STEPS-BE', 'BOM-RF3'}, optional Which colorscale to use. Applicable if units is 'mm/h', 'mm' or 'dBZ'. probthr : float, optional Intensity threshold to show in the color bar of the exceedance probability map. Required if ptype is "prob" and colorbar is True. title : str, optional If not None, print the title on top of the plot. colorbar : bool, optional If set to True, add a colorbar on the right side of the plot. axis : {'off','on'}, optional Whether to turn off or on the x and y axis. cax : Axes_ object, optional Axes into which the colorbar will be drawn. If no axes is provided the colorbar axes are created next to the plot. Other parameters ---------------- map_kwargs: dict Optional parameters that need to be passed to :py:func:`pysteps.visualization.basemaps.plot_geography`. Returns ------- ax : fig Axes_ Figure axes. Needed if one wants to add e.g. text inside the plot. """ if map_kwargs is None: map_kwargs = {} if "type" in kwargs: warnings.warn( "The 'type' keyword use to indicate the type of plot will be " "deprecated in version 1.6. Use 'ptype' instead." ) ptype = kwargs.get("type") if ptype not in PRECIP_VALID_TYPES: raise ValueError( f"Invalid precipitation type '{ptype}'." f"Supported: {str(PRECIP_VALID_TYPES)}" ) if units not in PRECIP_VALID_UNITS: raise ValueError( f"Invalid precipitation units '{units}." f"Supported: {str(PRECIP_VALID_UNITS)}" ) if ptype == "prob" and colorbar and probthr is None: raise ValueError("ptype='prob' but probthr not specified") if len(precip.shape) != 2: raise ValueError("The input is not two-dimensional array") # Assumes the input dimensions are lat/lon nlat, nlon = precip.shape x_grid, y_grid, extent, regular_grid, origin = get_geogrid( nlat, nlon, geodata=geodata ) ax = get_basemap_axis(extent, ax=ax, geodata=geodata, map_kwargs=map_kwargs) precip = np.ma.masked_invalid(precip) # plot rainfield if regular_grid: im = _plot_field(precip, ax, ptype, units, colorscale, extent, origin=origin) else: im = _plot_field( precip, ax, ptype, units, colorscale, extent, x_grid=x_grid, y_grid=y_grid ) plt.title(title) # add colorbar if colorbar: # get colormap and color levels _, _, clevs, clevs_str = get_colormap(ptype, units, colorscale) if ptype in ["intensity", "depth"]: extend = "max" else: extend = "neither" cbar = plt.colorbar( im, ticks=clevs, spacing="uniform", extend=extend, shrink=0.8, cax=cax ) if clevs_str is not None: cbar.ax.set_yticklabels(clevs_str) if ptype == "intensity": cbar.set_label(f"Precipitation intensity [{units}]") elif ptype == "depth": cbar.set_label(f"Precipitation depth [{units}]") else: cbar.set_label(f"P(R > {probthr:.1f} {units})") if geodata is None or axis == "off": ax.xaxis.set_ticks([]) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticks([]) ax.yaxis.set_ticklabels([]) if bbox is not None: ax.set_xlim(bbox[0], bbox[2]) ax.set_ylim(bbox[1], bbox[3]) return ax
25,069
def get_for_repo(repo, name, default=None): """Gets a configuration setting for a particular repository. Looks for a setting specific to the repository, then falls back to a global setting.""" NOT_FOUND = [] # a unique sentinel distinct from None value = get(name, NOT_FOUND, repo) if value is NOT_FOUND: value = get(name, default, '*') return value
25,070
def new_user(tenant: AnyStr, password: AnyStr) -> bool: """Return a boolean containing weither a new tenant is created or no.""" if not query.get_tenant_id(tenant): return True return False
25,071
def home(): """ Home page control code :return Rendered page: """ error = request.args.get("error", None) state, code = request.args.get("state", None), request.args.get("code", None) if code and not has_user() and 'state' in session and session['state'] == state: tok = reddit_get_access_token(code) username = reddit_get_username(tok) session['user'] = username session['token'] = tok session.modified = True session['state'] = str(uuid4()) session.modified = True return render_template('home.html', user=get_user(), error=False, redirect=whisky_recommender.config.REDDIT_REDIRECT, client_id=whisky_recommender.config.REDDIT_CLIENT, state=session['state'])
25,072
def build_and_save_df(): """Assembles all data together into a pandas DataFrame and saves as csv. Saves ---------------- elem_dict: dict Dictionary of mapping stoich vector to elements magpie_embed: dict Dictionary mapping precursors to magpie embeddings (for use in Roost) df: pd.Dataframe Dataframe with each row giving reaction information Data columns are as follows: ========== ============================================================== dois (string) reaction doi (for reference) reaction (string) reaction string prec_stoich (list of lists) stoichiometry vector for each precursor (zero padded) prec_magpie (list of lists) magpie embedding vector for each precursor prec_roost (list of strings) normalised formulas for each precursor for Roost prec_roost_am (list of tuples) as above, except (formula, amount) for each instead actions (list of lists) OHE action sequences for the reaction target (list) stoichiometry vector for target material ========== ============================================================== """ # NOTE the fact the the numbers for each element change each time the file # is processed should be fixed. data = load_dataset() elem_dict = find_elem_dict(data) save_dict(elem_dict, args.elem_dict) # data = data[:500] targets_stoich = preprocess_target_stoich(data, elem_dict) # prec_stoich, _ = preprocess_precursors_stoich(data, elem_dict) # # reduce dataset # if args.num_elem > 0: # data = remove_rare_elems(data, prec_stoich, targets_stoich, elem_dict) # elem_dict = find_elem_dict(data) # print(elem_dict) # targets_stoich = preprocess_target_stoich(data, elem_dict) # NOTE the prec_roost column is unneccesary and should be changed # NOTE the prec_magpie column is unneccesary with the associated magpie_embed reference and should be changed processed = preprocess_precursors_roost(data, elem_dict, get_amount=False, get_all=True) prec_stoich, prec_magpie, prec_roost, prec_roost_am, magpie_embed = processed save_dict(magpie_embed, args.magpie_embed) actions, action_dict = preprocess_actions(data) save_dict(action_dict, args.action_dict) dois = [x['doi'] for x in data] reactions = [x['reaction_string'] for x in data] features = {'prec_stoich': prec_stoich, 'prec_magpie': prec_magpie, 'prec_roost': prec_roost, 'prec_roost_am': prec_roost_am, 'actions': actions, 'target': targets_stoich} features = {k: v.tolist() if type(v) == np.ndarray else v for (k, v) in features.items()} # save data df = pd.DataFrame({'dois': dois, 'reaction': reactions, **features}) df["n_prec"] = df["prec_roost"].apply(lambda x: len(x)) save_dataset(df, args.clean_set) df_train, df_test = split(df, random_state=args.seed, test_size=args.test_size) save_dataset(df_test, args.test_set) if args.val_size: df_train, df_val = split(df_train, random_state=args.seed, test_size=args.val_size / (1 - args.test_size)) save_dataset(df_val, args.val_set) save_dataset(df_train, args.train_set) if args.split_prec_amts: save_dataset_splits(df_train, args.train_set) save_dataset_splits(df_test, args.test_set) if args.val_size: save_dataset_splits(df_val, args.val_set)
25,073
def get_date_list(num_days): """ For an integer number of days (num_days), get an ordered list of DateTime objects to report on. """ local_tz = tzlocal.get_localzone() local_start_date = local_tz.localize(datetime.datetime.now()).replace(hour=0, minute=0, second=0, microsecond=0) - datetime.timedelta(seconds=1) logger.debug("local_start_date={d}".format(d=local_start_date.strftime("%Y-%m-%d %H:%M:%S%z %Z"))) start_date = local_start_date.astimezone(pytz.utc) logger.debug("start_date={d}".format(d=start_date.strftime("%Y-%m-%d %H:%M:%S%z %Z"))) end_date = (start_date - datetime.timedelta(days=num_days)) + datetime.timedelta(seconds=1) logger.debug("end_date={d}".format(d=end_date.strftime("%Y-%m-%d %H:%M:%S%z %Z"))) dates = [start_date - datetime.timedelta(n) for n in range(num_days)] return dates
25,074
def is_even(val): """ Confirms if a value if even. :param val: Value to be tested. :type val: int, float :return: True if the number is even, otherwise false. :rtype: bool Examples: -------------------------- .. code-block:: python >>> even_numbers = list(filter(is_even, range(20))) >>> print(even_numbers) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> print(is_even(9)) False >>> print(is_even(-2)) True >>> print([value for value in range(20) if is_even(value)]) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> print([is_even(value) for value in range(4)]) [True, False, True, False] """ return (val % 2) == 0
25,075
def get_fremont_data(filename = "Fremont.csv", url = URL, force_download = False): """ Download and cache the fremont data Parameters ---------- csv file Fremont.csv url URL force download Returns ------- data : pandas dataframe """ if force_download or not os.path.exists(filename): urlretrieve(URL, "Fremont.csv") data = pd.read_csv("Fremont.csv", index_col = "Date", parse_dates = True) data.columns = ["Total", "East", "West"] return data
25,076
def min_spacing(mylist): """ Find the minimum spacing in the list. Args: mylist (list): A list of integer/float. Returns: int/float: Minimum spacing within the list. """ # Set the maximum of the minimum spacing. min_space = max(mylist) - min(mylist) # Iteratively find a smaller spacing. for item in mylist: spaces = [abs(item - item2) for item2 in mylist if item != item2] min_space = min(min_space, min(spaces)) # Return the answer. return min_space
25,077
def extract_dawn_compiler_options() -> list: """Generate options_info for the Dawn compiler options struct.""" options_info = [] regex = re.compile(r"OPT\(([^,]+), ?(\w+)") DAWN_CPP_SRC_ROOT = os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, "src", "dawn" ) # Extract info from .cpp files for name in [ os.path.join(DAWN_CPP_SRC_ROOT, "Compiler", "Options.inc"), os.path.join(DAWN_CPP_SRC_ROOT, "Optimizer", "OptimizerOptions.inc"), ]: options_cpp = [] with open(name, "r") as f: for line in f: line = line.strip() if not (line.startswith("//") or line.startswith("#")): if line.startswith("OPT("): m = regex.match(line) type_str, name_str = m.group(1), m.group(2) line = re.sub(regex, f'{name_str} = ("{type_str}" ', line) options_cpp.append(line) elif line: if options_cpp[-1].endswith('"'): options_cpp[-1] += " + " + line else: options_cpp[-1] += line # OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) options_cpp = "\n".join(options_cpp) for old, new in [("false", "'false'"), ("true", "'true'")]: options_cpp = options_cpp.replace(old, new) defs = {} exec(options_cpp, defs) for key, value in defs.items(): if not key.startswith("__"): py_type = pythonize_type(value[0]) py_default = pythonize_value(value[1], as_type=py_type) options_info.append( MemberInfo( py_name=pythonize_name(key), cpp_name=key, py_type=py_type, cpp_type=value[0], py_default=py_default, cpp_default=value[1], const=False, help=value[4], ) ) return options_info
25,078
def sign(x): """Return the mathematical sign of the particle.""" if x.imag: return x / sqrt(x.imag ** 2 + x.real ** 2) return 0 if x == 0 else -1 if x < 0 else 1
25,079
def wrap_strings(lines: [str], line_width: int): """Return a list of strings, wrapped to the specified length.""" i = 0 while i < len(lines): # if a line is over the limit if len(lines[i]) > line_width: # (try to) find the rightmost occurrence of a space in the first 80 chars try: split_index = lines[i][:line_width].rindex(" ") except ValueError: return None # split the line by the found space and add it to the next one lines.insert(i + 1, lines[i][split_index + 1 :]) lines[i] = lines[i][:split_index] i += 1 return lines
25,080
def test_deprecated_section(): """Parse deprecated section.""" docstring = """ Deprecated ---------- 1.23.4 Deprecated. Sorry. """ sections, _ = parse(docstring) assert len(sections) == 1 assert sections[0].value.version == "1.23.4" assert sections[0].value.description == "Deprecated.\nSorry."
25,081
def has_even_parity(message: int) -> bool: """ Return true if message has even parity.""" parity_is_even: bool = True while message: parity_is_even = not parity_is_even message = message & (message - 1) return parity_is_even
25,082
def is_primitive(structure): """ Checks if a structure is primitive or not, :param structure: AiiDA StructureData :return: True if the structure can not be anymore refined. prints False if the structure can be futher refined. """ refined_cell = find_primitive_cell(structure) prim = False if all(x in structure.cell for x in refined_cell.cell): prim = True return prim
25,083
def mock_mkdir(monkeypatch): """Mock the mkdir function.""" def mocked_mkdir(path, mode=0o755): return True monkeypatch.setattr("charms.layer.git_deploy.os.mkdir", mocked_mkdir)
25,084
def validate_run_items(run_items): """ Check the validity of classical addresses / qubits for the payload. :param list|range run_items: List of classical addresses or qubits to be validated. """ if not isinstance(run_items, (list, range)): raise TypeError("run_items must be a list") if any([not isinstance(i, integer_types) for i in run_items]): raise TypeError("run_items list must contain integer values")
25,085
def test_jsd1(): """ Test the JSD of a distribution with itself """ d1 = Distribution("AB", [0.5, 0.5]) jsd = JSD([d1, d1]) assert_almost_equal(jsd, 0)
25,086
def add_worker(): """Increase the number of your Gunicorn workers""" set_env_defaults() if not gunicorn_running(): puts(colors.red("Gunicorn isn't running!")) return puts(colors.green('Increasing number of workers...')) run('kill -TTIN `cat %s`' % (env.gunicorn_pidpath)) puts(colors.yellow('Active workers: %s' % gunicorn_running_workers()))
25,087
async def setup(mass) -> None: """Perform async setup of this Plugin/Provider.""" prov = FanartTvProvider(mass) await mass.register_provider(prov)
25,088
def zip_dir_recursively(base_dir, zip_file): """Zip compresses a base_dir recursively.""" zip_file = zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED) root_len = len(os.path.abspath(base_dir)) for root, _, files in os.walk(base_dir): archive_root = os.path.abspath(root)[root_len:] for f in files: fullpath = os.path.join(root, f) archive_name = os.path.join(archive_root, f) zip_file.write(fullpath, archive_name, zipfile.ZIP_DEFLATED) zip_file.close() return zip_file
25,089
def saferepr(obj, maxsize=240): """return a size-limited safe repr-string for the given object. Failing __repr__ functions of user instances will be represented with a short exception info and 'saferepr' generally takes care to never raise exceptions itself. This function is a wrapper around the Repr/reprlib functionality of the standard 2.6 lib. """ # review exception handling srepr = SafeRepr() srepr.maxstring = maxsize srepr.maxsize = maxsize srepr.maxother = 160 return srepr.repr(obj)
25,090
def figsize(x=9, y=4): """Temporarily set the figure size using 'with figsize(a,b):'""" size = pylab.rcParams['figure.figsize'] set_figsize(x, y) yield pylab.rcParams['figure.figsize'] = size
25,091
def filter(pred : Callable[[A], bool], stream : Stream[A]) -> Stream[A]: """Filter a stream of type `A`. :param pred: A predicate on type `A`. :type pred: `A -> bool` :param stream: A stream of type `A` to be filtered. :type stream: `Stream[A]` :return: A stream of type `A`. :rtype: `Stream[A]` """ def _thunk() -> StreamResult[A]: next_stream : Stream[A] = stream while True: next_value, next_stream = next_stream() if not pred(next_value): continue return next_value, filter(pred, next_stream) return _thunk
25,092
def _get_kernel_size_numel(kernel_size): """Determine number of pixels/voxels. ``kernel_size`` must be an ``N``-tuple.""" if not isinstance(kernel_size, tuple): raise ValueError(f"kernel_size must be a tuple. Got {kernel_size}.") return _get_numel_from_shape(kernel_size)
25,093
def random(): """Get a random UUID.""" return str(uuid.uuid4())
25,094
def printe(s: str, end="\n"): """ Print to stderr """ sys.stderr.write(s + end)
25,095
def reautorank(reaumur): """ This function converts Reaumur to rankine, with Reaumur as parameter.""" rankine = (reaumur * 2.25) + 491.67 return rankine
25,096
def list_pets(): """Shows list of all pets in db""" pets = Pet.query.all() return render_template('list.html', pets=pets)
25,097
def test_make_gameshow(): """Test gameshow factory.""" app = make_gameshow() assert isinstance(app, GameShow)
25,098
def BundleFpmcuUnittests(chroot, sysroot, output_directory): """Create artifact tarball for fingerprint MCU on-device unittests. Args: chroot (chroot_lib.Chroot): The chroot containing the sysroot. sysroot (sysroot_lib.Sysroot): The sysroot whose artifacts are being archived. output_directory (str): The path were the completed archives should be put. Returns: str|None - The archive file path if created, None otherwise. """ fpmcu_unittests_root = os.path.join(chroot.path, sysroot.path.lstrip(os.sep), 'firmware', 'chromeos-fpmcu-unittests') files = [os.path.relpath(f, fpmcu_unittests_root) for f in glob.iglob(os.path.join(fpmcu_unittests_root, '*'))] if not files: return None archive_file = os.path.join(output_directory, constants.FPMCU_UNITTESTS_ARCHIVE_NAME) cros_build_lib.CreateTarball( archive_file, fpmcu_unittests_root, compression=cros_build_lib.COMP_BZIP2, chroot=chroot.path, inputs=files) return archive_file
25,099