INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Create a new data item with computation specified by processing_id inputs and region_list_map. | def __make_computation(self, processing_id: str, inputs: typing.List[typing.Tuple[DisplayItem.DisplayItem, typing.Optional[Graphics.Graphic]]], region_list_map: typing.Mapping[str, typing.List[Graphics.Graphic]]=None, parameters: typing.Mapping[str, typing.Any]=None) -> DataItem.DataItem:
"""Create a new data i... |
Creates a color map for values in array: param array: color map to interpolate: param x: number of colors: return: interpolated color map | def interpolate_colors(array: numpy.ndarray, x: int) -> numpy.ndarray:
"""
Creates a color map for values in array
:param array: color map to interpolate
:param x: number of colors
:return: interpolated color map
"""
out_array = []
for i in range(x):
if i % (x / (len(array) - 1))... |
star any gist by providing gistID or gistname ( for authenticated user ) | def star(self, **args):
'''
star any gist by providing gistID or gistname(for authenticated user)
'''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Either provide authenticated user... |
fork any gist by providing gistID or gistname ( for authenticated user ) | def fork(self, **args):
'''
fork any gist by providing gistID or gistname(for authenticated user)
'''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Either provide authenticated user... |
Check a gist if starred by providing gistID or gistname ( for authenticated user ) | def checkifstar(self, **args):
'''
Check a gist if starred by providing gistID or gistname(for authenticated user)
'''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Either provide ... |
Salva o arquivo de log decodificado. | def salvar(self, destino=None, prefix='tmp', suffix='-sat.log'):
"""Salva o arquivo de log decodificado.
:param str destino: (Opcional) Caminho completo para o arquivo onde os
dados dos logs deverão ser salvos. Se não informado, será criado
um arquivo temporário via :func:`tempf... |
Constrói uma: class: RespostaExtrairLogs a partir do retorno informado. | def analisar(retorno):
"""Constrói uma :class:`RespostaExtrairLogs` a partir do retorno
informado.
:param unicode retorno: Retorno da função ``ExtrairLogs``.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='ExtrairLogs',
classe_res... |
Loads time series of 2D data grids from each opened file. The code handles loading a full time series from one file or individual time steps from multiple files. Missing files are supported. | def load_data_old(self):
"""
Loads time series of 2D data grids from each opened file. The code
handles loading a full time series from one file or individual time steps
from multiple files. Missing files are supported.
"""
units = ""
if len(self.file_objects) ==... |
Load data from netCDF file objects or list of netCDF file objects. Handles special variable name formats. | def load_data(self):
"""
Load data from netCDF file objects or list of netCDF file objects. Handles special variable name formats.
Returns:
Array of data loaded from files in (time, y, x) dimensions, Units
"""
units = ""
if self.file_objects[0] is None:
... |
Searches var list for variable name checks other variable name format options. | def format_var_name(variable, var_list):
"""
Searches var list for variable name, checks other variable name format options.
Args:
variable (str): Variable being loaded
var_list (list): List of variables in file.
Returns:
Name of variable in file con... |
Load data from flat data files containing total track information and information about each timestep. The two sets are combined using merge operations on the Track IDs. Additional member information is gathered from the appropriate member file. Args: mode: train or forecast format: file format being used. Default is c... | def load_data(self, mode="train", format="csv"):
"""
Load data from flat data files containing total track information and information about each timestep.
The two sets are combined using merge operations on the Track IDs. Additional member information is gathered
from the appropriate me... |
Calculate a copula multivariate normal distribution from the training data for each group of ensemble members. Distributions are written to a pickle file for later use. Args: output_file: Pickle file model_names: Names of the tracking models label_columns: Names of the data columns used for labeling Returns: | def calc_copulas(self,
output_file,
model_names=("start-time", "translation-x", "translation-y"),
label_columns=("Start_Time_Error", "Translation_Error_X", "Translation_Error_Y")):
"""
Calculate a copula multivariate normal distribution from... |
Fit machine learning models to predict whether or not hail will occur. Args: model_names: List of strings with the names for the particular machine learning models model_objs: scikit - learn style machine learning model objects. input_columns: list of the names of the columns used as input for the machine learning mode... | def fit_condition_models(self, model_names,
model_objs,
input_columns,
output_column="Matched",
output_threshold=0.0):
"""
Fit machine learning models to predict whether or not hail will o... |
Fit models to predict hail/ no - hail and use cross - validation to determine the probaility threshold that maximizes a skill score. | def fit_condition_threshold_models(self, model_names, model_objs, input_columns, output_column="Matched",
output_threshold=0.5, num_folds=5, threshold_score="ets"):
"""
Fit models to predict hail/no-hail and use cross-validation to determine the probaility threshol... |
Apply condition modelsto forecast data. Args: model_names: List of names associated with each condition model used for prediction input_columns: List of columns in data used as input into the model metadata_cols: Columns from input data that should be included in the data frame with the predictions. data_mode: Which da... | def predict_condition_models(self, model_names,
input_columns,
metadata_cols,
data_mode="forecast",
):
"""
Apply condition modelsto forecast data.
Args:
... |
Fits multitask machine learning models to predict the parameters of a size distribution Args: model_names: List of machine learning model names model_objs: scikit - learn style machine learning model objects input_columns: Training data columns used as input for ML model output_columns: Training data columns used for p... | def fit_size_distribution_models(self, model_names, model_objs, input_columns,
output_columns=None, calibrate=False):
"""
Fits multitask machine learning models to predict the parameters of a size distribution
Args:
model_names: List of machine le... |
This calculates 2 principal components for the hail size distribution between the shape and scale parameters. Separate machine learning models are fit to predict each component. | def fit_size_distribution_component_models(self, model_names, model_objs, input_columns, output_columns):
"""
This calculates 2 principal components for the hail size distribution between the shape and scale parameters.
Separate machine learning models are fit to predict each component.
... |
Make predictions using fitted size distribution models. Args: model_names: Name of the models for predictions input_columns: Data columns used for input into ML models metadata_cols: Columns from input data that should be included in the data frame with the predictions. data_mode: Set of data used as input for predicti... | def predict_size_distribution_models(self, model_names, input_columns, metadata_cols,
data_mode="forecast", location=6, calibrate=False):
"""
Make predictions using fitted size distribution models.
Args:
model_names: Name of the models for pre... |
Make predictions using fitted size distribution models. Args: model_names: Name of the models for predictions input_columns: Data columns used for input into ML models output_columns: Names of output columns metadata_cols: Columns from input data that should be included in the data frame with the predictions. data_mode... | def predict_size_distribution_component_models(self, model_names, input_columns, output_columns, metadata_cols,
data_mode="forecast", location=6):
"""
Make predictions using fitted size distribution models.
Args:
model_names: Name of... |
Fit size models to produce discrete pdfs of forecast hail sizes. Args: model_names: List of model names model_objs: List of model objects input_columns: List of input variables output_column: Output variable name output_start: Hail size bin start output_step: hail size bin step output_stop: hail size bin stop | def fit_size_models(self, model_names,
model_objs,
input_columns,
output_column="Hail_Size",
output_start=5,
output_step=5,
output_stop=100):
"""
Fit size model... |
Apply size models to forecast data. Args: model_names: input_columns: metadata_cols: data_mode: | def predict_size_models(self, model_names,
input_columns,
metadata_cols,
data_mode="forecast"):
"""
Apply size models to forecast data.
Args:
model_names:
input_columns:
metada... |
Fit machine learning models to predict track error offsets. model_names: model_objs: input_columns: output_columns: output_ranges: | def fit_track_models(self,
model_names,
model_objs,
input_columns,
output_columns,
output_ranges,
):
"""
Fit machine learning models to predict track erro... |
Save machine learning models to pickle files. | def save_models(self, model_path):
"""
Save machine learning models to pickle files.
"""
for group, condition_model_set in self.condition_models.items():
for model_name, model_obj in condition_model_set.items():
out_filename = model_path + \
... |
Load models from pickle files. | def load_models(self, model_path):
"""
Load models from pickle files.
"""
condition_model_files = sorted(glob(model_path + "*_condition.pkl"))
if len(condition_model_files) > 0:
for condition_model_file in condition_model_files:
model_comps = condition... |
Output forecast values to geoJSON file format.: param forecasts:: param condition_model_names:: param size_model_names:: param track_model_names:: param json_data_path:: param out_path:: return: | def output_forecasts_json(self, forecasts,
condition_model_names,
size_model_names,
dist_model_names,
track_model_names,
json_data_path,
out... |
Output hail forecast values to csv files by run date and ensemble member. | def output_forecasts_csv(self, forecasts, mode, csv_path, run_date_format="%Y%m%d-%H%M"):
"""
Output hail forecast values to csv files by run date and ensemble member.
Args:
forecasts:
mode:
csv_path:
Returns:
"""
merged_forecasts = pd... |
Carrega ( ou recarrega ) a biblioteca SAT. Se a convenção de chamada ainda não tiver sido definida será determinada pela extensão do arquivo da biblioteca. | def _carregar(self):
"""Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada
ainda não tiver sido definida, será determinada pela extensão do
arquivo da biblioteca.
:raises ValueError: Se a convenção de chamada não puder ser determinada
ou se não for um valor v... |
Função AtivarSAT conforme ER SAT item 6. 1. 1. Ativação do equipamento SAT. Dependendo do tipo do certificado o procedimento de ativação é complementado enviando - se o certificado emitido pela ICP - Brasil (: meth: comunicar_certificado_icpbrasil ). | def ativar_sat(self, tipo_certificado, cnpj, codigo_uf):
"""Função ``AtivarSAT`` conforme ER SAT, item 6.1.1.
Ativação do equipamento SAT. Dependendo do tipo do certificado, o
procedimento de ativação é complementado enviando-se o certificado
emitido pela ICP-Brasil (:meth:`comunicar_cer... |
Função ComunicarCertificadoICPBRASIL conforme ER SAT item 6. 1. 2. Envio do certificado criado pela ICP - Brasil. | 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.
... |
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. | 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 str... |
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. | 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... |
Função ConsultarNumeroSessao conforme ER SAT item 6. 1. 8. Consulta o equipamento SAT por um número de sessão específico. | 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 ConfigurarInterfaceDeRede conforme ER SAT item 6. 1. 9. Configurção da interface de comunicação do equipamento SAT. | 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 XM... |
Função AssociarAssinatura conforme ER SAT item 6. 1. 10. Associação da assinatura do aplicativo comercial. | 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 e... |
Função TrocarCodigoDeAtivacao conforme ER SAT item 6. 1. 15. Troca do código de ativação do equipamento SAT. | 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... |
Loads the forecast files and gathers the forecast information into pandas DataFrames. | 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... |
Loads the track total and step files and merges the information into a single data frame. | 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... |
Match forecasts and observations. | 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(sel... |
Calculates the cumulative ranked probability score ( CRPS ) on the forecast data. | 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 evalu... |
Calculates a ROC curve at a specified intensity threshold. | 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
... |
Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes. | 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 ... |
Get signature and params | 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:
... |
Retorna o número de horas minutos e segundos a partir do total de segundos informado. | 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)
... |
Retorna um texto legível que descreve o total de horas minutos e segundos calculados a partir do total de segundos informados. | 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)
... |
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 Top 198: MAXREF: Hourly Maximum of Simulated Refl... | 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:... |
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 | 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_... |
Load the forecast files into memory. | 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 + "/" + \
... |
Aggregate the forecasts within the specified time windows. | 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_na... |
Loads observations and masking grid ( if needed ). | 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... |
Use a dilation filter to grow positive observation areas by a specified number of grid points | 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... |
Generate ROC Curve objects for each machine learning model size threshold and time window. | 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.
:retur... |
Output reliability curves for each machine learning model size threshold and time window. | 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_na... |
Loads map coordinates from netCDF or pickle file created by util. makeMapGrids. | 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":... |
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 being interpolated variable ( str ): MRMS variable interp_type ( str ): Whether to use maximum neig... | 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 (datet... |
Loads data from MRMS GRIB2 files and handles compression duties if files are compressed. | 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("%... |
Interpolates MRMS data to a different grid using cubic bivariate splines | 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.varia... |
Finds the largest value within a given radius of a point on the interpolated grid. | 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 ... |
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. | 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 variab... |
Return a generator for data. | 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_hardwa... |
Parse config file for aliases and automatically register them. | 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 ... |
Configure an alias. | 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 ... |
Called from hardware source when new data arrives. | 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
ch... |
Called from hardware source when data starts streaming. | 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() |
Connect to the data item reference creating a crop graphic if necessary. | 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.
"""
d... |
Grab the earliest data from the buffer blocking until one is available. | 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:
... |
Grab the next data to finish from the buffer blocking until one is available. | 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) |
Grab the next data to start from the buffer blocking until one is available. | 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) |
Pause recording. | 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 |
Resume recording after pause. | 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 |
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. | 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
... |
Return a new pqict mapping keys from an iterable to the same value. | 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) |
Return a shallow copy of a pqdict. | def copy(self):
"""
Return a shallow copy of a pqdict.
"""
return self.__class__(self, key=self._keyfn, precedes=self._precedes) |
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. | 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 ite... |
Remove and return the item with highest priority. Raises KeyError if pqdict is empty. | 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 ... |
Return the item with highest priority. Raises KeyError if pqdict is empty. | 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 |
Add a new item. Raises KeyError if key is already in the pqdict. | 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 |
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. | 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
... |
Update the priority value of an existing item. Raises KeyError if key is not in the pqdict. | 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 |
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. | 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 ... |
Fast way to swap the priority level of two items in the pqdict. Raises KeyError if either key does not exist. | def swap_priority(self, key1, key2):
"""
Fast way to swap the priority level of two items in the pqdict. Raises
``KeyError`` if either key does not exist.
"""
heap = self._heap
position = self._position
if key1 not in self or key2 not in self:
raise K... |
Repair a broken heap. If the state of an item s priority value changes you can re - sort the relevant item only by providing key. | def heapify(self, key=__marker):
"""
Repair a broken heap. If the state of an item's priority value changes
you can re-sort the relevant item only by providing ``key``.
"""
if key is self.__marker:
n = len(self._heap)
for pos in reversed(range(n//2)):
... |
Check to make sure _version. py is contained in the package | def package_has_version_file(package_name):
""" Check to make sure _version.py is contained in the package """
version_file_path = helpers.package_file_path('_version.py', package_name)
return os.path.isfile(version_file_path) |
Grab the project name out of setup. py | def get_project_name():
""" Grab the project name out of setup.py """
setup_py_content = helpers.get_file_content('setup.py')
ret = helpers.value_of_named_argument_in_function(
'name', 'setup', setup_py_content, resolve_varname=True
)
if ret and ret[0] == ret[-1] in ('"', "'"):
ret =... |
Get the version which is currently configured by the package | def get_version(package_name, ignore_cache=False):
""" Get the version which is currently configured by the package """
if ignore_cache:
with microcache.temporarily_disabled():
found = helpers.regex_in_package_file(
VERSION_SET_REGEX, '_version.py', package_name, return_match... |
Set the version in _version. py to version_str | def set_version(package_name, version_str):
""" Set the version in _version.py to version_str """
current_version = get_version(package_name)
version_file_path = helpers.package_file_path('_version.py', package_name)
version_file_content = helpers.get_file_content(version_file_path)
version_file_con... |
Check to see if the version specified is a valid as far as pkg_resources is concerned | def version_is_valid(version_str):
""" Check to see if the version specified is a valid as far as pkg_resources is concerned
>>> version_is_valid('blah')
False
>>> version_is_valid('1.2.3')
True
"""
try:
packaging.version.Version(version_str)
except packaging.version.InvalidVers... |
Query the pypi index at index_url using warehouse api to find all of the releases | def _get_uploaded_versions_warehouse(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using warehouse api to find all of the "releases" """
url = '/'.join((index_url, project_name, 'json'))
response = requests.get(url, verify=requests_verify)
if response.status_code ... |
Query the pypi index at index_url using pypicloud api to find all versions | def _get_uploaded_versions_pypicloud(project_name, index_url, requests_verify=True):
""" Query the pypi index at index_url using pypicloud api to find all versions """
api_url = index_url
for suffix in ('/pypi', '/pypi/', '/simple', '/simple/'):
if api_url.endswith(suffix):
api_url = api... |
Check to see if the version specified has already been uploaded to the configured index | def version_already_uploaded(project_name, version_str, index_url, requests_verify=True):
""" Check to see if the version specified has already been uploaded to the configured index
"""
all_versions = _get_uploaded_versions(project_name, index_url, requests_verify)
return version_str in all_versions |
Attempt to convert a README. md file into README. rst | def convert_readme_to_rst():
""" Attempt to convert a README.md file into README.rst """
project_files = os.listdir('.')
for filename in project_files:
if filename.lower() == 'readme':
raise ProjectError(
'found {} in project directory...'.format(filename) +
... |
Collect relative paths to all files which have already been packaged | def get_packaged_files(package_name):
""" Collect relative paths to all files which have already been packaged """
if not os.path.isdir('dist'):
return []
return [os.path.join('dist', filename) for filename in os.listdir('dist')] |
Look through built package directory and see if there are multiple versions there | def multiple_packaged_versions(package_name):
""" Look through built package directory and see if there are multiple versions there """
dist_files = os.listdir('dist')
versions = set()
for filename in dist_files:
version = funcy.re_find(r'{}-(.+).tar.gz'.format(package_name), filename)
i... |
Calculate the neighborhood probability over the full period of the forecast | def period_neighborhood_probability(self, radius, smoothing, threshold, stride,start_time,end_time):
"""
Calculate the neighborhood probability over the full period of the forecast
Args:
radius: circular radius from each point in km
smoothing: width of Gaussian smoother ... |
Constrói uma: class: RespostaSAT ou especialização dependendo da função SAT encontrada na sessão consultada. | def analisar(retorno):
"""Constrói uma :class:`RespostaSAT` ou especialização dependendo da
função SAT encontrada na sessão consultada.
:param unicode retorno: Retorno da função ``ConsultarNumeroSessao``.
"""
if '|' not in retorno:
raise ErroRespostaSATInvalida('Resp... |
Analisa o retorno ( supostamente um retorno de uma função do SAT ) conforme o padrão e campos esperados. O retorno deverá possuir dados separados entre si através de pipes e o número de campos deverá coincidir com os campos especificados. | def analisar_retorno(retorno,
classe_resposta=RespostaSAT, campos=RespostaSAT.CAMPOS,
campos_alternativos=[], funcao=None, manter_verbatim=True):
"""Analisa o retorno (supostamente um retorno de uma função do SAT) conforme
o padrão e campos esperados. O retorno deverá possuir dados separados ent... |
Constrói uma: class: RespostaSAT para o retorno ( unicode ) da função: meth: ~satcfe. base. FuncoesSAT. comunicar_certificado_icpbrasil. | def comunicar_certificado_icpbrasil(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='ComunicarCertificadoICPB... |
Constrói uma: class: RespostaSAT para o retorno ( unicode ) da função: meth: ~satcfe. base. FuncoesSAT. consultar_sat. | def consultar_sat(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='ConsultarSAT')
if resposta.EEEEE not in ('08000',):
... |
Constrói uma: class: RespostaSAT para o retorno ( unicode ) da função: meth: ~satcfe. base. FuncoesSAT. configurar_interface_de_rede. | def configurar_interface_de_rede(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='ConfigurarInterfaceDeRede')
... |
Constrói uma: class: RespostaSAT para o retorno ( unicode ) da função: meth: ~satcfe. base. FuncoesSAT. associar_assinatura. | def associar_assinatura(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.associar_assinatura`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='AssociarAssinatura')
if resposta.EEEEE n... |
Constrói uma: class: RespostaSAT para o retorno ( unicode ) da função: meth: ~satcfe. base. FuncoesSAT. atualizar_software_sat. | def atualizar_software_sat(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='AtualizarSoftwareSAT')
if resposta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.