code stringlengths 1 18.2k |
|---|
:return: Retorna *verbatim* a resposta da função SAT. :rtype: string """ return self.invocar__AtivarSAT( self.gerar_numero_sessao(), tipo_certificado, self._codigo_ativacao, cnpj, codigo_uf) |
def comunicar_certificado_icpbrasil(self, certificado): """Função ``ComunicarCertificadoICPBRASIL`` conforme ER SAT, item 6.1.2. Envio do certificado criado pela ICP-Brasil. :param str certificado: Conteúdo do certificado digital criado pela autoridade certificadora ICP-Brasil. :return: Retorna *verbatim* a resposta da... |
def enviar_dados_venda(self, dados_venda): """Função ``EnviarDadosVenda`` conforme ER SAT, item 6.1.3. Envia o CF-e de venda para o equipamento SAT, que o enviará para autorização pela SEFAZ. :param dados_venda: Uma instância de :class:`~satcfe.entidades.CFeVenda` ou uma string contendo o XML do CF-e de venda. :return:... |
self.invocar__EnviarDadosVenda( self.gerar_numero_sessao(), self._codigo_ativacao, cfe_venda) |
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento): """Função ``CancelarUltimaVenda`` conforme ER SAT, item 6.1.4. Envia o CF-e de cancelamento para o equipamento SAT, que o enviará para autorização e cancelamento do CF-e pela SEFAZ. :param chave_cfe: String contendo a chave do CF-e a ser cancelado, prefixa... |
Retorna *verbatim* a resposta da função SAT. :rtype: string """ cfe_canc = dados_cancelamento \ if isinstance(dados_cancelamento, basestring) \ else dados_cancelamento.documento() return self.invocar__CancelarUltimaVenda( self.gerar_numero_sessao(), self._codigo_ativacao, chave_cfe, cfe_canc) |
def consultar_numero_sessao(self, numero_sessao): """Função ``ConsultarNumeroSessao`` conforme ER SAT, item 6.1.8. Consulta o equipamento SAT por um número de sessão específico. :param int numero_sessao: Número da sessão que se quer consultar. :return: Retorna *verbatim* a resposta da função SAT. :rtype: string """ ret... |
def configurar_interface_de_rede(self, configuracao): """Função ``ConfigurarInterfaceDeRede`` conforme ER SAT, item 6.1.9. Configurção da interface de comunicação do equipamento SAT. :param configuracao: Instância de :class:`~satcfe.rede.ConfiguracaoRede` ou uma string contendo o XML com as configurações de rede. :retu... |
def associar_assinatura(self, sequencia_cnpj, assinatura_ac): """Função ``AssociarAssinatura`` conforme ER SAT, item 6.1.10. Associação da assinatura do aplicativo comercial. :param sequencia_cnpj: Sequência string de 28 dígitos composta do CNPJ do desenvolvedor da AC e do CNPJ do estabelecimento comercial contribuinte... |
SAT. :rtype: string """ return self.invocar__AssociarAssinatura( self.gerar_numero_sessao(), self._codigo_ativacao, sequencia_cnpj, assinatura_ac) |
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Função ``TrocarCodigoDeAtivacao`` conforme ER SAT, item 6.1.15. Troca do código de ativação do equipamento SAT. :param str novo_codigo_ativacao: O novo código de ativação escolhido pelo contri... |
Deverá ser o valor de uma das constantes :attr:`satcomum.constantes.CODIGO_ATIVACAO_REGULAR` (padrão) ou :attr:`satcomum.constantes.CODIGO_ATIVACAO_EMERGENCIA`. Nenhuma validação será realizada antes que a função seja efetivamente invocada. Entretanto, se opção de código de ativação indicada for ``CODIGO_ATIVACAO_EMERG... |
Este código deverá ser usado quando o usuário perder o código de ativação regular, e precisar definir um novo código de ativação. Note que, o argumento ``opcao`` deverá ser informado com o valor :attr:`satcomum.constantes.CODIGO_ATIVACAO_EMERGENCIA` para que este código de emergência seja considerado. :return: Retorna ... |
uma string nula por exemplo) ou se o código de emergencia avaliar como falso quando a opção for pelo código de ativação de emergência. .. warning:: Os argumentos da função ``TrocarCodigoDeAtivacao`` requerem que o novo código de ativação seja especificado duas vezes (dois argumentos com o mesmo conteúdo, como confirmaç... |
a confirmação do código de ativação fora do escopo desta API. """ if not novo_codigo_ativacao: raise ValueError('Novo codigo de ativacao invalido: {!r}'.format( novo_codigo_ativacao)) codigo_ativacao = self._codigo_ativacao if opcao == constantes.CODIGO_ATIVACAO_EMERGENCIA: if codigo_emergencia: codigo_ativacao = codig... |
def load_forecasts(self): """ Loads the forecast files and gathers the forecast information into pandas DataFrames. """ forecast_path = self.forecast_json_path + "/{0}/{1}/".format(self.run_date.strftime("%Y%m%d"), self.ensemble_member) forecast_files = sorted(glob(forecast_path + "*.json")) for forecast_file in foreca... |
model_type in self.model_types: for model_name in self.model_names[model_type]: prediction = feature['properties'][model_type + "_" + model_name.replace(" ", "-")] if model_type == "condition": prediction = [prediction] row = [track_id, obs_track_id, self.ensemble_name, self.ensemble_member, forecast_hours[f], f + 1, d... |
def load_obs(self): """ Loads the track total and step files and merges the information into a single data frame. """ track_total_file = self.track_data_csv_path + \ "track_total_{0}_{1}_{2}.csv".format(self.ensemble_name, self.ensemble_member, self.run_date.strftime("%Y%m%d")) track_step_file = self.track_data_csv_pat... |
self.obs = obs_data |
def merge_obs(self): """ Match forecasts and observations. """ for model_type in self.model_types: self.matched_forecasts[model_type] = {} for model_name in self.model_names[model_type]: self.matched_forecasts[model_type][model_name] = pd.merge(self.forecasts[model_type][model_name], self.obs, right_on="Step_ID", how="... |
def crps(self, model_type, model_name, condition_model_name, condition_threshold, query=None): """ Calculates the cumulative ranked probability score (CRPS) on the forecast data. Args: model_type: model type being evaluated. model_name: machine learning model being evaluated. condition_model_name: Name of the hail/no-h... |
gamma_cdf(x, a, loc, b): if a == 0 or b == 0: cdf = np.ones(x.shape) else: cdf = gamma.cdf(x, a, loc, b) return cdf crps_obj = DistributedCRPS(self.dist_thresholds) if query is not None: sub_forecasts = self.matched_forecasts[model_type][model_name].query(query) sub_forecasts = sub_forecasts.reset_index(drop=True) cond... |
f in range(sub_forecasts.shape[0]): condition_prob = condition_forecasts.loc[f, self.forecast_bins["condition"][0]] if condition_prob >= condition_threshold: f_params = [0, 0, 0] else: f_params = sub_forecasts[self.forecast_bins[model_type]].values[f] forecast_cdfs[f] = gamma_cdf(self.dist_thresholds, f_params[0], f_pa... |
def roc(self, model_type, model_name, intensity_threshold, prob_thresholds, query=None): """ Calculates a ROC curve at a specified intensity threshold. Args: model_type: type of model being evaluated (e.g. size). model_name: machine learning model being evaluated intensity_threshold: forecast bin used as the split poin... |
DistributedROC object """ roc_obj = DistributedROC(prob_thresholds, 0.5) if query is not None: sub_forecasts = self.matched_forecasts[model_type][model_name].query(query) sub_forecasts = sub_forecasts.reset_index(drop=True) else: sub_forecasts = self.matched_forecasts[model_type][model_name] obs_values = np.zeros(sub_f... |
= 1 - sub_forecasts[self.forecast_bins[model_type].astype(str)].values.cumsum(axis=1)[:, fbin] obs_values[sub_forecasts[self.type_cols[model_type]].values >= intensity_threshold] = 1 else: forecast_values = sub_forecasts[self.forecast_bins[model_type].astype(str)[0]].values obs_values[sub_forecasts[self.type_cols[model... |
def sample_forecast_max_hail(self, dist_model_name, condition_model_name, num_samples, condition_threshold=0.5, query=None): """ Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes. Hail sizes are sampled from each predicted gamma distribution. The total number of sam... |
dist_model_name: Name of the distribution machine learning model being evaluated condition_model_name: Name of the hail/no-hail model being evaluated num_samples: Number of maximum hail samples to draw condition_threshold: Threshold for drawing hail samples query: A str that selects a subset of the data for evaluation ... |
self.matched_forecasts["dist"][dist_model_name].query(query) dist_forecasts = dist_forecasts.reset_index(drop=True) condition_forecasts = self.matched_forecasts["condition"][condition_model_name].query(query) condition_forecasts = condition_forecasts.reset_index(drop=True) else: dist_forecasts = self.matched_forecasts[... |
def get_params(self): """Get signature and params """ params = { 'key': self.get_app_key(), 'uid': self.user_id, 'widget': self.widget_code } products_number = len(self.products) if self.get_api_type() == self.API_GOODS: if isinstance(self.products, list): if products_number == 1: product = self.products[0] if isinstan... |
if product.get_type() == Product.TYPE_SUBSCRIPTION: params['ag_period_length'] = product.get_period_length() params['ag_period_type'] = product.get_period_type() if product.is_recurring(): params['ag_recurring'] = 1 if product.is_recurring() else 0 if post_trial_product: params['ag_trial'] = 1 params['ag_post_trial_ext... |
params['external_ids[' + str(index) + ']'] = product.get_id() if product.get_amount() > 0: params['prices[' + str(index) + ']'] = product.get_amount() if product.get_currency_code() != '' and product.get_currency_code() is not None: params['currencies[' + str(index) + ']'] = product.get_currency_code() index += 1 param... |
def hms(segundos): # TODO: mover para util.py """ Retorna o número de horas, minutos e segundos a partir do total de segundos informado. .. sourcecode:: python >>> hms(1) (0, 0, 1) >>> hms(60) (0, 1, 0) >>> hms(3600) (1, 0, 0) >>> hms(3601) (1, 0, 1) >>> hms(3661) (1, 1, 1) :param int segundos: O número total de segund... |
elementos representando, respectivamente, o número de horas, minutos e segundos calculados a partir do total de segundos. :rtype: tuple """ h = (segundos / 3600) m = (segundos - (3600 * h)) / 60 s = (segundos - (3600 * h) - (m * 60)); return (h, m, s) |
def hms_humanizado(segundos): # TODO: mover para util.py """ Retorna um texto legível que descreve o total de horas, minutos e segundos calculados a partir do total de segundos informados. .. sourcecode:: python >>> hms_humanizado(0) 'zero segundos' >>> hms_humanizado(1) '1 segundo' >>> hms_humanizado(2) '2 segundos' >... |
:rtype: str """ p = lambda n, s, p: p if n > 1 else s h, m, s = hms(segundos) tokens = [ '' if h == 0 else '{:d} {}'.format(h, p(h, 'hora', 'horas')), '' if m == 0 else '{:d} {}'.format(m, p(m, 'minuto', 'minutos')), '' if s == 0 else '{:d} {}'.format(s, p(s, 'segundo', 'segundos'))] tokens = [token for token in tokens |
if token] if len(tokens) == 1: return tokens[0] if len(tokens) > 1: return '{} e {}'.format(', '.join(tokens[:-1]), tokens[-1]) return 'zero segundos' |
def format_grib_name(self, selected_variable): """ Assigns name to grib2 message number with name 'unknown'. Names based on NOAA grib2 abbreviations. Args: selected_variable(str): name of selected variable for loading Names: 3: LCDC: Low Cloud Cover 4: MCDC: Medium Cloud Cover 5: HCDC: High Cloud Cover 197: RETOP: Echo... |
Helicity over Layer 2km to 5 km AGL, and 0km to 3km AGL examples:' MXUPHL_5000' or 'MXUPHL_3000' 200: MNUPHL: Hourly Minimum of Updraft Helicity at same levels of MXUPHL examples:' MNUPHL_5000' or 'MNUPHL_3000' 220: MAXUVV: Hourly Maximum of Upward Vertical Velocity in the lowest 400hPa 221: MAXDVV: Hourly Maximum of D... |
10m Wind Speed 223: MAXVW: V Component of Hourly Maximum 10m Wind Speed Returns: Given an uknown string name of a variable, returns the grib2 message Id and units of the variable, based on the self.unknown_name and self.unknown_units dictonaries above. Allows access of data values of unknown variable name, given the ID... |
if selected_variable == value: Id = key u = units[key] return Id, u |
def load_data(self): """ Loads data from grib2 file objects or list of grib2 file objects. Handles specific grib2 variable names and grib2 message numbers. Returns: Array of data loaded from files in (time, y, x) dimensions, Units """ file_objects = self.file_objects var = self.variable valid_date = self.valid_dates da... |
self.lon if self.sector_ind_path: inds_file = pd.read_csv(self.sector_ind_path+'sector_data_indices.csv') inds = inds_file.loc[:,'indices'] out_x = self.mapping_data["x"] if not file_objects: print() print("No {0} model runs on {1}".format(member,self.run_date)) print() units = None return self.data, units for f, file ... |
grib[var].units elif type(var) is str: if '_' in var: variable = var.split('_')[0] level = int(var.split('_')[1]) if variable in unknown_names.values(): Id, units = self.format_grib_name(variable) data_values = grib.select(parameterNumber=Id, level=level)[0].values #lat, lon = grib.select(parameterNumber=Id, level=leve... |
= grib.select(parameterNumber=Id)[0].values #lat, lon = grib.select(parameterNumber=Id)[0].latlons() #proj = Proj(grib.select(parameterNumber=Id)[0].projparams) elif len(grib.select(name=var)) > 1: raise NameError("Multiple '{0}' records found. Rename with level:'{0}_level'".format(var)) else: data_values = grib.select... |
def load_forecasts(self): """ Load the forecast files into memory. """ run_date_str = self.run_date.strftime("%Y%m%d") for model_name in self.model_names: self.raw_forecasts[model_name] = {} forecast_file = self.forecast_path + run_date_str + "/" + \ model_name.replace(" ", "-") + "_hailprobs_{0}_{1}.nc".format(self.en... |
def get_window_forecasts(self): """ Aggregate the forecasts within the specified time windows. """ for model_name in self.model_names: self.window_forecasts[model_name] = {} for size_threshold in self.size_thresholds: self.window_forecasts[model_name][size_threshold] = \ np.array([self.raw_forecasts[model_name][size_th... |
def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). :param mask_threshold: Values greater than the threshold are kept, others are masked. :return: """ start_date = self.run_date + timedelta(hours=self.start_hour) end_date = self.run_date + timedelta(hours=self.end_hour) mrms_gri... |
MRMSGrid(start_date, end_date, self.mask_variable, self.mrms_path) mask_grid.load_data() self.raw_obs[self.mask_variable] = np.where(mask_grid.data >= mask_threshold, 1, 0) self.window_obs[self.mask_variable] = np.array([self.raw_obs[self.mask_variable][sl].max(axis=0) for sl in self.hour_windows]) |
def dilate_obs(self, dilation_radius): """ Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: Number of times to dilate the grid. :return: """ for s in self.size_thresholds: self.dilated_obs[s] = np.zeros(self.window_obs[self.mrms_variable].shape) for t... |
def roc_curves(self, prob_thresholds): """ Generate ROC Curve objects for each machine learning model, size threshold, and time window. :param prob_thresholds: Probability thresholds for the ROC Curve :param dilation_radius: Number of times to dilate the observation grid. :return: a dictionary of DistributedROC objects... |
enumerate(self.hour_windows): hour_range = (hour_window.start, hour_window.stop) all_roc_curves[model_name][size_threshold][hour_range] = \ DistributedROC(prob_thresholds, 1) if self.obs_mask: all_roc_curves[model_name][size_threshold][hour_range].update( self.window_forecasts[model_name][size_threshold][h][ self.windo... |
def reliability_curves(self, prob_thresholds): """ Output reliability curves for each machine learning model, size threshold, and time window. :param prob_thresholds: :param dilation_radius: :return: """ all_rel_curves = {} for model_name in self.model_names: all_rel_curves[model_name] = {} for size_threshold in self.s... |
) else: all_rel_curves[model_name][size_threshold][hour_range].update( self.window_forecasts[model_name][size_threshold][h], self.dilated_obs[size_threshold][h] ) return all_rel_curves |
def load_map_coordinates(map_file): """ Loads map coordinates from netCDF or pickle file created by util.makeMapGrids. Args: map_file: Filename for the file containing coordinate information. Returns: Latitude and longitude grids as numpy arrays. """ if map_file[-4:] == ".pkl": map_data = pickle.load(open(map_file)) lo... |
= map_data.variables["XLAT"][0] return lon, lat |
def interpolate_mrms_day(start_date, variable, interp_type, mrms_path, map_filename, out_path): """ For a given day, this module interpolates hourly MRMS data to a specified latitude and longitude grid, and saves the interpolated grids to CF-compliant netCDF4 files. Args: start_date (datetime.datetime): Date of data be... |
files map_filename (str): Name of the map filename. Supports ARPS map file format and netCDF files containing latitude and longitude variables out_path (str): Path to location where interpolated netCDF4 files are saved. """ try: print(start_date, variable) end_date = start_date + timedelta(hours=23) mrms = MRMSGrid(sta... |
map_filename[-3:] == "txt": mapping_data = make_proj_grids(*read_ncar_map_file(map_filename)) mrms.interpolate_to_netcdf(mapping_data["lon"], mapping_data["lat"], out_path, interp_type=interp_type) else: lon, lat = load_map_coordinates(map_filename) mrms.interpolate_to_netcdf(lon, lat, out_path, interp_type=interp_type... |
def load_data(self): """ Loads data from MRMS GRIB2 files and handles compression duties if files are compressed. """ data = [] loaded_dates = [] loaded_indices = [] for t, timestamp in enumerate(self.all_dates): date_str = timestamp.date().strftime("%Y%m%d") full_path = self.path_start + date_str + "/" if self.variabl... |
file_dates: data_file = data_files[np.where(timestamp==file_dates)[0][0]] print(full_path + data_file) if data_file[-2:] == "gz": subprocess.call(["gunzip", full_path + data_file]) file_obj = Nio.open_file(full_path + data_file[:-3]) else: file_obj = Nio.open_file(full_path + data_file) var_name = sorted(file_obj.varia... |
+ data_file[:-3]]) else: subprocess.call(["gzip", full_path + data_file]) loaded_dates.append(timestamp) loaded_indices.append(t) if len(loaded_dates) > 0: self.loaded_dates = pd.DatetimeIndex(loaded_dates) self.data = np.ones((self.all_dates.shape[0], data[0].shape[0], data[0].shape[1])) * -9999 self.data[loaded_indic... |
def interpolate_grid(self, in_lon, in_lat): """ Interpolates MRMS data to a different grid using cubic bivariate splines """ out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1])) for d in range(self.data.shape[0]): print("Loading ", d, self.variable, self.start_date) if self.data[d].max() > -999: ... |
self.variable, self.start_date) flat_data = spline.ev(in_lat.ravel(), in_lon.ravel()) out_data[d] = flat_data.reshape(in_lon.shape) del spline else: print(d, " is missing") out_data[d] = -9999 return out_data |
def max_neighbor(self, in_lon, in_lat, radius=0.05): """ Finds the largest value within a given radius of a point on the interpolated grid. Args: in_lon: 2D array of longitude values in_lat: 2D array of latitude values radius: radius of influence for largest neighbor search in degrees Returns: Array of interpolated dat... |
out_indices[0].ravel() out_cols = out_indices[1].ravel() for d in range(self.data.shape[0]): nz_points = np.where(self.data[d] > 0) if len(nz_points[0]) > 0: nz_vals = self.data[d][nz_points] nz_rank = np.argsort(nz_vals) original_points = cKDTree(np.vstack((self.lat[nz_points[0][nz_rank]], self.lon[nz_points[1][nz_ran... |
def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00", interp_type="spline"): """ Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create separate directories for each variable if they are not already available. """ if interp_typ... |
OSError: print(out_path + self.variable + " already created") out_file = out_path + self.variable + "/" + "{0}_{1}_{2}.nc".format(self.variable, self.start_date.strftime("%Y%m%d-%H:%M"), self.end_date.strftime("%Y%m%d-%H:%M")) out_obj = Dataset(out_file, "w") out_obj.createDimension("time", out_data.shape[0]) out_obj.c... |
data_var.units = "dBZ" elif "Rotation" in self.variable: data_var.units = "s-1" else: data_var.units = "" out_lon = out_obj.createVariable("longitude", "f4", ("y", "x"), zlib=True) out_lon[:] = in_lon out_lon.units = "degrees_east" out_lat = out_obj.createVariable("latitude", "f4", ("y", "x"), zlib=True) out_lat[:] = i... |
def get_data_generator_by_id(hardware_source_id, sync=True): """ Return a generator for data. :param bool sync: whether to wait for current frame to finish then collect next frame NOTE: a new ndarray is created for each call. """ hardware_source = HardwareSourceManager().get_hardware_source_for_hardware_source_id(hardw... |
def parse_hardware_aliases_config_file(config_path): """ Parse config file for aliases and automatically register them. Returns True if alias file was found and parsed (successfully or unsuccessfully). Returns False if alias file was not found. Config file is a standard .ini file with a section """ if os.path.exists(co... |
config.get(section, "hardware_alias") display_name = config.get(section, "display_name") try: logging.info("Adding alias {:s} for device {:s}, display name: {:s} ".format(hardware_alias, device, display_name)) HardwareSourceManager().make_instrument_alias(device, hardware_alias, _(display_name)) except Exception as e: ... |
def make_instrument_alias(self, instrument_id, alias_instrument_id, display_name): """ Configure an alias. Callers can use the alias to refer to the instrument or hardware source. The alias should be lowercase, no spaces. The display name may be used to display alias to the user. Neither the original instrument or hard... |
hardware source id (lowercase, no spaces) :param str alias_instrument_id: the alias of the hardware source id (lowercase, no spaces) :param str display_name: the display name for the alias """ self.__aliases[alias_instrument_id] = (instrument_id, display_name) for f in self.aliases_updated: f() |
def update(self, data_and_metadata: DataAndMetadata.DataAndMetadata, state: str, sub_area, view_id) -> None: """Called from hardware source when new data arrives.""" self.__state = state self.__sub_area = sub_area hardware_source_id = self.__hardware_source.hardware_source_id channel_index = self.index channel_id = sel... |
if channel_name is not None: hardware_source_metadata["channel_name"] = channel_name if view_id: hardware_source_metadata["view_id"] = view_id metadata.setdefault("hardware_source", dict()).update(hardware_source_metadata) data = data_and_metadata.data master_data = self.__data_and_metadata.data if self.__data_and_meta... |
> 0 or left > 0 or bottom < data.shape[0] or right < data.shape[1]: master_data = numpy.copy(master_data) master_data[top:bottom, left:right] = data[top:bottom, left:right] else: master_data = numpy.copy(data) else: master_data = data # numpy.copy(data). assume data does not need a copy. data_descriptor = data_and_meta... |
metadata=metadata, timestamp=timestamp, data_descriptor=data_descriptor) self.__data_and_metadata = new_extended_data self.data_channel_updated_event.fire(new_extended_data) self.is_dirty = True |
def start(self): """Called from hardware source when data starts streaming.""" old_start_count = self.__start_count self.__start_count += 1 if old_start_count == 0: self.data_channel_start_event.fire() |
def connect_data_item_reference(self, data_item_reference): """Connect to the data item reference, creating a crop graphic if necessary. If the data item reference does not yet have an associated data item, add a listener and wait for the data item to be set, then connect. """ display_item = data_item_reference.display... |
ugh. recursive mess. self.__data_item_reference_changed_event_listener = data_item_reference.data_item_reference_changed_event.listen(data_item_reference_changed) |
def grab_earliest(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the earliest data from the buffer, blocking until one is available.""" timeout = timeout if timeout is not None else 10.0 with self.__buffer_lock: if len(self.__buffer) == 0: done_event = threading.Event() self.__done_... |
def grab_next(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the next data to finish from the buffer, blocking until one is available.""" with self.__buffer_lock: self.__buffer = list() return self.grab_latest(timeout) |
def grab_following(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the next data to start from the buffer, blocking until one is available.""" self.grab_next(timeout) return self.grab_next(timeout) |
def pause(self) -> None: """Pause recording. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.started: self.__state = DataChannelBuffer.State.paused |
def resume(self) -> None: """Resume recording after pause. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.paused: self.__state = DataChannelBuffer.State.started |
def nlargest(n, mapping): """ Takes a mapping and returns the n keys associated with the largest values in descending order. If the mapping has fewer than n items, all its keys are returned. Equivalent to: ``next(zip(*heapq.nlargest(mapping.items(), key=lambda x: x[1])))`` Returns ------- list of up to n keys from the ... |
for i in range(n): pq.additem(*next(it)) except StopIteration: pass try: while it: pq.pushpopitem(*next(it)) except StopIteration: pass out = list(pq.popkeys()) out.reverse() return out |
def fromkeys(cls, iterable, value, **kwargs): """ Return a new pqict mapping keys from an iterable to the same value. """ return cls(((k, value) for k in iterable), **kwargs) |
def copy(self): """ Return a shallow copy of a pqdict. """ return self.__class__(self, key=self._keyfn, precedes=self._precedes) |
def pop(self, key=__marker, default=__marker): """ If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` is not provided and ``key`` is not in the pqdict, raise a ``KeyError``. If ``key`` is not provided, remove the top item and return its key, or raise ``KeyError... |
# pq semantics: remove and return top *key* (value is discarded) if key is self.__marker: if not heap: raise KeyError('pqdict is empty') key = heap[0].key del self[key] return key # dict semantics: remove and return *value* mapped from key try: pos = position.pop(key) # raises KeyError except KeyError: if default is se... |
is not node_to_delete: heap[pos] = end position[end.key] = pos self._reheapify(pos) value = node_to_delete.value del node_to_delete return value |
def popitem(self): """ Remove and return the item with highest priority. Raises ``KeyError`` if pqdict is empty. """ heap = self._heap position = self._position try: end = heap.pop(-1) except IndexError: raise KeyError('pqdict is empty') if heap: node = heap[0] heap[0] = end position[end.key] = 0 self._sink(0) else: no... |
def topitem(self): """ Return the item with highest priority. Raises ``KeyError`` if pqdict is empty. """ try: node = self._heap[0] except IndexError: raise KeyError('pqdict is empty') return node.key, node.value |
def additem(self, key, value): """ Add a new item. Raises ``KeyError`` if key is already in the pqdict. """ if key in self._position: raise KeyError('%s is already in the queue' % repr(key)) self[key] = value |
def pushpopitem(self, key, value, node_factory=_Node): """ Equivalent to inserting a new item followed by removing the top priority item, but faster. Raises ``KeyError`` if the new key is already in the pqdict. """ heap = self._heap position = self._position precedes = self._precedes prio = self._keyfn(value) if self._... |
queue' % repr(key)) if heap and precedes(heap[0].prio, node.prio): node, heap[0] = heap[0], node position[key] = 0 del position[node.key] self._sink(0) return node.key, node.value |
def updateitem(self, key, new_val): """ Update the priority value of an existing item. Raises ``KeyError`` if key is not in the pqdict. """ if key not in self._position: raise KeyError(key) self[key] = new_val |
def replace_key(self, key, new_key): """ Replace the key of an existing heap node in place. Raises ``KeyError`` if the key to replace does not exist or if the new key is already in the pqdict. """ heap = self._heap position = self._position if new_key in self: raise KeyError('%s is already in the queue' % repr(new_key)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.