code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _solve_eigen(self, X, y, shrinkage): """Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduc...
Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduction (with optional shrinkage). Parameters ...
_solve_eigen
python
Jingkang50/OpenOOD
openood/postprocessors/mds_ensemble_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/mds_ensemble_postprocessor.py
MIT
def compute_channel_distances(mavs, features, eu_weight=0.5): """ Input: mavs (channel, C) features: (N, channel, C) Output: channel_distances: dict of distance distribution from MAV for each channel. """ eucos_dists, eu_dists, cos_dists = [], [], [] for channel, ...
Input: mavs (channel, C) features: (N, channel, C) Output: channel_distances: dict of distance distribution from MAV for each channel.
compute_channel_distances
python
Jingkang50/OpenOOD
openood/postprocessors/openmax_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/openmax_postprocessor.py
MIT
def fit_weibull(means, dists, categories, tailsize=20, distance_type='eucos'): """ Input: means (C, channel, C) dists (N_c, channel, C) * C Output: weibull_model : Perform EVT based analysis using tails of distances and save weibull model parameters for re-adj...
Input: means (C, channel, C) dists (N_c, channel, C) * C Output: weibull_model : Perform EVT based analysis using tails of distances and save weibull model parameters for re-adjusting softmax scores
fit_weibull
python
Jingkang50/OpenOOD
openood/postprocessors/openmax_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/openmax_postprocessor.py
MIT
def openmax(weibull_model, categories, input_score, eu_weight, alpha=10, distance_type='eucos'): """Re-calibrate scores via OpenMax layer Output: openmax probability and softmax probability """ nb_classes = len(categories) ranked_l...
Re-calibrate scores via OpenMax layer Output: openmax probability and softmax probability
openmax
python
Jingkang50/OpenOOD
openood/postprocessors/openmax_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/openmax_postprocessor.py
MIT
def update_distances(self, cluster_centers, only_new=True, reset_dist=False): """Update min distances given cluster centers. Args: cluster_centers: indices of cluster centers only_new: only calculate distance...
Update min distances given cluster centers. Args: cluster_centers: indices of cluster centers only_new: only calculate distance for newly selected points and update min_distances. rest_dist: whether to reset min_distances.
update_distances
python
Jingkang50/OpenOOD
openood/postprocessors/patchcore_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/patchcore_postprocessor.py
MIT
def select_batch_(self, model, already_selected, N, **kwargs): """Diversity promoting active learning method that greedily forms a batch to minimize the maximum distance to a cluster center among all unlabeled datapoints. Args: model: model with scikit-like API with decision_f...
Diversity promoting active learning method that greedily forms a batch to minimize the maximum distance to a cluster center among all unlabeled datapoints. Args: model: model with scikit-like API with decision_function implemented already_selected: index of datapoints alread...
select_batch_
python
Jingkang50/OpenOOD
openood/postprocessors/patchcore_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/patchcore_postprocessor.py
MIT
def kernel(feat, feat_t, prob, prob_t, split=2): """Kernel function (assume feature is normalized)""" size = ceil(len(feat_t) / split) rel_full = [] for i in range(split): feat_t_ = feat_t[i * size:(i + 1) * size] prob_t_ = prob_t[i * size:(i + 1) * size] with torch.no_grad(): ...
Kernel function (assume feature is normalized)
kernel
python
Jingkang50/OpenOOD
openood/postprocessors/relation_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/relation_postprocessor.py
MIT
def get_relation(feat, feat_t, prob, prob_t, pow=1, chunk=50, thres=0.03): """Get relation values (top-k and summation) Args: feat (torch.Tensor [N,D]): features of the source data feat_t (torch.Tensor [N',D]): features of the target data prob (torch.Tensor [N,C]): probabilty vectors of...
Get relation values (top-k and summation) Args: feat (torch.Tensor [N,D]): features of the source data feat_t (torch.Tensor [N',D]): features of the target data prob (torch.Tensor [N,C]): probabilty vectors of the source data prob_t (torch.Tensor [N',C]): probabilty vectors of the t...
get_relation
python
Jingkang50/OpenOOD
openood/postprocessors/relation_postprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/postprocessors/relation_postprocessor.py
MIT
def __call__(self, img): """ Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it. """ h = img.size(1) w = img.size(2) mask = np.ones((h, w), np.floa...
Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it.
__call__
python
Jingkang50/OpenOOD
openood/preprocessors/cutout_preprocessor.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/preprocessors/cutout_preprocessor.py
MIT
def get_similarity_matrix(outputs, chunk=2, multi_gpu=False): """Compute similarity matrix. - outputs: (B', d) tensor for B' = B * chunk - sim_matrix: (B', B') tensor """ if multi_gpu: outputs_gathered = [] for out in outputs.chunk(chunk): gather_t = [ t...
Compute similarity matrix. - outputs: (B', d) tensor for B' = B * chunk - sim_matrix: (B', B') tensor
get_similarity_matrix
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def Supervised_NT_xent(sim_matrix, labels, temperature=0.5, chunk=2, eps=1e-8, multi_gpu=False): """Compute NT_xent loss. - sim_matrix: (B', B') tensor for B' = B * chunk (first 2B are pos samples...
Compute NT_xent loss. - sim_matrix: (B', B') tensor for B' = B * chunk (first 2B are pos samples)
Supervised_NT_xent
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def __init__(self, size=None, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)): """Inception Crop size (tuple): size of forwarding image (C, W, H) scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped. """ sup...
Inception Crop size (tuple): size of forwarding image (C, W, H) scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped.
__init__
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def __init__(self): """ img_size : (int, int, int) Height and width must be powers of 2. E.g. (32, 32, 1) or (64, 128, 3). Last number indicates number of channels, e.g. 1 for grayscale or 3 for RGB """ super(HorizontalFlipLayer, self).__init__() ...
img_size : (int, int, int) Height and width must be powers of 2. E.g. (32, 32, 1) or (64, 128, 3). Last number indicates number of channels, e.g. 1 for grayscale or 3 for RGB
__init__
python
Jingkang50/OpenOOD
openood/trainers/csi_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/csi_trainer.py
MIT
def init_center_c(train_loader, net, eps=0.1): """Initialize hypersphere center c as the mean from an initial forward pass on the data.""" n_samples = 0 first_iter = True train_dataiter = iter(train_loader) net.eval() with torch.no_grad(): for train_step in tqdm(range(1, ...
Initialize hypersphere center c as the mean from an initial forward pass on the data.
init_center_c
python
Jingkang50/OpenOOD
openood/trainers/dsvdd_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/dsvdd_trainer.py
MIT
def prepare_mixup(batch, alpha=1.0, use_cuda=True): """Returns mixed inputs, pairs of targets, and lambda.""" if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = batch['data'].size()[0] if use_cuda: index = torch.randperm(batch_size).cuda() else: ...
Returns mixed inputs, pairs of targets, and lambda.
prepare_mixup
python
Jingkang50/OpenOOD
openood/trainers/mixup_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/mixup_trainer.py
MIT
def get_lr(step, dataset_size, base_lr=0.003): """Returns learning-rate for `step` or None at the end.""" supports = get_schedule(dataset_size) # Linear warmup if step < supports[0]: return base_lr * step / supports[0] # End of training elif step >= supports[-1]: return None ...
Returns learning-rate for `step` or None at the end.
get_lr
python
Jingkang50/OpenOOD
openood/trainers/mos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/mos_trainer.py
MIT
def mixup_data(x, y, lam): """Returns mixed inputs, pairs of targets, and lambda.""" indices = torch.randperm(x.shape[0]).to(x.device) mixed_x = lam * x + (1 - lam) * x[indices] y_a, y_b = y, y[indices] return mixed_x, y_a, y_b
Returns mixed inputs, pairs of targets, and lambda.
mixup_data
python
Jingkang50/OpenOOD
openood/trainers/mos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/mos_trainer.py
MIT
def topk(output, target, ks=(1, )): """Returns one boolean vector for each k, whether the target is within the output's top-k.""" _, pred = output.topk(max(ks), 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) return [correct[:k].max(0)[0] for k in ks]
Returns one boolean vector for each k, whether the target is within the output's top-k.
topk
python
Jingkang50/OpenOOD
openood/trainers/mos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/mos_trainer.py
MIT
def KNN_dis_search_distance(target, index, K=50, num_points=10, length=2000, depth=342): ''' data_point: Queue for searching k-th points target: the target of the searc...
data_point: Queue for searching k-th points target: the target of the search K
KNN_dis_search_distance
python
Jingkang50/OpenOOD
openood/trainers/npos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/npos_trainer.py
MIT
def KNN_dis_search_decrease( target, index, K=50, select=1, ): ''' data_point: Queue for searching k-th points target: the target of the search K ''' # Normalize the features target_norm = torch.norm(target, p=2, dim=1, keepdim=True) normed_target = target / target_norm ...
data_point: Queue for searching k-th points target: the target of the search K
KNN_dis_search_decrease
python
Jingkang50/OpenOOD
openood/trainers/npos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/npos_trainer.py
MIT
def mixup_data(x, y, alpha=1.0): """Returns mixed inputs, pairs of targets, and lambda.""" if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = x.size()[0] index = torch.randperm(batch_size).cuda() mixed_x = lam * x + (1 - lam) * x[index] y_a, y_b = y...
Returns mixed inputs, pairs of targets, and lambda.
mixup_data
python
Jingkang50/OpenOOD
openood/trainers/regmixup_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/regmixup_trainer.py
MIT
def preprocess_features(npdata, pca=256): """Preprocess an array of features. Args: npdata (np.array N * ndim): features to preprocess pca (int): dim of output Returns: np.array of dim N * pca: data PCA-reduced, whitened and L2-normalized """ _, ndim = npdata.shape npdata...
Preprocess an array of features. Args: npdata (np.array N * ndim): features to preprocess pca (int): dim of output Returns: np.array of dim N * pca: data PCA-reduced, whitened and L2-normalized
preprocess_features
python
Jingkang50/OpenOOD
openood/trainers/udg_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/udg_trainer.py
MIT
def run_kmeans(x, nmb_clusters, verbose=False): """Runs kmeans on 1 GPU. Args: x: data nmb_clusters (int): number of clusters Returns: list: ids of data in each cluster """ n_data, d = x.shape # faiss implementation of k-means clus = faiss.Clustering(d, nmb_clusters...
Runs kmeans on 1 GPU. Args: x: data nmb_clusters (int): number of clusters Returns: list: ids of data in each cluster
run_kmeans
python
Jingkang50/OpenOOD
openood/trainers/udg_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/udg_trainer.py
MIT
def cluster(self, data, verbose=True): """Performs k-means clustering. Args: x_data (np.array N * dim): data to cluster """ # PCA-reducing, whitening and L2-normalization xb = preprocess_features(data, pca=self.pca_dim) if np.isnan(xb).any(): row_...
Performs k-means clustering. Args: x_data (np.array N * dim): data to cluster
cluster
python
Jingkang50/OpenOOD
openood/trainers/udg_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/udg_trainer.py
MIT
def log_sum_exp(value, num_classes=10, dim=None, keepdim=False): """Numerically stable implementation of the operation.""" value.exp().sum(dim, keepdim).log() # TODO: torch.max(value, dim=None) threw an error at time of writing weight_energy = torch.nn.Linear(num_classes, 1).cuda() if dim is not No...
Numerically stable implementation of the operation.
log_sum_exp
python
Jingkang50/OpenOOD
openood/trainers/vos_trainer.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/trainers/vos_trainer.py
MIT
def get_local_rank() -> int: """ Returns: The rank of the current process within the local (per-machine) process group. """ if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 assert ( _LOCAL_PROCESS_GROUP is not None ), 'Local ...
Returns: The rank of the current process within the local (per-machine) process group.
get_local_rank
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def get_local_size() -> int: """ Returns: The size of the per-machine process group, i.e. the number of processes per machine. """ if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
get_local_size
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def synchronize(): """Helper function to synchronize (barrier) among all processes when using distributed training.""" if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return if dist.get_bac...
Helper function to synchronize (barrier) among all processes when using distributed training.
synchronize
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def _get_global_gloo_group(): """Return a process group based on gloo backend, containing all the ranks The result is cached.""" if dist.get_backend() == 'nccl': return dist.new_group(backend='gloo') else: return dist.group.WORLD
Return a process group based on gloo backend, containing all the ranks The result is cached.
_get_global_gloo_group
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def all_gather(data, group=None): """Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of ...
Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank
all_gather
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def gather(data, dst=0, group=None): """Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Re...
Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: on dst, a list of...
gather
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def shared_random_seed(): """ Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock. """ ints = np.random.randint(2**31) ...
Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock.
shared_random_seed
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def reduce_dict(input_dict, average=True): """Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average o...
Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average or sum Returns: a dict with the same k...
reduce_dict
python
Jingkang50/OpenOOD
openood/utils/comm.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/comm.py
MIT
def setup_config(config_process_order=('merge', 'parse_args', 'parse_refs')): """Parsing configuration files and command line augments. This method reads the command line to 1. extract and stack YAML config files, 2. collect modification in command line arguments, so that the finalized conf...
Parsing configuration files and command line augments. This method reads the command line to 1. extract and stack YAML config files, 2. collect modification in command line arguments, so that the finalized configuration file is generated. Note: The default arguments allow the follo...
setup_config
python
Jingkang50/OpenOOD
openood/utils/config.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/config.py
MIT
def launch( main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=(), timeout=DEFAULT_TIMEOUT, ): """Launch multi-gpu or distributed training. This function must be called on all machines involved in the training. It will spa...
Launch multi-gpu or distributed training. This function must be called on all machines involved in the training. It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine. Args: main_func: a function that will be called by `main_func(*args)` num_gpus_per_machine (i...
launch
python
Jingkang50/OpenOOD
openood/utils/launch.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/launch.py
MIT
def mkdir_if_missing(dirname): """Create dirname if it is missing.""" if not osp.exists(dirname): try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise
Create dirname if it is missing.
mkdir_if_missing
python
Jingkang50/OpenOOD
openood/utils/logger.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/logger.py
MIT
def setup_logger(config): """generate exp directory to save configs, logger, checkpoints, etc. Args: config: all configs of the experiment """ print('------------------ Config --------------------------', flush=True) print(config, flush=True) print(u'\u2500' * 70, flush=True) outpu...
generate exp directory to save configs, logger, checkpoints, etc. Args: config: all configs of the experiment
setup_logger
python
Jingkang50/OpenOOD
openood/utils/logger.py
https://github.com/Jingkang50/OpenOOD/blob/master/openood/utils/logger.py
MIT
async def maigret( username: str, site_dict: Dict[str, MaigretSite], logger, query_notify=None, proxy=None, tor_proxy=None, i2p_proxy=None, timeout=3, is_parsing_enabled=False, id_type="username", debug=False, forced=False, max_connections=100, no_progressbar=Fals...
Main search func Checks for existence of username on certain sites. Keyword Arguments: username -- Username string will be used for search. site_dict -- Dictionary containing sites data in MaigretSite objects. query_notify -- Object with base type of QueryNotif...
maigret
python
soxoj/maigret
maigret/checking.py
https://github.com/soxoj/maigret/blob/master/maigret/checking.py
MIT
def timeout_check(value): """Check Timeout Argument. Checks timeout for validity. Keyword Arguments: value -- Time in seconds to wait before timing out request. Return Value: Floating point number representing the time (in seconds) that should be used for the timeout. ...
Check Timeout Argument. Checks timeout for validity. Keyword Arguments: value -- Time in seconds to wait before timing out request. Return Value: Floating point number representing the time (in seconds) that should be used for the timeout. NOTE: Will raise an exception ...
timeout_check
python
soxoj/maigret
maigret/checking.py
https://github.com/soxoj/maigret/blob/master/maigret/checking.py
MIT
def notify_about_errors( search_results: QueryResultWrapper, query_notify, show_statistics=False ) -> List[Tuple]: """ Prepare error notifications in search results, text + symbol, to be displayed by notify object. Example: [ ("Too many errors of type "timeout" (50.0%)", "!") ("...
Prepare error notifications in search results, text + symbol, to be displayed by notify object. Example: [ ("Too many errors of type "timeout" (50.0%)", "!") ("Verbose error statistics:", "-") ]
notify_about_errors
python
soxoj/maigret
maigret/errors.py
https://github.com/soxoj/maigret/blob/master/maigret/errors.py
MIT
async def increment_progress(self, count): """Update progress by calling the provided progress function.""" if self.progress: if asyncio.iscoroutinefunction(self.progress): await self.progress(count) else: self.progress(count) await...
Update progress by calling the provided progress function.
increment_progress
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def worker(self): """Consume tasks from the queue and process them.""" while True: try: f, args, kwargs = self.queue.get_nowait() except asyncio.QueueEmpty: return query_future = f(*args, **kwargs) query_task = create...
Consume tasks from the queue and process them.
worker
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def _run(self, queries: Iterable[QueryDraft]): """Main runner function to execute tasks with progress tracking.""" self.results: List[Any] = [] queries_list = list(queries) min_workers = min(len(queries_list), self.workers_count) workers = [create_task_func()(self.worker())...
Main runner function to execute tasks with progress tracking.
_run
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def worker(self): """Process tasks from the queue and put results into the results queue.""" while True: task = await self.queue.get() if task is self._stop_signal: self.queue.task_done() break try: f, args, kwarg...
Process tasks from the queue and put results into the results queue.
worker
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
async def run(self, queries: Iterable[Callable[..., Any]]): """Run workers to process queries in parallel.""" start_time = time.time() # Add tasks to the queue for t in queries: await self.queue.put(t) # Create workers workers = [ asyncio.create_...
Run workers to process queries in parallel.
run
python
soxoj/maigret
maigret/executors.py
https://github.com/soxoj/maigret/blob/master/maigret/executors.py
MIT
def __init__( self, result=None, verbose=False, print_found_only=False, skip_check_errors=False, color=True, ): """Create Query Notify Print Object. Contains information about a specific method of notifying the results of a query. Key...
Create Query Notify Print Object. Contains information about a specific method of notifying the results of a query. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing resu...
__init__
python
soxoj/maigret
maigret/notify.py
https://github.com/soxoj/maigret/blob/master/maigret/notify.py
MIT
def start(self, message, id_type): """Notify Start. Will print the title to the standard output. Keyword Arguments: self -- This object. message -- String containing username that the series of queries are about...
Notify Start. Will print the title to the standard output. Keyword Arguments: self -- This object. message -- String containing username that the series of queries are about. Return Value: Nothing. ...
start
python
soxoj/maigret
maigret/notify.py
https://github.com/soxoj/maigret/blob/master/maigret/notify.py
MIT
def update(self, result, is_similar=False): """Notify Update. Will print the query result to the standard output. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing result...
Notify Update. Will print the query result to the standard output. Keyword Arguments: self -- This object. result -- Object of type QueryResult() containing results for this query. Return Value: Nothin...
update
python
soxoj/maigret
maigret/notify.py
https://github.com/soxoj/maigret/blob/master/maigret/notify.py
MIT
def __init__( self, username, site_name, site_url_user, status, ids_data=None, query_time=None, context=None, error=None, tags=[], ): """ Keyword Arguments: self -- This object. username...
Keyword Arguments: self -- This object. username -- String indicating username that query result was about. site_name -- String which identifies site. site_url_user -- String containing URL f...
__init__
python
soxoj/maigret
maigret/result.py
https://github.com/soxoj/maigret/blob/master/maigret/result.py
MIT
def __str__(self): """Convert Object To String. Keyword Arguments: self -- This object. Return Value: Nicely formatted string to get information about this object. """ status = str(self.status) if self.context is not None: #...
Convert Object To String. Keyword Arguments: self -- This object. Return Value: Nicely formatted string to get information about this object.
__str__
python
soxoj/maigret
maigret/result.py
https://github.com/soxoj/maigret/blob/master/maigret/result.py
MIT
def extract_id_from_url(self, url: str) -> Optional[Tuple[str, str]]: """ Extracts username from url. It's outdated, detects only a format of https://example.com/{username} """ if not self.url_regexp: return None match_groups = self.url_regexp.match(url) ...
Extracts username from url. It's outdated, detects only a format of https://example.com/{username}
extract_id_from_url
python
soxoj/maigret
maigret/sites.py
https://github.com/soxoj/maigret/blob/master/maigret/sites.py
MIT
def ranked_sites_dict( self, reverse=False, top=sys.maxsize, tags=[], names=[], disabled=True, id_type="username", ): """ Ranking and filtering of the sites list Args: reverse (bool, optional): Reverse the sorting order. De...
Ranking and filtering of the sites list Args: reverse (bool, optional): Reverse the sorting order. Defaults to False. top (int, optional): Maximum number of sites to return. Defaults to sys.maxsize. tags (list, optional): List of tags to filter sites by. Defaults to...
ranked_sites_dict
python
soxoj/maigret
maigret/sites.py
https://github.com/soxoj/maigret/blob/master/maigret/sites.py
MIT
def _format_top_items( self, title, items_dict, limit, is_markdown, valid_items=None ): """Helper method to format top items lists""" output = f"Top {limit} {title}:\n" for item, count in sorted(items_dict.items(), key=lambda x: x[1], reverse=True)[ :limit ]: ...
Helper method to format top items lists
_format_top_items
python
soxoj/maigret
maigret/sites.py
https://github.com/soxoj/maigret/blob/master/maigret/sites.py
MIT
def attribute(self, attribute_name, db=None, default=None): # type: (str, CanMatrix, typing.Any) -> typing.Any """Get Board unit attribute by its name. :param str attribute_name: attribute name. :param CanMatrix db: Optional database parameter to get global default attribute value. :pa...
Get Board unit attribute by its name. :param str attribute_name: attribute name. :param CanMatrix db: Optional database parameter to get global default attribute value. :param default: Default value if attribute doesn't exist. :return: Return the attribute value if found, else `default`...
attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_attribute(self, attribute, value): # type (attribute: str, value: typing.Any) -> None """ Add the Attribute to current ECU. If the attribute already exists, update the value. :param str attribute: Attribute name :param any value: Attribute value """ try: ...
Add the Attribute to current ECU. If the attribute already exists, update the value. :param str attribute: Attribute name :param any value: Attribute value
add_attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def attribute(self, attributeName, db=None, default=None): # type: (str, CanMatrix, typing.Any) -> typing.Any """Get any Signal attribute by its name. :param str attributeName: attribute name, can be mandatory (ex: start_bit, size) or optional (customer) attribute. :param CanMatrix db: ...
Get any Signal attribute by its name. :param str attributeName: attribute name, can be mandatory (ex: start_bit, size) or optional (customer) attribute. :param CanMatrix db: Optional database parameter to get global default attribute value. :param default: Default value if attribute doesn't exi...
attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_attribute(self, attribute, value): """ Add user defined attribute to the Signal. Update the value if the attribute already exists. :param str attribute: attribute name :param value: attribute value """ try: self.attributes[attribute] = str(value) ...
Add user defined attribute to the Signal. Update the value if the attribute already exists. :param str attribute: attribute name :param value: attribute value
add_attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_values(self, value, valueName): """ Add named Value Description to the Signal. :param int or str value: signal value (0xFF) :param str valueName: Human readable value description ("Init") """ if isinstance(value, defaultFloatFactory): self.values[valu...
Add named Value Description to the Signal. :param int or str value: signal value (0xFF) :param str valueName: Human readable value description ("Init")
add_values
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def set_startbit(self, start_bit, bitNumbering=None, startLittle=None): """ Set start_bit. bitNumbering is 1 for LSB0/LSBFirst, 0 for MSB0/MSBFirst. If bit numbering is consistent with byte order (little=LSB0, big=MSB0) (KCD, SYM), start bit unmodified. Otherwise reverse...
Set start_bit. bitNumbering is 1 for LSB0/LSBFirst, 0 for MSB0/MSBFirst. If bit numbering is consistent with byte order (little=LSB0, big=MSB0) (KCD, SYM), start bit unmodified. Otherwise reverse bit numbering. For DBC, ArXML (OSEK), both little endian and big endian us...
set_startbit
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def get_startbit(self, bit_numbering=None, start_little=None): """Get signal start bit. Handle byte and bit order.""" startBitInternal = self.start_bit # convert from big endian start bit at # start bit(msbit) to end bit(lsbit) if start_little is True and self.is_little_endian is...
Get signal start bit. Handle byte and bit order.
get_startbit
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calculate_raw_range(self): """Compute raw signal range based on Signal bit width and whether the Signal is signed or not. :return: Signal range, i.e. (0, 15) for unsigned 4 bit Signal or (-8, 7) for signed one. :rtype: tuple """ factory = ( self.float_factory ...
Compute raw signal range based on Signal bit width and whether the Signal is signed or not. :return: Signal range, i.e. (0, 15) for unsigned 4 bit Signal or (-8, 7) for signed one. :rtype: tuple
calculate_raw_range
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def set_min(self, min=None): # type: (canmatrix.types.OptionalPhysicalValue) -> canmatrix.types.OptionalPhysicalValue """Set minimal physical Signal value. :param min: minimal physical value. If None and enabled (`calc_min_for_none`), compute using `calc_min` """ self.min = min ...
Set minimal physical Signal value. :param min: minimal physical value. If None and enabled (`calc_min_for_none`), compute using `calc_min`
set_min
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calc_min(self): # type: () -> canmatrix.types.PhysicalValue """Compute minimal physical Signal value based on offset and factor and `calculate_raw_range`.""" rawMin = self.calculate_raw_range()[0] return self.offset + (self.float_factory(rawMin) * self.factor)
Compute minimal physical Signal value based on offset and factor and `calculate_raw_range`.
calc_min
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def set_max(self, max=None): # type: (canmatrix.types.OptionalPhysicalValue) -> canmatrix.types.OptionalPhysicalValue """Set maximal signal value. :param max: minimal physical value. If None and enabled (`calc_max_for_none`), compute using `calc_max` """ self.max = max ...
Set maximal signal value. :param max: minimal physical value. If None and enabled (`calc_max_for_none`), compute using `calc_max`
set_max
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calc_max(self): # type: () -> canmatrix.types.PhysicalValue """Compute maximal physical Signal value based on offset, factor and `calculate_raw_range`.""" rawMax = self.calculate_raw_range()[1] return self.offset + (self.float_factory(rawMax) * self.factor)
Compute maximal physical Signal value based on offset, factor and `calculate_raw_range`.
calc_max
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def phys2raw(self, value=None): # type: (canmatrix.types.OptionalPhysicalValue) -> canmatrix.types.RawValue """Return the raw value (= as is on CAN). :param value: (scaled) value compatible with `decimal` or value choice to encode :return: raw unscaled value as it appears on the bus ...
Return the raw value (= as is on CAN). :param value: (scaled) value compatible with `decimal` or value choice to encode :return: raw unscaled value as it appears on the bus :rtype: int or decimal.Decimal
phys2raw
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def raw2phys(self, value, decode_to_str=False): # type: (canmatrix.types.RawValue, bool) -> typing.Union[canmatrix.types.PhysicalValue, str] """Decode the given raw value (= as is on CAN). :param value: raw value compatible with `decimal`. :param bool decode_to_str: If True, try to get ...
Decode the given raw value (= as is on CAN). :param value: raw value compatible with `decimal`. :param bool decode_to_str: If True, try to get value representation as *string* ('Init' etc.) :return: physical value (scaled)
raw2phys
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def by_name(self, name): # type: (str) -> typing.Union[Signal, None] """ Find a Signal in the group by Signal name. :param str name: Signal name to find :return: signal contained in the group identified by name :rtype: Signal """ for test in self.signals: ...
Find a Signal in the group by Signal name. :param str name: Signal name to find :return: signal contained in the group identified by name :rtype: Signal
by_name
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def grouper(iterable, n, fillvalue=None): """Collect data into fixed-length chunks or blocks.""" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
Collect data into fixed-length chunks or blocks.
grouper
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def unpack_bitstring(length, is_float, is_signed, bits): # type: (int, bool, bool, typing.Any) -> typing.Union[float, int] """ returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_si...
returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return:
unpack_bitstring
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def pack_bitstring(length, is_float, value, signed): """ returns a value in bits :param length: length of signal in bits :param is_float: value is float :param value: value to encode :param signed: value is signed :return: """ if is_float: types = { 32: '>f', ...
returns a value in bits :param length: length of signal in bits :param is_float: value is float :param value: value to encode :param signed: value is signed :return:
pack_bitstring
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_signal(self, signal): # type: (Signal) -> Signal """ Add Signal to Pdu. :param Signal signal: Signal to be added. :return: the signal added. """ self.signals.append(signal) return self.signals[len(self.signals) - 1]
Add Signal to Pdu. :param Signal signal: Signal to be added. :return: the signal added.
add_signal
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_signal_group(self, Name: str, Id: int, signalNames: typing.Sequence[str], e2e_properties: typing.Optional[AutosarE2EProperties] = None) -> None: """Add new SignalGroup to the Frame. Add given signals ...
Add new SignalGroup to the Frame. Add given signals to the group. :param str Name: Group name :param int Id: Group id :param list of str signalNames: list of Signal names to add. Non existing names are ignored.
add_signal_group
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def signal_by_name(self, name): # type: (str) -> typing.Union[Signal, None] """ Get signal by name. :param str name: signal name to be found. :return: signal with given name or None if not found """ for signal in self.signals: if signal.name == name: ...
Get signal by name. :param str name: signal name to be found. :return: signal with given name or None if not found
signal_by_name
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def is_multiplexed(self): # type: () -> bool """Frame is multiplexed if at least one of its signals is a multiplexer.""" for sig in self.signals: if sig.is_multiplexer: return True return False
Frame is multiplexed if at least one of its signals is a multiplexer.
is_multiplexed
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def get_multiplexer(self): # type: () -> typing.Union[Signal, None] """get multiplexer signal if any in frame.""" for sig in self.signals: if sig.is_multiplexer: return sig return None
get multiplexer signal if any in frame.
get_multiplexer
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def get_signals_for_multiplexer_value(self, mux_value): # type: (int) -> typing.Sequence[Signal] """Find Frame Signals by given muxer value. :param int mux_value: muxer value :return: list of signals relevant for given muxer value. :rtype: list of signals """ muxe...
Find Frame Signals by given muxer value. :param int mux_value: muxer value :return: list of signals relevant for given muxer value. :rtype: list of signals
get_signals_for_multiplexer_value
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def effective_cycle_time(self): """Calculate effective cycle time for frame, depending on singal cycle times""" min_cycle_time_list = [y for y in [x.cycle_time for x in self.signals] + [self.cycle_time] if y != 0] if len(min_cycle_time_list) == 0: return 0 elif len(min_cycle_...
Calculate effective cycle time for frame, depending on singal cycle times
effective_cycle_time
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def attribute(self, attribute_name, db=None, default=None): # type: (str, typing.Optional[CanMatrix], typing.Any) -> typing.Any """Get any Frame attribute by its name. :param str attribute_name: attribute name, can be mandatory (ex: id) or optional (customer) attribute. :param CanMatrix...
Get any Frame attribute by its name. :param str attribute_name: attribute name, can be mandatory (ex: id) or optional (customer) attribute. :param CanMatrix db: Optional database parameter to get global default attribute value. :param default: Default value if attribute doesn't exist. :...
attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_signal_group(self, Name: str, Id: int, signalNames: typing.Sequence[str], e2e_properties: typing.Optional[AutosarE2EProperties] = None) -> None: """Add new SignalGroup to the Frame. Add given signals t...
Add new SignalGroup to the Frame. Add given signals to the group. :param str Name: Group name :param int Id: Group id :param list of str signalNames: list of Signal names to add. Non existing names are ignored.
add_signal_group
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def signal_group_by_name(self, name): # type: (str) -> typing.Union[SignalGroup, None] """Get signal group. :param str name: group name :return: SignalGroup by name or None if not found. :rtype: SignalGroup """ for signalGroup in self.signalGroups: if...
Get signal group. :param str name: group name :return: SignalGroup by name or None if not found. :rtype: SignalGroup
signal_group_by_name
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_pdu(self, pdu): # type: (Pdu) -> Pdu """ Add Pdu to Frame. :param Pdu pdu: Pdu to be added. :return: the pdu added. """ self.pdus.append(pdu) return self.pdus[len(self.pdus) - 1]
Add Pdu to Frame. :param Pdu pdu: Pdu to be added. :return: the pdu added.
add_pdu
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def pdu_by_name(self, name): # type: (str) -> typing.Union[Pdu, None] """Get PDU. :param str name: PDU name :return: PDU by name or None if not found. :rtype: Pdu """ for pdu in self.pdus: if pdu.name == name: return pdu return...
Get PDU. :param str name: PDU name :return: PDU by name or None if not found. :rtype: Pdu
pdu_by_name
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def pdu_by_id(self, pdu_id): # type: (int) -> typing.Union[Pdu, None] """Get PDU. :param int pdu_id: PDU id :return: PDU by id or None if not found. :rtype: Pdu """ for pdu in self.pdus: if pdu.id == pdu_id: return pdu return N...
Get PDU. :param int pdu_id: PDU id :return: PDU by id or None if not found. :rtype: Pdu
pdu_by_id
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_signal(self, signal): # type: (Signal) -> Signal """ Add Signal to Frame. :param Signal signal: Signal to be added. :return: the signal added. """ self.signals.append(signal) return self.signals[len(self.signals) - 1]
Add Signal to Frame. :param Signal signal: Signal to be added. :return: the signal added.
add_signal
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_receiver(self, receiver): # type: (str) -> None """Add receiver ECU Name to Frame. :param str receiver: receiver name """ if receiver not in self.receivers: self.receivers.append(receiver)
Add receiver ECU Name to Frame. :param str receiver: receiver name
add_receiver
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def signal_by_name(self, name): # type: (str) -> typing.Union[Signal, None] """ Get signal by name. :param str name: signal name to be found. :return: signal with given name or None if not found """ for signal in self.signals: if signal.name == name: ...
Get signal by name. :param str name: signal name to be found. :return: signal with given name or None if not found
signal_by_name
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def glob_signals(self, glob_str): # type: (str) -> typing.Sequence[Signal] """Find Frame Signals by given glob pattern. :param str glob_str: glob pattern for signal name. See `fnmatch.fnmatchcase` :return: list of Signals by glob pattern. :rtype: list of Signal """ ...
Find Frame Signals by given glob pattern. :param str glob_str: glob pattern for signal name. See `fnmatch.fnmatchcase` :return: list of Signals by glob pattern. :rtype: list of Signal
glob_signals
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_attribute(self, attribute, value): # type: (str, typing.Any) -> None """ Add the attribute with value to customer Frame attribute-list. If Attribute already exits, modify its value. :param str attribute: Attribute name :param any value: attribute value """ ...
Add the attribute with value to customer Frame attribute-list. If Attribute already exits, modify its value. :param str attribute: Attribute name :param any value: attribute value
add_attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def del_attribute(self, attribute): # type: (str) -> typing.Any """ Remove attribute from customer Frame attribute-list. :param str attribute: Attribute name """ if attribute in self.attributes: del self.attributes[attribute]
Remove attribute from customer Frame attribute-list. :param str attribute: Attribute name
del_attribute
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def add_comment(self, comment): # type: (str) -> None """ Set Frame comment. :param str comment: Frame comment """ self.comment = comment
Set Frame comment. :param str comment: Frame comment
add_comment
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def calc_dlc(self): # type: () -> None """ Compute minimal Frame DLC (length) based on its Signals :return: Message DLC """ max_bit = 0 for sig in self.signals: if sig.get_startbit() + int(sig.size) > max_bit: max_bit = sig.get_startbi...
Compute minimal Frame DLC (length) based on its Signals :return: Message DLC
calc_dlc
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def fit_dlc(self): """ Compute next allowed DLC (length) for current Frame """ max_byte = self.size last_size = 8 for max_size in [12, 16, 20, 24, 32, 48, 64]: if max_byte > last_size and max_byte < max_size: self.size = max_size ...
Compute next allowed DLC (length) for current Frame
fit_dlc
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def get_frame_layout(self): # type: () -> typing.Sequence[typing.Sequence[str]] """ get layout of frame. Represents the bit usage in the frame by means of a list with n items (n bits of frame length). Every item represents one bit and contains a list of signals (object refs) wit...
get layout of frame. Represents the bit usage in the frame by means of a list with n items (n bits of frame length). Every item represents one bit and contains a list of signals (object refs) with each signal, occupying that bit. Bits with empty list are unused. Example: [[], ...
get_frame_layout
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def create_dummy_signals(self): # type: () -> None """Create big-endian dummy signals for unused bits. Names of dummy signals are *_Dummy_<frame.name>_<index>* """ bitfield = self.get_frame_layout() startBit = -1 sigCount = 0 for index, bit_signals in enumerate(...
Create big-endian dummy signals for unused bits. Names of dummy signals are *_Dummy_<frame.name>_<index>*
create_dummy_signals
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def update_receiver(self): # type: () -> None """ Collect Frame receivers out of receiver given in each signal. Add them to `self.receiver` list. """ self.receivers = [] for sig in self.signals: for receiver in sig.receivers: self.add_receiver(receive...
Collect Frame receivers out of receiver given in each signal. Add them to `self.receiver` list.
update_receiver
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def signals_to_bytes(self, data): # type: (typing.Mapping[str, canmatrix.types.RawValue]) -> bytes """Return a byte string containing the values from data packed according to the frame format. :param data: data dictionary of signal : rawValue :return: A byte string of the packed...
Return a byte string containing the values from data packed according to the frame format. :param data: data dictionary of signal : rawValue :return: A byte string of the packed values.
signals_to_bytes
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def encode(self, data=None): # type: (typing.Optional[typing.Mapping[str, typing.Any]]) -> bytes """Return a byte string containing the values from data packed according to the frame format. :param dict data: data dictionary :return: A byte string of the packed values. "...
Return a byte string containing the values from data packed according to the frame format. :param dict data: data dictionary :return: A byte string of the packed values.
encode
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def bytes_to_bitstrings(data): # type: (bytes) -> typing.Tuple[str, str] """Return two arrays big and little containing bits of given data (bytearray) :param data: bytearray of bits (little endian). i.e. bytearray([0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8]) :return: bi...
Return two arrays big and little containing bits of given data (bytearray) :param data: bytearray of bits (little endian). i.e. bytearray([0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8]) :return: bit arrays in big and little byteorder
bytes_to_bitstrings
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause
def bitstring_to_signal_list(signals, big, little, size): # type: (typing.Sequence[Signal], str, str, int) -> typing.Sequence[canmatrix.types.RawValue] """Return OrderedDictionary with Signal Name: object decodedSignal (flat / without support for multiplexed frames) :param signals: Iterable of ...
Return OrderedDictionary with Signal Name: object decodedSignal (flat / without support for multiplexed frames) :param signals: Iterable of signals (class signal) to decode from frame. :param big: bytearray of bits (big endian). :param little: bytearray of bits (little endian). :param s...
bitstring_to_signal_list
python
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/canmatrix.py
BSD-2-Clause