hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
958k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f72c4d0057651aa215322c6c946998d0af458554
753
py
Python
merge_intervals.py
gvalleru/interview_q_py3
5ca71ec603610a4dc7baeb9c429b852d97ae3cb9
[ "Apache-2.0" ]
null
null
null
merge_intervals.py
gvalleru/interview_q_py3
5ca71ec603610a4dc7baeb9c429b852d97ae3cb9
[ "Apache-2.0" ]
null
null
null
merge_intervals.py
gvalleru/interview_q_py3
5ca71ec603610a4dc7baeb9c429b852d97ae3cb9
[ "Apache-2.0" ]
null
null
null
# Interval class which converts class Interval: def __init__(self, interval_=[0, 0]): self.start = interval_[0] self.end = interval_[1] def __repr__(self): return '[{}, {}]'.format(self.start, self.end) class Solution: def merge(self, intervals): intervals = [Interval(i) for i in intervals] intervals.sort(key=lambda x: x.start) print intervals stack = [] for interval in intervals: if not stack: stack.append(interval) else: if interval.start <= stack[-1].end: stack[-1].end = max(stack[-1].end, interval.end) else: stack.append(interval) return stack
28.961538
68
0.536521
class Interval: def __init__(self, interval_=[0, 0]): self.start = interval_[0] self.end = interval_[1] def __repr__(self): return '[{}, {}]'.format(self.start, self.end) class Solution: def merge(self, intervals): intervals = [Interval(i) for i in intervals] intervals.sort(key=lambda x: x.start) print intervals stack = [] for interval in intervals: if not stack: stack.append(interval) else: if interval.start <= stack[-1].end: stack[-1].end = max(stack[-1].end, interval.end) else: stack.append(interval) return stack
false
true
f72c4d210b5eea32e3d333a149d7cfd14424c8d5
14,927
py
Python
uf/application/uda.py
yupeijei1997/unif
16685a89446e6ce14080439162a9bfd0c75f0521
[ "Apache-2.0" ]
1
2021-05-15T12:07:40.000Z
2021-05-15T12:07:40.000Z
uf/application/uda.py
yupeijei1997/unif
16685a89446e6ce14080439162a9bfd0c75f0521
[ "Apache-2.0" ]
null
null
null
uf/application/uda.py
yupeijei1997/unif
16685a89446e6ce14080439162a9bfd0c75f0521
[ "Apache-2.0" ]
null
null
null
# coding:=utf-8 # Copyright 2021 Tencent. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Applications based on UDA. ''' import numpy as np from uf.tools import tf from .base import ClassifierModule from .bert import BERTClassifier, get_bert_config, get_key_to_depths from uf.modeling.bert import BERTEncoder from uf.modeling.uda import UDADecoder from uf.tokenization.word_piece import get_word_piece_tokenizer import uf.utils as utils import uf.modeling.util as util class UDAClassifier(BERTClassifier, ClassifierModule): ''' Single-label classifier on UDA. ''' _INFER_ATTRIBUTES = BERTClassifier._INFER_ATTRIBUTES def __init__(self, config_file, vocab_file, max_seq_length=128, label_size=None, init_checkpoint=None, output_dir=None, gpu_ids=None, drop_pooler=False, uda_softmax_temp=-1, uda_confidence_thresh=-1, tsa_schedule='linear', do_lower_case=True, truncate_method='LIFO'): super(ClassifierModule, self).__init__( init_checkpoint, output_dir, gpu_ids) self.batch_size = 0 self.max_seq_length = max_seq_length self.label_size = label_size self.truncate_method = truncate_method self._drop_pooler = drop_pooler self._uda_softmax_temp = uda_softmax_temp self._uda_confidence_thresh = uda_confidence_thresh self._tsa_schedule = tsa_schedule self._id_to_label = None self.__init_args__ = locals() self.bert_config = get_bert_config(config_file) self.tokenizer = get_word_piece_tokenizer(vocab_file, do_lower_case) self._key_to_depths = get_key_to_depths( self.bert_config.num_hidden_layers) if '[CLS]' not in self.tokenizer.vocab: self.tokenizer.add('[CLS]') self.bert_config.vocab_size += 1 tf.logging.info('Add necessary token `[CLS]` into vocabulary.') if '[SEP]' not in self.tokenizer.vocab: self.tokenizer.add('[SEP]') self.bert_config.vocab_size += 1 tf.logging.info('Add necessary token `[SEP]` into vocabulary.') def convert(self, X=None, y=None, sample_weight=None, X_tokenized=None, is_training=False): self._assert_legal(X, y, sample_weight, X_tokenized) # simplified when not training if not is_training: return super().convert( X, y, sample_weight, X_tokenized, is_training) if is_training: assert y is not None, '`y` can\'t be None.' n_inputs = None data = {} # convert X if X or X_tokenized: tokenized = False if X else X_tokenized (input_ids, input_mask, segment_ids, aug_input_ids, aug_input_mask, aug_segment_ids, is_supervised) = self._convert_X_reimp( X_tokenized if tokenized else X, y, tokenized=tokenized) data['input_ids'] = np.array(input_ids, dtype=np.int32) data['input_mask'] = np.array(input_mask, dtype=np.int32) data['segment_ids'] = np.array(segment_ids, dtype=np.int32) data['aug_input_ids'] = np.array(aug_input_ids, dtype=np.int32) data['aug_input_mask'] = np.array(aug_input_mask, dtype=np.int32) data['aug_segment_ids'] = np.array(aug_segment_ids, dtype=np.int32) data['is_supervised'] = np.array(is_supervised, dtype=np.int32) n_inputs = len(input_ids) if n_inputs < self.batch_size: self.batch_size = max(n_inputs, len(self._gpu_ids)) # convert y if y: label_ids = self._convert_y(y) data['label_ids'] = np.array(label_ids, dtype=np.int32) # convert sample_weight if is_training or y: sample_weight = self._convert_sample_weight( sample_weight, n_inputs) data['sample_weight'] = np.array(sample_weight, dtype=np.float32) return data def _convert_X_reimp(self, X_target, y, tokenized): # tokenize input texts sup_ori_input_tokens = [] aug_input_tokens = [] is_supervised = [] for ex_id, example in enumerate(X_target): try: label = y[ex_id] if label is None: assert len(example) == 2 sup_ori_input_tokens.append( self._convert_x(example[0], tokenized)) aug_input_tokens.append( self._convert_x(example[1], tokenized)) is_supervised.append(0) else: sup_ori_input_tokens.append( self._convert_x(example, tokenized)) aug_input_tokens.append([]) is_supervised.append(1) except AssertionError: raise AssertionError ( 'Must have exactly two inputs for an ' 'unsupervised example, respectively original ' 'and augmented.') except Exception: raise ValueError( 'Wrong input format (line %d): \'%s\'. ' % (ex_id, example)) input_ids = [] input_mask = [] segment_ids = [] for ex_id, segments in enumerate(sup_ori_input_tokens): _input_tokens = ['[CLS]'] _input_ids = [] _input_mask = [1] _segment_ids = [0] utils.truncate_segments( segments, self.max_seq_length - len(segments) - 1, truncate_method=self.truncate_method) for s_id, segment in enumerate(segments): _segment_id = min(s_id, 1) _input_tokens.extend(segment + ['[SEP]']) _input_mask.extend([1] * (len(segment) + 1)) _segment_ids.extend([_segment_id] * (len(segment) + 1)) _input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens) # padding for _ in range(self.max_seq_length - len(_input_ids)): _input_ids.append(0) _input_mask.append(0) _segment_ids.append(0) input_ids.append(_input_ids) input_mask.append(_input_mask) segment_ids.append(_segment_ids) aug_input_ids = [] aug_input_mask = [] aug_segment_ids = [] for ex_id, segments in enumerate(aug_input_tokens): _input_tokens = ['[CLS]'] _input_ids = [] _input_mask = [1] _segment_ids = [0] utils.truncate_segments( segments, self.max_seq_length - len(segments) - 1, truncate_method=self.truncate_method) for s_id, segment in enumerate(segments): _segment_id = min(s_id, 1) _input_tokens.extend(segment + ['[SEP]']) _input_mask.extend([1] * (len(segment) + 1)) _segment_ids.extend([_segment_id] * (len(segment) + 1)) _input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens) # padding for _ in range(self.max_seq_length - len(_input_ids)): _input_ids.append(0) _input_mask.append(0) _segment_ids.append(0) aug_input_ids.append(_input_ids) aug_input_mask.append(_input_mask) aug_segment_ids.append(_segment_ids) return (input_ids, input_mask, segment_ids, aug_input_ids, aug_input_mask, aug_segment_ids, is_supervised) def _convert_y(self, y): label_set = set(y) if None in label_set: label_set -= {None} # automatically set `label_size` if self.label_size: assert len(label_set) <= self.label_size, ( 'Number of unique `y`s exceeds `label_size`.') else: self.label_size = len(label_set) # automatically set `id_to_label` if not self._id_to_label: self._id_to_label = list(label_set) try: # Allign if user inputs continual integers. # e.g. [2, 0, 1] self._id_to_label = list(sorted(self._id_to_label)) except Exception: pass if len(self._id_to_label) < self.label_size: for i in range(len(self._id_to_label), self.label_size): self._id_to_label.append(i) # automatically set `label_to_id` for prediction self._label_to_id = { label: index for index, label in enumerate(self._id_to_label)} label_ids = [self._label_to_id[label] if label is not None else -1 for label in y] return label_ids def _set_placeholders(self, target, on_export=False, **kwargs): self.placeholders = { 'input_ids': utils.get_placeholder( target, 'input_ids', [None, self.max_seq_length], tf.int32), 'input_mask': utils.get_placeholder( target, 'input_mask', [None, self.max_seq_length], tf.int32), 'segment_ids': utils.get_placeholder( target, 'segment_ids', [None, self.max_seq_length], tf.int32), 'label_ids': utils.get_placeholder( target, 'label_ids', [None], tf.int32), } if kwargs.get('is_training'): self.placeholders['aug_input_ids'] = utils.get_placeholder( target, 'aug_input_ids', [None, self.max_seq_length], tf.int32) self.placeholders['aug_input_mask'] = utils.get_placeholder( target, 'aug_input_mask', [None, self.max_seq_length], tf.int32) self.placeholders['aug_segment_ids'] = utils.get_placeholder( target, 'aug_segment_ids', [None, self.max_seq_length], tf.int32) self.placeholders['is_supervised'] = utils.get_placeholder( target, 'is_supervised', [None], tf.float32) if not on_export: self.placeholders['sample_weight'] = \ utils.get_placeholder( target, 'sample_weight', [None], tf.float32) def _forward(self, is_training, split_placeholders, **kwargs): if not is_training: return super()._forward(is_training, split_placeholders, **kwargs) aug_input_ids = tf.boolean_mask( split_placeholders['aug_input_ids'], mask=(1.0 - split_placeholders['is_supervised']), axis=0) aug_input_mask = tf.boolean_mask( split_placeholders['aug_input_mask'], mask=(1.0 - split_placeholders['is_supervised']), axis=0) aug_segment_ids = tf.boolean_mask( split_placeholders['aug_segment_ids'], mask=(1.0 - split_placeholders['is_supervised']), axis=0) input_ids = tf.concat( [split_placeholders['input_ids'], aug_input_ids], axis=0) input_mask = tf.concat( [split_placeholders['input_mask'], aug_input_mask], axis=0) segment_ids = tf.concat( [split_placeholders['segment_ids'], aug_segment_ids], axis=0) encoder = BERTEncoder( bert_config=self.bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, scope='bert', drop_pooler=self._drop_pooler, **kwargs) encoder_output = encoder.get_pooled_output() label_ids = split_placeholders['label_ids'] is_expanded = tf.zeros_like(label_ids, dtype=tf.float32) batch_size = util.get_shape_list(aug_input_ids)[0] aug_is_expanded = tf.ones((batch_size), dtype=tf.float32) is_expanded = tf.concat([is_expanded, aug_is_expanded], axis=0) decoder = UDADecoder( is_training=is_training, input_tensor=encoder_output, is_supervised=split_placeholders['is_supervised'], is_expanded=is_expanded, label_ids=label_ids, label_size=self.label_size, sample_weight=split_placeholders.get('sample_weight'), scope='cls/seq_relationship', global_step=self._global_step, num_train_steps=self.total_steps, uda_softmax_temp=self._uda_softmax_temp, uda_confidence_thresh=self._uda_confidence_thresh, tsa_schedule=self._tsa_schedule, **kwargs) (total_loss, losses, probs, preds) = decoder.get_forward_outputs() return (total_loss, losses, probs, preds) def _get_fit_ops(self, as_feature=False): ops = [self._train_op, self._preds['preds'], self._losses['supervised'], self._losses['unsupervised'], ] if as_feature: ops.extend([self.placeholders['is_supervised'], self.placeholders['label_ids']]) return ops def _get_fit_info(self, output_arrays, feed_dict, as_feature=False): if as_feature: batch_is_sup = output_arrays[-2] batch_labels = output_arrays[-1] else: batch_is_sup = feed_dict[self.placeholders['is_supervised']] batch_labels = feed_dict[self.placeholders['label_ids']] # accuracy batch_preds = output_arrays[1] accuracy = np.sum((batch_preds == batch_labels) * batch_is_sup) / \ np.sum(batch_is_sup) # supervised loss batch_sup_losses = output_arrays[2] sup_loss = np.mean(batch_sup_losses) # supervised loss batch_unsup_losses = output_arrays[3] unsup_loss = np.mean(batch_unsup_losses) info = '' info += ', accuracy %.4f' % accuracy info += ', supervised loss %.6f' % sup_loss info += ', unsupervised loss %.6f' % unsup_loss return info
38.872396
79
0.586923
import numpy as np from uf.tools import tf from .base import ClassifierModule from .bert import BERTClassifier, get_bert_config, get_key_to_depths from uf.modeling.bert import BERTEncoder from uf.modeling.uda import UDADecoder from uf.tokenization.word_piece import get_word_piece_tokenizer import uf.utils as utils import uf.modeling.util as util class UDAClassifier(BERTClassifier, ClassifierModule): _INFER_ATTRIBUTES = BERTClassifier._INFER_ATTRIBUTES def __init__(self, config_file, vocab_file, max_seq_length=128, label_size=None, init_checkpoint=None, output_dir=None, gpu_ids=None, drop_pooler=False, uda_softmax_temp=-1, uda_confidence_thresh=-1, tsa_schedule='linear', do_lower_case=True, truncate_method='LIFO'): super(ClassifierModule, self).__init__( init_checkpoint, output_dir, gpu_ids) self.batch_size = 0 self.max_seq_length = max_seq_length self.label_size = label_size self.truncate_method = truncate_method self._drop_pooler = drop_pooler self._uda_softmax_temp = uda_softmax_temp self._uda_confidence_thresh = uda_confidence_thresh self._tsa_schedule = tsa_schedule self._id_to_label = None self.__init_args__ = locals() self.bert_config = get_bert_config(config_file) self.tokenizer = get_word_piece_tokenizer(vocab_file, do_lower_case) self._key_to_depths = get_key_to_depths( self.bert_config.num_hidden_layers) if '[CLS]' not in self.tokenizer.vocab: self.tokenizer.add('[CLS]') self.bert_config.vocab_size += 1 tf.logging.info('Add necessary token `[CLS]` into vocabulary.') if '[SEP]' not in self.tokenizer.vocab: self.tokenizer.add('[SEP]') self.bert_config.vocab_size += 1 tf.logging.info('Add necessary token `[SEP]` into vocabulary.') def convert(self, X=None, y=None, sample_weight=None, X_tokenized=None, is_training=False): self._assert_legal(X, y, sample_weight, X_tokenized) if not is_training: return super().convert( X, y, sample_weight, X_tokenized, is_training) if is_training: assert y is not None, '`y` can\'t be None.' n_inputs = None data = {} # convert X if X or X_tokenized: tokenized = False if X else X_tokenized (input_ids, input_mask, segment_ids, aug_input_ids, aug_input_mask, aug_segment_ids, is_supervised) = self._convert_X_reimp( X_tokenized if tokenized else X, y, tokenized=tokenized) data['input_ids'] = np.array(input_ids, dtype=np.int32) data['input_mask'] = np.array(input_mask, dtype=np.int32) data['segment_ids'] = np.array(segment_ids, dtype=np.int32) data['aug_input_ids'] = np.array(aug_input_ids, dtype=np.int32) data['aug_input_mask'] = np.array(aug_input_mask, dtype=np.int32) data['aug_segment_ids'] = np.array(aug_segment_ids, dtype=np.int32) data['is_supervised'] = np.array(is_supervised, dtype=np.int32) n_inputs = len(input_ids) if n_inputs < self.batch_size: self.batch_size = max(n_inputs, len(self._gpu_ids)) # convert y if y: label_ids = self._convert_y(y) data['label_ids'] = np.array(label_ids, dtype=np.int32) # convert sample_weight if is_training or y: sample_weight = self._convert_sample_weight( sample_weight, n_inputs) data['sample_weight'] = np.array(sample_weight, dtype=np.float32) return data def _convert_X_reimp(self, X_target, y, tokenized): # tokenize input texts sup_ori_input_tokens = [] aug_input_tokens = [] is_supervised = [] for ex_id, example in enumerate(X_target): try: label = y[ex_id] if label is None: assert len(example) == 2 sup_ori_input_tokens.append( self._convert_x(example[0], tokenized)) aug_input_tokens.append( self._convert_x(example[1], tokenized)) is_supervised.append(0) else: sup_ori_input_tokens.append( self._convert_x(example, tokenized)) aug_input_tokens.append([]) is_supervised.append(1) except AssertionError: raise AssertionError ( 'Must have exactly two inputs for an ' 'unsupervised example, respectively original ' 'and augmented.') except Exception: raise ValueError( 'Wrong input format (line %d): \'%s\'. ' % (ex_id, example)) input_ids = [] input_mask = [] segment_ids = [] for ex_id, segments in enumerate(sup_ori_input_tokens): _input_tokens = ['[CLS]'] _input_ids = [] _input_mask = [1] _segment_ids = [0] utils.truncate_segments( segments, self.max_seq_length - len(segments) - 1, truncate_method=self.truncate_method) for s_id, segment in enumerate(segments): _segment_id = min(s_id, 1) _input_tokens.extend(segment + ['[SEP]']) _input_mask.extend([1] * (len(segment) + 1)) _segment_ids.extend([_segment_id] * (len(segment) + 1)) _input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens) # padding for _ in range(self.max_seq_length - len(_input_ids)): _input_ids.append(0) _input_mask.append(0) _segment_ids.append(0) input_ids.append(_input_ids) input_mask.append(_input_mask) segment_ids.append(_segment_ids) aug_input_ids = [] aug_input_mask = [] aug_segment_ids = [] for ex_id, segments in enumerate(aug_input_tokens): _input_tokens = ['[CLS]'] _input_ids = [] _input_mask = [1] _segment_ids = [0] utils.truncate_segments( segments, self.max_seq_length - len(segments) - 1, truncate_method=self.truncate_method) for s_id, segment in enumerate(segments): _segment_id = min(s_id, 1) _input_tokens.extend(segment + ['[SEP]']) _input_mask.extend([1] * (len(segment) + 1)) _segment_ids.extend([_segment_id] * (len(segment) + 1)) _input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens) # padding for _ in range(self.max_seq_length - len(_input_ids)): _input_ids.append(0) _input_mask.append(0) _segment_ids.append(0) aug_input_ids.append(_input_ids) aug_input_mask.append(_input_mask) aug_segment_ids.append(_segment_ids) return (input_ids, input_mask, segment_ids, aug_input_ids, aug_input_mask, aug_segment_ids, is_supervised) def _convert_y(self, y): label_set = set(y) if None in label_set: label_set -= {None} # automatically set `label_size` if self.label_size: assert len(label_set) <= self.label_size, ( 'Number of unique `y`s exceeds `label_size`.') else: self.label_size = len(label_set) # automatically set `id_to_label` if not self._id_to_label: self._id_to_label = list(label_set) try: # Allign if user inputs continual integers. # e.g. [2, 0, 1] self._id_to_label = list(sorted(self._id_to_label)) except Exception: pass if len(self._id_to_label) < self.label_size: for i in range(len(self._id_to_label), self.label_size): self._id_to_label.append(i) # automatically set `label_to_id` for prediction self._label_to_id = { label: index for index, label in enumerate(self._id_to_label)} label_ids = [self._label_to_id[label] if label is not None else -1 for label in y] return label_ids def _set_placeholders(self, target, on_export=False, **kwargs): self.placeholders = { 'input_ids': utils.get_placeholder( target, 'input_ids', [None, self.max_seq_length], tf.int32), 'input_mask': utils.get_placeholder( target, 'input_mask', [None, self.max_seq_length], tf.int32), 'segment_ids': utils.get_placeholder( target, 'segment_ids', [None, self.max_seq_length], tf.int32), 'label_ids': utils.get_placeholder( target, 'label_ids', [None], tf.int32), } if kwargs.get('is_training'): self.placeholders['aug_input_ids'] = utils.get_placeholder( target, 'aug_input_ids', [None, self.max_seq_length], tf.int32) self.placeholders['aug_input_mask'] = utils.get_placeholder( target, 'aug_input_mask', [None, self.max_seq_length], tf.int32) self.placeholders['aug_segment_ids'] = utils.get_placeholder( target, 'aug_segment_ids', [None, self.max_seq_length], tf.int32) self.placeholders['is_supervised'] = utils.get_placeholder( target, 'is_supervised', [None], tf.float32) if not on_export: self.placeholders['sample_weight'] = \ utils.get_placeholder( target, 'sample_weight', [None], tf.float32) def _forward(self, is_training, split_placeholders, **kwargs): if not is_training: return super()._forward(is_training, split_placeholders, **kwargs) aug_input_ids = tf.boolean_mask( split_placeholders['aug_input_ids'], mask=(1.0 - split_placeholders['is_supervised']), axis=0) aug_input_mask = tf.boolean_mask( split_placeholders['aug_input_mask'], mask=(1.0 - split_placeholders['is_supervised']), axis=0) aug_segment_ids = tf.boolean_mask( split_placeholders['aug_segment_ids'], mask=(1.0 - split_placeholders['is_supervised']), axis=0) input_ids = tf.concat( [split_placeholders['input_ids'], aug_input_ids], axis=0) input_mask = tf.concat( [split_placeholders['input_mask'], aug_input_mask], axis=0) segment_ids = tf.concat( [split_placeholders['segment_ids'], aug_segment_ids], axis=0) encoder = BERTEncoder( bert_config=self.bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, scope='bert', drop_pooler=self._drop_pooler, **kwargs) encoder_output = encoder.get_pooled_output() label_ids = split_placeholders['label_ids'] is_expanded = tf.zeros_like(label_ids, dtype=tf.float32) batch_size = util.get_shape_list(aug_input_ids)[0] aug_is_expanded = tf.ones((batch_size), dtype=tf.float32) is_expanded = tf.concat([is_expanded, aug_is_expanded], axis=0) decoder = UDADecoder( is_training=is_training, input_tensor=encoder_output, is_supervised=split_placeholders['is_supervised'], is_expanded=is_expanded, label_ids=label_ids, label_size=self.label_size, sample_weight=split_placeholders.get('sample_weight'), scope='cls/seq_relationship', global_step=self._global_step, num_train_steps=self.total_steps, uda_softmax_temp=self._uda_softmax_temp, uda_confidence_thresh=self._uda_confidence_thresh, tsa_schedule=self._tsa_schedule, **kwargs) (total_loss, losses, probs, preds) = decoder.get_forward_outputs() return (total_loss, losses, probs, preds) def _get_fit_ops(self, as_feature=False): ops = [self._train_op, self._preds['preds'], self._losses['supervised'], self._losses['unsupervised'], ] if as_feature: ops.extend([self.placeholders['is_supervised'], self.placeholders['label_ids']]) return ops def _get_fit_info(self, output_arrays, feed_dict, as_feature=False): if as_feature: batch_is_sup = output_arrays[-2] batch_labels = output_arrays[-1] else: batch_is_sup = feed_dict[self.placeholders['is_supervised']] batch_labels = feed_dict[self.placeholders['label_ids']] # accuracy batch_preds = output_arrays[1] accuracy = np.sum((batch_preds == batch_labels) * batch_is_sup) / \ np.sum(batch_is_sup) # supervised loss batch_sup_losses = output_arrays[2] sup_loss = np.mean(batch_sup_losses) # supervised loss batch_unsup_losses = output_arrays[3] unsup_loss = np.mean(batch_unsup_losses) info = '' info += ', accuracy %.4f' % accuracy info += ', supervised loss %.6f' % sup_loss info += ', unsupervised loss %.6f' % unsup_loss return info
true
true
f72c4da207cd6d82929af064fa9ceebeef08defa
283
py
Python
iterators_and_generators/demo_generators.py
Minkov/python-oop-2020-02
d2acb1504c1a135cded2ae6ff42acccb303d9ab1
[ "MIT" ]
2
2020-02-27T18:34:45.000Z
2020-10-25T17:34:15.000Z
iterators_and_generators/demo_generators.py
Minkov/python-oop-2020-02
d2acb1504c1a135cded2ae6ff42acccb303d9ab1
[ "MIT" ]
null
null
null
iterators_and_generators/demo_generators.py
Minkov/python-oop-2020-02
d2acb1504c1a135cded2ae6ff42acccb303d9ab1
[ "MIT" ]
null
null
null
def custom_range(min, max): index = min while index <= max: yield index index += 1 it = custom_range(1, 2) print(next(it)) print(next(it)) print((x for x in range(3))) even = filter(lambda x: x % 2 == 0, range(10)) for x in even: print(x)
18.866667
47
0.55477
def custom_range(min, max): index = min while index <= max: yield index index += 1 it = custom_range(1, 2) print(next(it)) print(next(it)) print((x for x in range(3))) even = filter(lambda x: x % 2 == 0, range(10)) for x in even: print(x)
true
true
f72c4f1fb0a457648028cbec2b488d34d23bde73
5,745
py
Python
logistic_fit.py
ege-erdil/logistic-fit
7c6cc9ed35877ed8d142dd75b7b98658e19cf7cb
[ "MIT" ]
null
null
null
logistic_fit.py
ege-erdil/logistic-fit
7c6cc9ed35877ed8d142dd75b7b98658e19cf7cb
[ "MIT" ]
null
null
null
logistic_fit.py
ege-erdil/logistic-fit
7c6cc9ed35877ed8d142dd75b7b98658e19cf7cb
[ "MIT" ]
null
null
null
from autograd import grad import autograd.numpy as np from scipy.stats import logistic, norm from scipy.optimize import minimize def logistic_pdf(x, loc, scale): y = (x - loc)/scale return np.exp(-y)/(scale * (1 + np.exp(-y))**2) def logistic_cdf(x, loc, scale): y = (x-loc)/scale if y < -100: return 0 elif y > 100: return 1 else: return 1/(1 + np.exp(-y)) def logistic_logpdf(x, loc, scale): y = (x - loc)/scale if y < -250: return y - np.log(scale) elif y > 250: return -y - np.log(scale) else: return -y - np.log(scale) - 2 * np.log(1 + np.exp(-y)) def square_dist(a1, a2): s = 0 for k in range(len(a1)): s += (a1[k] - a2[k])**2 return s def log_likelihood_logistic(data, params): n = len(data) c = (len(params) + 1)//3 r = 0 if (len(params) + 1) % 3 != 0: print("Parameters specified incorrectly!") return None else: weights = [1] for k in range(c-1): weights.append(np.exp(params[2*c + k])) s = np.sum(weights) for x in data: pdf_list = [logistic_logpdf(x, params[2*j], np.exp(params[2*j+1])) for j in range(c)] pdf_list_avg = np.sum(pdf_list)/c pdf_list_n = [weights[j] * np.exp(pdf_list[j] - pdf_list_avg) for j in range(c)] r += (pdf_list_avg + np.log(np.sum(pdf_list_n)/s))/n return r def cdf_loss(percentiles, params): n = len(percentiles) c = (len(params) + 1)//3 r = 0 if (len(params) + 1) % 3 != 0: print("Parameters specified incorrectly!") return None else: weights = [1] for k in range(c-1): weights.append(np.exp(params[2*c + k])) s = np.sum(weights) for q in range(1, n): cdf_list = [logistic_cdf(percentiles[q-1], params[2*j], np.exp(params[2*j+1])) for j in range(c)] cdf_list_n = [weights[j] * cdf_list[j] for j in range(c)] r += (np.sum(cdf_list_n)/s - q/n)**2/n return r def estimate(data, bins=20, num = 1, tol = 0.01, maxiter = 100): fit_params = np.zeros(3*num - 1) a = np.average(data) s = np.log(np.std(data)) percentiles = [np.percentile(data, k) for k in range(100//bins, 100, 100//bins)] for i in range(num): fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1) fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1) def training_loss(params): return cdf_loss(percentiles, params) + 0.0001 * np.dot(params[2*num:], params[2*num:]) training_loss_jac = grad(training_loss) res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol}) print(res) final_params = res.x for i in range(num): final_params[2*i+1] = np.exp(final_params[2*i+1]) results = [] for i in range(num): results.append(final_params[2*i]) results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i]) for i in range(num-1): results.append(final_params[2*num + i]) return results def estimate_log(data, num = 1, tol = 0.01, maxiter = 100): fit_params = np.zeros(3*num - 1) a = np.average(data) s = np.log(np.std(data)) for i in range(num): fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1) fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1) def training_likelihood(params): return log_likelihood_logistic(data, params) def training_loss(params): return -log_likelihood_logistic(data, params) training_likelihood_jac = grad(training_likelihood) training_loss_jac = grad(training_loss) res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol}) print(res) final_params = res.x for i in range(num): final_params[2*i+1] = np.exp(final_params[2*i+1]) results = [] for i in range(num): results.append(final_params[2*i]) results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i]) for i in range(num-1): results.append(final_params[2*num + i]) return results def estimate_powell(data, num = 1, tol = 0.01, maxiter = 100): fit_params = np.zeros(3*num - 1) a = np.average(data) s = np.log(np.std(data)) for i in range(num): fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1) fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1) def training_likelihood(params): return log_likelihood_logistic(data, params) def training_loss(params): return -log_likelihood_logistic(data, params) training_likelihood_jac = grad(training_likelihood) training_loss_jac = grad(training_loss) res = minimize(training_loss, x0=fit_params, method="Powell", tol=tol, options = {"maxiter": maxiter}) print(res) final_params = res.x for i in range(num): final_params[2*i+1] = np.exp(final_params[2*i+1]) results = [] for i in range(num): results.append(final_params[2*i]) results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i]) for i in range(num-1): results.append(final_params[2*num + i]) return results
33.794118
132
0.582594
from autograd import grad import autograd.numpy as np from scipy.stats import logistic, norm from scipy.optimize import minimize def logistic_pdf(x, loc, scale): y = (x - loc)/scale return np.exp(-y)/(scale * (1 + np.exp(-y))**2) def logistic_cdf(x, loc, scale): y = (x-loc)/scale if y < -100: return 0 elif y > 100: return 1 else: return 1/(1 + np.exp(-y)) def logistic_logpdf(x, loc, scale): y = (x - loc)/scale if y < -250: return y - np.log(scale) elif y > 250: return -y - np.log(scale) else: return -y - np.log(scale) - 2 * np.log(1 + np.exp(-y)) def square_dist(a1, a2): s = 0 for k in range(len(a1)): s += (a1[k] - a2[k])**2 return s def log_likelihood_logistic(data, params): n = len(data) c = (len(params) + 1)//3 r = 0 if (len(params) + 1) % 3 != 0: print("Parameters specified incorrectly!") return None else: weights = [1] for k in range(c-1): weights.append(np.exp(params[2*c + k])) s = np.sum(weights) for x in data: pdf_list = [logistic_logpdf(x, params[2*j], np.exp(params[2*j+1])) for j in range(c)] pdf_list_avg = np.sum(pdf_list)/c pdf_list_n = [weights[j] * np.exp(pdf_list[j] - pdf_list_avg) for j in range(c)] r += (pdf_list_avg + np.log(np.sum(pdf_list_n)/s))/n return r def cdf_loss(percentiles, params): n = len(percentiles) c = (len(params) + 1)//3 r = 0 if (len(params) + 1) % 3 != 0: print("Parameters specified incorrectly!") return None else: weights = [1] for k in range(c-1): weights.append(np.exp(params[2*c + k])) s = np.sum(weights) for q in range(1, n): cdf_list = [logistic_cdf(percentiles[q-1], params[2*j], np.exp(params[2*j+1])) for j in range(c)] cdf_list_n = [weights[j] * cdf_list[j] for j in range(c)] r += (np.sum(cdf_list_n)/s - q/n)**2/n return r def estimate(data, bins=20, num = 1, tol = 0.01, maxiter = 100): fit_params = np.zeros(3*num - 1) a = np.average(data) s = np.log(np.std(data)) percentiles = [np.percentile(data, k) for k in range(100//bins, 100, 100//bins)] for i in range(num): fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1) fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1) def training_loss(params): return cdf_loss(percentiles, params) + 0.0001 * np.dot(params[2*num:], params[2*num:]) training_loss_jac = grad(training_loss) res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol}) print(res) final_params = res.x for i in range(num): final_params[2*i+1] = np.exp(final_params[2*i+1]) results = [] for i in range(num): results.append(final_params[2*i]) results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i]) for i in range(num-1): results.append(final_params[2*num + i]) return results def estimate_log(data, num = 1, tol = 0.01, maxiter = 100): fit_params = np.zeros(3*num - 1) a = np.average(data) s = np.log(np.std(data)) for i in range(num): fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1) fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1) def training_likelihood(params): return log_likelihood_logistic(data, params) def training_loss(params): return -log_likelihood_logistic(data, params) training_likelihood_jac = grad(training_likelihood) training_loss_jac = grad(training_loss) res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol}) print(res) final_params = res.x for i in range(num): final_params[2*i+1] = np.exp(final_params[2*i+1]) results = [] for i in range(num): results.append(final_params[2*i]) results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i]) for i in range(num-1): results.append(final_params[2*num + i]) return results def estimate_powell(data, num = 1, tol = 0.01, maxiter = 100): fit_params = np.zeros(3*num - 1) a = np.average(data) s = np.log(np.std(data)) for i in range(num): fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1) fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1) def training_likelihood(params): return log_likelihood_logistic(data, params) def training_loss(params): return -log_likelihood_logistic(data, params) training_likelihood_jac = grad(training_likelihood) training_loss_jac = grad(training_loss) res = minimize(training_loss, x0=fit_params, method="Powell", tol=tol, options = {"maxiter": maxiter}) print(res) final_params = res.x for i in range(num): final_params[2*i+1] = np.exp(final_params[2*i+1]) results = [] for i in range(num): results.append(final_params[2*i]) results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i]) for i in range(num-1): results.append(final_params[2*num + i]) return results
true
true
f72c4f3b403c785cc891e829c3dd7d88ad7ca116
308
py
Python
tests/parser_test.py
krilifon/proxy-parse
79d1c1655024a03e7a8c1b653dfdf6d68f89e511
[ "MIT" ]
4
2021-11-29T18:56:54.000Z
2021-12-23T10:59:58.000Z
tests/parser_test.py
krilifon/proxy-parse
79d1c1655024a03e7a8c1b653dfdf6d68f89e511
[ "MIT" ]
null
null
null
tests/parser_test.py
krilifon/proxy-parse
79d1c1655024a03e7a8c1b653dfdf6d68f89e511
[ "MIT" ]
null
null
null
from proxy_parse import ProxyParser from proxy_parse.spiders import HideMySpider def test_proxy_parser(): proxy_parser = ProxyParser(scrapy_spiders=[HideMySpider]) result = proxy_parser.parse() assert type(result) is list assert all(type(proxy) is str and ":" in proxy for proxy in result)
30.8
71
0.762987
from proxy_parse import ProxyParser from proxy_parse.spiders import HideMySpider def test_proxy_parser(): proxy_parser = ProxyParser(scrapy_spiders=[HideMySpider]) result = proxy_parser.parse() assert type(result) is list assert all(type(proxy) is str and ":" in proxy for proxy in result)
true
true
f72c50b550d0cb981526fc944b9967a3ca63e4c6
237
py
Python
polyaxon/api/code_reference/serializers.py
elyase/polyaxon
1c19f059a010a6889e2b7ea340715b2bcfa382a0
[ "MIT" ]
null
null
null
polyaxon/api/code_reference/serializers.py
elyase/polyaxon
1c19f059a010a6889e2b7ea340715b2bcfa382a0
[ "MIT" ]
null
null
null
polyaxon/api/code_reference/serializers.py
elyase/polyaxon
1c19f059a010a6889e2b7ea340715b2bcfa382a0
[ "MIT" ]
null
null
null
from rest_framework import serializers from db.models.repos import CodeReference class CodeReferenceSerializer(serializers.ModelSerializer): class Meta: model = CodeReference exclude = ['created_at', 'updated_at']
23.7
59
0.755274
from rest_framework import serializers from db.models.repos import CodeReference class CodeReferenceSerializer(serializers.ModelSerializer): class Meta: model = CodeReference exclude = ['created_at', 'updated_at']
true
true
f72c516d329c6cda5c8629429947754fd975930b
458
py
Python
.venv/lib/python3.7/site-packages/jupyter_client/__init__.py
ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos
4acdbc423428fb2e0068720add69e7870c87929a
[ "Apache-2.0" ]
76
2020-07-06T14:44:05.000Z
2022-02-14T15:30:21.000Z
.venv/lib/python3.7/site-packages/jupyter_client/__init__.py
ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos
4acdbc423428fb2e0068720add69e7870c87929a
[ "Apache-2.0" ]
24
2020-03-25T19:35:43.000Z
2022-02-10T11:46:50.000Z
.venv/lib/python3.7/site-packages/jupyter_client/__init__.py
ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos
4acdbc423428fb2e0068720add69e7870c87929a
[ "Apache-2.0" ]
11
2019-01-21T17:51:48.000Z
2021-08-10T07:04:33.000Z
"""Client-side implementations of the Jupyter protocol""" from ._version import version_info, __version__, protocol_version_info, protocol_version from .connect import * from .launcher import * from .client import KernelClient from .manager import KernelManager, AsyncKernelManager, run_kernel from .blocking import BlockingKernelClient from .asynchronous import AsyncKernelClient from .multikernelmanager import MultiKernelManager, AsyncMultiKernelManager
41.636364
88
0.851528
from ._version import version_info, __version__, protocol_version_info, protocol_version from .connect import * from .launcher import * from .client import KernelClient from .manager import KernelManager, AsyncKernelManager, run_kernel from .blocking import BlockingKernelClient from .asynchronous import AsyncKernelClient from .multikernelmanager import MultiKernelManager, AsyncMultiKernelManager
true
true
f72c517b8635ba9e8ee1d7ac3aac00b5ef74b266
475
py
Python
src/som/primitives/invokable_primitives.py
smarr/RPySOM
941e1fe08753d6e97dac24c3ba4d1e99a9c40160
[ "MIT" ]
12
2016-01-07T14:20:57.000Z
2019-10-13T06:56:20.000Z
src/som/primitives/invokable_primitives.py
smarr/RPySOM
941e1fe08753d6e97dac24c3ba4d1e99a9c40160
[ "MIT" ]
2
2016-05-26T06:53:33.000Z
2020-09-02T15:58:28.000Z
src/som/primitives/invokable_primitives.py
SOM-st/RPySOM
2dcfc71786a3bd5be5a842c649645f71d6c35f89
[ "MIT" ]
2
2016-05-25T06:07:52.000Z
2019-10-02T16:52:25.000Z
from som.primitives.primitives import Primitives from som.vmobjects.primitive import UnaryPrimitive def _holder(rcvr): return rcvr.get_holder() def _signature(rcvr): return rcvr.get_signature() class InvokablePrimitivesBase(Primitives): def install_primitives(self): self._install_instance_primitive(UnaryPrimitive("holder", self._universe, _holder)) self._install_instance_primitive(UnaryPrimitive("signature", self._universe, _signature))
27.941176
97
0.785263
from som.primitives.primitives import Primitives from som.vmobjects.primitive import UnaryPrimitive def _holder(rcvr): return rcvr.get_holder() def _signature(rcvr): return rcvr.get_signature() class InvokablePrimitivesBase(Primitives): def install_primitives(self): self._install_instance_primitive(UnaryPrimitive("holder", self._universe, _holder)) self._install_instance_primitive(UnaryPrimitive("signature", self._universe, _signature))
true
true
f72c517f1ba15c39ff29e590665a48a098bdbe9a
868
py
Python
Aula_extrator_url/main.py
laurourbano/Projetos_Python
50e7f4a7ff34158385ea7b635bac95ec8a0363a1
[ "MIT" ]
1
2021-12-28T02:51:34.000Z
2021-12-28T02:51:34.000Z
Aula_extrator_url/main.py
laurourbano/Projetos_Python
50e7f4a7ff34158385ea7b635bac95ec8a0363a1
[ "MIT" ]
null
null
null
Aula_extrator_url/main.py
laurourbano/Projetos_Python
50e7f4a7ff34158385ea7b635bac95ec8a0363a1
[ "MIT" ]
null
null
null
# Arquivo utilizado até a aula 3, quando então passamos a utilizar a classe # ExtratorURL no arquivo extrator_url.py url = "bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar" # Sanitização da URL url = url.strip() # Validação da URL if url == "": raise ValueError("A URL está vazia") # Separa base e parâmetros indice_interrogacao = url.find('?') url_base = url[:indice_interrogacao] url_parametros = url[indice_interrogacao+1:] print(url_parametros) # Busca o valor de um parâmetro parametro_busca = 'quantidade' indice_parametro = url_parametros.find(parametro_busca) indice_valor = indice_parametro + len(parametro_busca) + 1 indice_e_comercial = url_parametros.find('&', indice_valor) if indice_e_comercial == -1: valor = url_parametros[indice_valor:] else: valor = url_parametros[indice_valor:indice_e_comercial] print(valor)
31
78
0.776498
url = "bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar" url = url.strip() if url == "": raise ValueError("A URL está vazia") indice_interrogacao = url.find('?') url_base = url[:indice_interrogacao] url_parametros = url[indice_interrogacao+1:] print(url_parametros) parametro_busca = 'quantidade' indice_parametro = url_parametros.find(parametro_busca) indice_valor = indice_parametro + len(parametro_busca) + 1 indice_e_comercial = url_parametros.find('&', indice_valor) if indice_e_comercial == -1: valor = url_parametros[indice_valor:] else: valor = url_parametros[indice_valor:indice_e_comercial] print(valor)
true
true
f72c51acdba5f7032ff01e97210db5d3fb75c607
8,224
py
Python
conda/cli/main.py
jacoblsmith/conda
f50b919a4c923820c1bb2b449603534084faa28b
[ "BSD-3-Clause" ]
null
null
null
conda/cli/main.py
jacoblsmith/conda
f50b919a4c923820c1bb2b449603534084faa28b
[ "BSD-3-Clause" ]
null
null
null
conda/cli/main.py
jacoblsmith/conda
f50b919a4c923820c1bb2b449603534084faa28b
[ "BSD-3-Clause" ]
null
null
null
# (c) Continuum Analytics, Inc. / http://continuum.io # All Rights Reserved # # conda is distributed under the terms of the BSD 3-clause license. # Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause. '''conda is a tool for managing environments and packages. conda provides the following commands: Information =========== info : display information about the current install list : list packages linked into a specified environment search : print information about a specified package help : display a list of available conda commands and their help strings Package Management ================== create : create a new conda environment from a list of specified packages install : install new packages into an existing conda environment update : update packages in a specified conda environment Packaging ========= build : build a package from recipe package : create a conda package in an environment index : updates repodata.json in channel directories Additional help for each command can be accessed by using: conda <command> -h ''' from __future__ import print_function, division, absolute_import import sys def main(): if len(sys.argv) > 1: argv1 = sys.argv[1] if argv1 in ('..activate', '..deactivate', '..activateroot', '..checkenv'): import conda.cli.activate as activate activate.main() return if argv1 in ('..changeps1'): import conda.cli.misc as misc misc.main() return if argv1 == 'pip': sys.exit("""ERROR: The "conda pip" command has been removed from conda (as of version 1.8) for the following reasons: * users get the wrong impression that you *must* use conda pip (instead of simply pip) when using Anaconda * there should only be one preferred way to build packages, and that is the conda build command * the command did too many things at once, i.e. build a package and then also install it * the command is Python centric, whereas conda (from a package management perspective) is Python agnostic * packages created with conda pip are not robust, i.e. they will maybe not work on other people's systems In short: * use "conda build" if you want to build a conda package * use "conda install" if you want to install something * use "pip" if you want to install something that is on PyPI for which there isn't a conda package. """) if argv1 in ('activate', 'deactivate'): sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1) if sys.platform != 'win32': sys.stderr.write('Did you mean "source %s" ?\n' % ' '.join(sys.argv[1:])) sys.exit(1) # for backwards compatibility of conda-api if sys.argv[1:4] == ['share', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_create_bundle prefix = sys.argv[4] path, warnings = old_create_bundle(abspath(prefix)) json.dump(dict(path=path, warnings=warnings), sys.stdout, indent=2, sort_keys=True) return if sys.argv[1:4] == ['clone', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_clone_bundle prefix, path = sys.argv[4:6] old_clone_bundle(path, abspath(prefix)) json.dump(dict(warnings=[]), sys.stdout, indent=2) return if len(sys.argv) == 1: sys.argv.append('-h') import logging from conda.cli import conda_argparse import argparse import conda p = conda_argparse.ArgumentParser( description='conda is a tool for managing and deploying applications, environments and packages.' ) p.add_argument( '-V', '--version', action='version', version='conda %s' % conda.__version__, help="Show the conda version number and exit." ) p.add_argument( "--debug", action = "store_true", help = "Show debug output." ) p.add_argument( "--json", action = "store_true", help = argparse.SUPPRESS, ) sub_parsers = p.add_subparsers( metavar = 'command', dest = 'cmd', ) from conda.cli import main_info main_info.configure_parser(sub_parsers) from conda.cli import main_help main_help.configure_parser(sub_parsers) from conda.cli import main_list main_list.configure_parser(sub_parsers) from conda.cli import main_search main_search.configure_parser(sub_parsers) from conda.cli import main_create main_create.configure_parser(sub_parsers) from conda.cli import main_install main_install.configure_parser(sub_parsers) from conda.cli import main_update main_update.configure_parser(sub_parsers) from conda.cli import main_remove main_remove.configure_parser(sub_parsers) main_remove.configure_parser(sub_parsers, name='uninstall') from conda.cli import main_run main_run.configure_parser(sub_parsers) from conda.cli import main_config main_config.configure_parser(sub_parsers) from conda.cli import main_init main_init.configure_parser(sub_parsers) from conda.cli import main_clean main_clean.configure_parser(sub_parsers) from conda.cli import main_package main_package.configure_parser(sub_parsers) from conda.cli import main_bundle main_bundle.configure_parser(sub_parsers) from conda.cli.find_commands import find_commands sub_parsers.completer = lambda prefix, **kwargs: [i for i in list(sub_parsers.choices) + find_commands() if i.startswith(prefix)] args = p.parse_args() if getattr(args, 'json', False): # Silence logging info to avoid interfering with JSON output for logger in logging.Logger.manager.loggerDict: if logger not in ('fetch', 'progress'): logging.getLogger(logger).setLevel(logging.CRITICAL + 1) if args.debug: logging.disable(logging.NOTSET) logging.basicConfig(level=logging.DEBUG) if (not main_init.is_initialized() and 'init' not in sys.argv and 'info' not in sys.argv): if hasattr(args, 'name') and hasattr(args, 'prefix'): import conda.config as config from conda.cli import common if common.get_prefix(args) == config.root_dir: sys.exit("""\ Error: This installation of conda is not initialized. Use 'conda create -n envname' to create a conda environment and 'source activate envname' to activate it. # Note that pip installing conda is not the recommended way for setting up your # system. The recommended way for setting up a conda system is by installing # Miniconda, see: http://repo.continuum.io/miniconda/index.html""") args_func(args, p) def args_func(args, p): from conda.cli import common use_json = getattr(args, 'json', False) try: args.func(args, p) except RuntimeError as e: if 'maximum recursion depth exceeded' in str(e): print_issue_message(e, use_json=use_json) raise common.error_and_exit(str(e), json=use_json) except Exception as e: print_issue_message(e, use_json=use_json) raise # as if we did not catch it def print_issue_message(e, use_json=False): from conda.cli import common if e.__class__.__name__ not in ('ScannerError', 'ParserError'): message = """\ An unexpected error has occurred, please consider sending the following traceback to the conda GitHub issue tracker at: https://github.com/conda/conda/issues Include the output of the command 'conda info' in your report. """ if use_json: import traceback common.error_and_exit(message + traceback.format_exc(), error_type="UnexpectedError", json=True) print(message) if __name__ == '__main__': main()
35.601732
105
0.655399
from __future__ import print_function, division, absolute_import import sys def main(): if len(sys.argv) > 1: argv1 = sys.argv[1] if argv1 in ('..activate', '..deactivate', '..activateroot', '..checkenv'): import conda.cli.activate as activate activate.main() return if argv1 in ('..changeps1'): import conda.cli.misc as misc misc.main() return if argv1 == 'pip': sys.exit("""ERROR: The "conda pip" command has been removed from conda (as of version 1.8) for the following reasons: * users get the wrong impression that you *must* use conda pip (instead of simply pip) when using Anaconda * there should only be one preferred way to build packages, and that is the conda build command * the command did too many things at once, i.e. build a package and then also install it * the command is Python centric, whereas conda (from a package management perspective) is Python agnostic * packages created with conda pip are not robust, i.e. they will maybe not work on other people's systems In short: * use "conda build" if you want to build a conda package * use "conda install" if you want to install something * use "pip" if you want to install something that is on PyPI for which there isn't a conda package. """) if argv1 in ('activate', 'deactivate'): sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1) if sys.platform != 'win32': sys.stderr.write('Did you mean "source %s" ?\n' % ' '.join(sys.argv[1:])) sys.exit(1) if sys.argv[1:4] == ['share', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_create_bundle prefix = sys.argv[4] path, warnings = old_create_bundle(abspath(prefix)) json.dump(dict(path=path, warnings=warnings), sys.stdout, indent=2, sort_keys=True) return if sys.argv[1:4] == ['clone', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_clone_bundle prefix, path = sys.argv[4:6] old_clone_bundle(path, abspath(prefix)) json.dump(dict(warnings=[]), sys.stdout, indent=2) return if len(sys.argv) == 1: sys.argv.append('-h') import logging from conda.cli import conda_argparse import argparse import conda p = conda_argparse.ArgumentParser( description='conda is a tool for managing and deploying applications, environments and packages.' ) p.add_argument( '-V', '--version', action='version', version='conda %s' % conda.__version__, help="Show the conda version number and exit." ) p.add_argument( "--debug", action = "store_true", help = "Show debug output." ) p.add_argument( "--json", action = "store_true", help = argparse.SUPPRESS, ) sub_parsers = p.add_subparsers( metavar = 'command', dest = 'cmd', ) from conda.cli import main_info main_info.configure_parser(sub_parsers) from conda.cli import main_help main_help.configure_parser(sub_parsers) from conda.cli import main_list main_list.configure_parser(sub_parsers) from conda.cli import main_search main_search.configure_parser(sub_parsers) from conda.cli import main_create main_create.configure_parser(sub_parsers) from conda.cli import main_install main_install.configure_parser(sub_parsers) from conda.cli import main_update main_update.configure_parser(sub_parsers) from conda.cli import main_remove main_remove.configure_parser(sub_parsers) main_remove.configure_parser(sub_parsers, name='uninstall') from conda.cli import main_run main_run.configure_parser(sub_parsers) from conda.cli import main_config main_config.configure_parser(sub_parsers) from conda.cli import main_init main_init.configure_parser(sub_parsers) from conda.cli import main_clean main_clean.configure_parser(sub_parsers) from conda.cli import main_package main_package.configure_parser(sub_parsers) from conda.cli import main_bundle main_bundle.configure_parser(sub_parsers) from conda.cli.find_commands import find_commands sub_parsers.completer = lambda prefix, **kwargs: [i for i in list(sub_parsers.choices) + find_commands() if i.startswith(prefix)] args = p.parse_args() if getattr(args, 'json', False): for logger in logging.Logger.manager.loggerDict: if logger not in ('fetch', 'progress'): logging.getLogger(logger).setLevel(logging.CRITICAL + 1) if args.debug: logging.disable(logging.NOTSET) logging.basicConfig(level=logging.DEBUG) if (not main_init.is_initialized() and 'init' not in sys.argv and 'info' not in sys.argv): if hasattr(args, 'name') and hasattr(args, 'prefix'): import conda.config as config from conda.cli import common if common.get_prefix(args) == config.root_dir: sys.exit("""\ Error: This installation of conda is not initialized. Use 'conda create -n envname' to create a conda environment and 'source activate envname' to activate it. # Note that pip installing conda is not the recommended way for setting up your # system. The recommended way for setting up a conda system is by installing # Miniconda, see: http://repo.continuum.io/miniconda/index.html""") args_func(args, p) def args_func(args, p): from conda.cli import common use_json = getattr(args, 'json', False) try: args.func(args, p) except RuntimeError as e: if 'maximum recursion depth exceeded' in str(e): print_issue_message(e, use_json=use_json) raise common.error_and_exit(str(e), json=use_json) except Exception as e: print_issue_message(e, use_json=use_json) raise def print_issue_message(e, use_json=False): from conda.cli import common if e.__class__.__name__ not in ('ScannerError', 'ParserError'): message = """\ An unexpected error has occurred, please consider sending the following traceback to the conda GitHub issue tracker at: https://github.com/conda/conda/issues Include the output of the command 'conda info' in your report. """ if use_json: import traceback common.error_and_exit(message + traceback.format_exc(), error_type="UnexpectedError", json=True) print(message) if __name__ == '__main__': main()
true
true
f72c52094e0d1fefbdc0188332f4f3efdc92129b
4,055
py
Python
semantic-conventions/src/opentelemetry/semconv/model/constraints.py
bogdandrutu/build-tools
08bec45f36f112751a2ea0785368a4fa8e2add6a
[ "Apache-2.0" ]
null
null
null
semantic-conventions/src/opentelemetry/semconv/model/constraints.py
bogdandrutu/build-tools
08bec45f36f112751a2ea0785368a4fa8e2add6a
[ "Apache-2.0" ]
null
null
null
semantic-conventions/src/opentelemetry/semconv/model/constraints.py
bogdandrutu/build-tools
08bec45f36f112751a2ea0785368a4fa8e2add6a
[ "Apache-2.0" ]
null
null
null
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass, field, replace from typing import List, Tuple, Set from opentelemetry.semconv.model.exceptions import ValidationError from opentelemetry.semconv.model.semantic_attribute import SemanticAttribute from opentelemetry.semconv.model.utils import validate_values from ruamel.yaml.comments import CommentedSeq # We cannot frozen due to later evaluation of the attributes @dataclass class AnyOf: """Defines a constraint where at least one of the list of attributes must be set. The implementation of this class is evaluated in two times. At parsing time, the choice_list_ids field is populated. After all yaml files are parsed, the choice_list_attributes field is populated with the object representation of the attribute ids of choice_list_ids. Attributes: choice_list_ids Contains the lists of attributes ids that must be set. inherited True if it is inherited by another semantic convention, i.e. by include or extends. choice_list_attributes Contains the list of attributes objects. This list contains the same lists of attributes of choice_list_ids but instead of the ids, it contains the respective objects representations. _yaml_src_position Contains the position in the YAML file of the AnyOf attribute """ choice_list_ids: Tuple[Tuple[str, ...]] inherited: bool = False choice_list_attributes: Tuple[Tuple[SemanticAttribute, ...]] = () _yaml_src_position: int = 0 def __eq__(self, other): if not isinstance(other, AnyOf): return False return self.choice_list_ids == other.choice_list_ids def __hash__(self): return hash(self.choice_list_ids) def add_attributes(self, attr: List[SemanticAttribute]): self.choice_list_attributes += (attr,) def inherit_anyof(self): return replace(self, inherited=True) @dataclass(frozen=True) class Include: semconv_id: str def parse_constraints(yaml_constraints): """ This method parses the yaml representation for semantic convention attributes creating a list of Constraint objects. """ constraints = () allowed_keys = ("include", "any_of") for constraint in yaml_constraints: validate_values(constraint, allowed_keys) if len(constraint.keys()) > 1: position = constraint.lc.data[list(constraint)[1]] msg = ( "Invalid entry in constraint array - multiple top-level keys in entry." ) raise ValidationError.from_yaml_pos(position, msg) if "include" in constraint: constraints += (Include(constraint.get("include")),) elif "any_of" in constraint: choice_sets = () for constraint_list in constraint.get("any_of"): inner_id_list = () if isinstance(constraint_list, CommentedSeq): inner_id_list = tuple( attr_constraint for attr_constraint in constraint_list ) else: inner_id_list += (constraint_list,) choice_sets += (inner_id_list,) any_of = AnyOf(choice_sets) any_of._yaml_src_position = constraint.get("any_of").lc.data constraints += (any_of,) return constraints
41.377551
119
0.67349
from dataclasses import dataclass, field, replace from typing import List, Tuple, Set from opentelemetry.semconv.model.exceptions import ValidationError from opentelemetry.semconv.model.semantic_attribute import SemanticAttribute from opentelemetry.semconv.model.utils import validate_values from ruamel.yaml.comments import CommentedSeq @dataclass class AnyOf: choice_list_ids: Tuple[Tuple[str, ...]] inherited: bool = False choice_list_attributes: Tuple[Tuple[SemanticAttribute, ...]] = () _yaml_src_position: int = 0 def __eq__(self, other): if not isinstance(other, AnyOf): return False return self.choice_list_ids == other.choice_list_ids def __hash__(self): return hash(self.choice_list_ids) def add_attributes(self, attr: List[SemanticAttribute]): self.choice_list_attributes += (attr,) def inherit_anyof(self): return replace(self, inherited=True) @dataclass(frozen=True) class Include: semconv_id: str def parse_constraints(yaml_constraints): constraints = () allowed_keys = ("include", "any_of") for constraint in yaml_constraints: validate_values(constraint, allowed_keys) if len(constraint.keys()) > 1: position = constraint.lc.data[list(constraint)[1]] msg = ( "Invalid entry in constraint array - multiple top-level keys in entry." ) raise ValidationError.from_yaml_pos(position, msg) if "include" in constraint: constraints += (Include(constraint.get("include")),) elif "any_of" in constraint: choice_sets = () for constraint_list in constraint.get("any_of"): inner_id_list = () if isinstance(constraint_list, CommentedSeq): inner_id_list = tuple( attr_constraint for attr_constraint in constraint_list ) else: inner_id_list += (constraint_list,) choice_sets += (inner_id_list,) any_of = AnyOf(choice_sets) any_of._yaml_src_position = constraint.get("any_of").lc.data constraints += (any_of,) return constraints
true
true
f72c526d85a4169c9d8e5811a9e733fff90c8df8
3,136
py
Python
gitea_api/models/issue_labels_option.py
r7l/python-gitea-api
31d3dba27ea7e551e2048a1230c4ab4d73365006
[ "MIT" ]
1
2022-02-09T23:43:26.000Z
2022-02-09T23:43:26.000Z
gitea_api/models/issue_labels_option.py
r7l/python-gitea-api
31d3dba27ea7e551e2048a1230c4ab4d73365006
[ "MIT" ]
null
null
null
gitea_api/models/issue_labels_option.py
r7l/python-gitea-api
31d3dba27ea7e551e2048a1230c4ab4d73365006
[ "MIT" ]
null
null
null
# coding: utf-8 """ Gitea API. This documentation describes the Gitea API. # noqa: E501 OpenAPI spec version: 1.16.7 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class IssueLabelsOption(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'labels': 'list[int]' } attribute_map = { 'labels': 'labels' } def __init__(self, labels=None): # noqa: E501 """IssueLabelsOption - a model defined in Swagger""" # noqa: E501 self._labels = None self.discriminator = None if labels is not None: self.labels = labels @property def labels(self): """Gets the labels of this IssueLabelsOption. # noqa: E501 list of label IDs # noqa: E501 :return: The labels of this IssueLabelsOption. # noqa: E501 :rtype: list[int] """ return self._labels @labels.setter def labels(self, labels): """Sets the labels of this IssueLabelsOption. list of label IDs # noqa: E501 :param labels: The labels of this IssueLabelsOption. # noqa: E501 :type: list[int] """ self._labels = labels def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(IssueLabelsOption, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, IssueLabelsOption): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
27.752212
80
0.552934
import pprint import re import six class IssueLabelsOption(object): swagger_types = { 'labels': 'list[int]' } attribute_map = { 'labels': 'labels' } def __init__(self, labels=None): self._labels = None self.discriminator = None if labels is not None: self.labels = labels @property def labels(self): return self._labels @labels.setter def labels(self, labels): self._labels = labels def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(IssueLabelsOption, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, IssueLabelsOption): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f72c52cdd198823444e5eba59c73f88ccbadef74
3,334
py
Python
benchmark/startCirq3299.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startCirq3299.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startCirq3299.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=45 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=9 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.Y.on(input_qubit[3])) # number=12 c.append(cirq.H.on(input_qubit[3])) # number=36 c.append(cirq.CZ.on(input_qubit[2],input_qubit[3])) # number=37 c.append(cirq.H.on(input_qubit[3])) # number=38 c.append(cirq.H.on(input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[1])) # number=6 c.append(cirq.H.on(input_qubit[2])) # number=24 c.append(cirq.CZ.on(input_qubit[3],input_qubit[2])) # number=25 c.append(cirq.H.on(input_qubit[2])) # number=26 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.H.on(input_qubit[2])) # number=42 c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=43 c.append(cirq.H.on(input_qubit[2])) # number=44 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=39 c.append(cirq.X.on(input_qubit[2])) # number=40 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=41 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=31 c.append(cirq.H.on(input_qubit[3])) # number=16 c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=17 c.append(cirq.H.on(input_qubit[3])) # number=18 c.append(cirq.X.on(input_qubit[3])) # number=14 c.append(cirq.H.on(input_qubit[3])) # number=32 c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=33 c.append(cirq.H.on(input_qubit[3])) # number=34 c.append(cirq.rx(-1.928937889304133).on(input_qubit[1])) # number=35 c.append(cirq.Y.on(input_qubit[2])) # number=10 c.append(cirq.Y.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[1])) # number=20 c.append(cirq.X.on(input_qubit[1])) # number=21 c.append(cirq.X.on(input_qubit[3])) # number=27 c.append(cirq.X.on(input_qubit[3])) # number=28 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq3299.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
37.044444
77
0.678164
import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np from cirq.contrib.svg import SVGCircuit def make_circuit(n: int, input_qubit): c = cirq.Circuit() c.append(cirq.H.on(input_qubit[0])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.Y.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.CZ.on(input_qubit[2],input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.CZ.on(input_qubit[3],input_qubit[2])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) c.append(cirq.X.on(input_qubit[2])) c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.X.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.rx(-1.928937889304133).on(input_qubit[1])) c.append(cirq.Y.on(input_qubit[2])) c.append(cirq.Y.on(input_qubit[2])) c.append(cirq.X.on(input_qubit[1])) c.append(cirq.X.on(input_qubit[1])) c.append(cirq.X.on(input_qubit[3])) c.append(cirq.X.on(input_qubit[3])) c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq3299.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
true
true
f72c52e95f901b6fd8527d85d0d774d80df5f455
842
py
Python
zeeguu/api/api/teacher_dashboard/student_words.py
mircealungu/Zeeguu-API-2
1e8ea7f5dd0b883ed2d714b9324162b1a8edd170
[ "MIT" ]
8
2018-02-06T15:47:55.000Z
2021-05-26T15:24:49.000Z
zeeguu/api/api/teacher_dashboard/student_words.py
mircealungu/Zeeguu-API-2
1e8ea7f5dd0b883ed2d714b9324162b1a8edd170
[ "MIT" ]
57
2018-02-02T19:54:38.000Z
2021-07-15T15:45:15.000Z
zeeguu/api/api/teacher_dashboard/student_words.py
mircealungu/Zeeguu-API-2
1e8ea7f5dd0b883ed2d714b9324162b1a8edd170
[ "MIT" ]
13
2017-10-12T09:05:19.000Z
2020-02-19T09:38:01.000Z
import zeeguu.core from zeeguu.core.sql.learner.words import words_not_studied, learned_words from ._common_api_parameters import _get_student_cohort_and_period_from_POST_params from .. import api, json_result, with_session db = zeeguu.core.db @api.route("/student_words_not_studied", methods=["POST"]) @with_session def student_words_not_studied(): user, cohort, from_str, to_str = _get_student_cohort_and_period_from_POST_params() stats = words_not_studied(user.id, cohort.language_id, from_str, to_str) return json_result(stats) @api.route("/student_learned_words", methods=["POST"]) @with_session def student_learned_words(): user, cohort, from_date, to_date = _get_student_cohort_and_period_from_POST_params() stats = learned_words(user.id, cohort.language_id, from_date, to_date) return json_result(stats)
35.083333
88
0.800475
import zeeguu.core from zeeguu.core.sql.learner.words import words_not_studied, learned_words from ._common_api_parameters import _get_student_cohort_and_period_from_POST_params from .. import api, json_result, with_session db = zeeguu.core.db @api.route("/student_words_not_studied", methods=["POST"]) @with_session def student_words_not_studied(): user, cohort, from_str, to_str = _get_student_cohort_and_period_from_POST_params() stats = words_not_studied(user.id, cohort.language_id, from_str, to_str) return json_result(stats) @api.route("/student_learned_words", methods=["POST"]) @with_session def student_learned_words(): user, cohort, from_date, to_date = _get_student_cohort_and_period_from_POST_params() stats = learned_words(user.id, cohort.language_id, from_date, to_date) return json_result(stats)
true
true
f72c53192b9962222a935bcba714f77187770d13
186
py
Python
Reliability_Tests/ex78.py
dieterch/dReliaCalc
1e0a06e904f3a60527c3a6ae0f45c666a9b48128
[ "MIT" ]
null
null
null
Reliability_Tests/ex78.py
dieterch/dReliaCalc
1e0a06e904f3a60527c3a6ae0f45c666a9b48128
[ "MIT" ]
null
null
null
Reliability_Tests/ex78.py
dieterch/dReliaCalc
1e0a06e904f3a60527c3a6ae0f45c666a9b48128
[ "MIT" ]
null
null
null
from reliability.Reliability_testing import one_sample_proportion result = one_sample_proportion(trials=30, successes=29) print(result) ''' (0.8278305443665873, 0.9991564290733695) '''
23.25
65
0.817204
from reliability.Reliability_testing import one_sample_proportion result = one_sample_proportion(trials=30, successes=29) print(result)
true
true
f72c533b9f24bb347b96c3082d58404f5c3dff10
592
py
Python
examples/display_feed_example.py
UniquePassive/randcam
7c8dc977cfaf5eddb9b06f6280ab268526114d40
[ "Apache-2.0" ]
1
2018-06-04T04:10:06.000Z
2018-06-04T04:10:06.000Z
examples/display_feed_example.py
UniquePassive/randcam
7c8dc977cfaf5eddb9b06f6280ab268526114d40
[ "Apache-2.0" ]
null
null
null
examples/display_feed_example.py
UniquePassive/randcam
7c8dc977cfaf5eddb9b06f6280ab268526114d40
[ "Apache-2.0" ]
1
2018-06-04T04:10:07.000Z
2018-06-04T04:10:07.000Z
import cv2 import binascii from randcam import RandCam with RandCam(0, True) as rc: result, random = rc.seed() while True: result, image = rc.feed.read() cv2.imshow('Captured Image', image) key = cv2.waitKey(1) # 'S' key - reseed if key == ord('s'): result, random = rc.seed() # 'R' key - print random string elif key == ord('r'): byte_array = bytearray(random.getrandbits(8) for i in range(32)) print("random string: %s" % binascii.hexlify(byte_array).decode("utf-8"))
29.6
86
0.554054
import cv2 import binascii from randcam import RandCam with RandCam(0, True) as rc: result, random = rc.seed() while True: result, image = rc.feed.read() cv2.imshow('Captured Image', image) key = cv2.waitKey(1) if key == ord('s'): result, random = rc.seed() elif key == ord('r'): byte_array = bytearray(random.getrandbits(8) for i in range(32)) print("random string: %s" % binascii.hexlify(byte_array).decode("utf-8"))
true
true
f72c534e1699dc5a2e1677045e0d3915c236a50b
12,873
py
Python
info_summary/get_summary_pdf.py
Dangaran/home_station_project
890b342e79e3dd493a8f418ed9283f0d444e5073
[ "CC0-1.0" ]
null
null
null
info_summary/get_summary_pdf.py
Dangaran/home_station_project
890b342e79e3dd493a8f418ed9283f0d444e5073
[ "CC0-1.0" ]
null
null
null
info_summary/get_summary_pdf.py
Dangaran/home_station_project
890b342e79e3dd493a8f418ed9283f0d444e5073
[ "CC0-1.0" ]
null
null
null
import requests import pandas as pd from plotnine import * import json import time from fpdf import FPDF from datetime import datetime # change pandas display options pd.options.display.max_columns = 101 pd.options.display.max_rows = 200 pd.options.display.precision = 7 # get aemet and home information last_day = { 'date_start': int(time.time()) - 86400, 'date_end': int(time.time()) } response_aemet = requests.post('url_to_aws_lambda/get-aemet-data', json=last_day) aemet_info = json.loads(response_aemet.text) response_home = requests.post('url_to_aws_lambda/get-home-data', json=last_day) home_info = json.loads(response_home.text) # merge dataframes aemet_info_df = pd.DataFrame(aemet_info) aemet_info_df.sort_values(by="timestamp", inplace=True) home_info_df = pd.DataFrame(home_info) home_info_df.sort_values(by="timestamp", inplace=True) last_day_info = pd.merge(aemet_info_df, home_info_df, on='timestamp', suffixes=("_aemet", "_home")) last_day_info = last_day_info.iloc[100:124, :] # ----------------------------------------------------------- # # TEMPERATURE ANALYSIS # # ----------------------------------------------------------- # prepare data for plotting home_temp_threshold = 20 # transform hour column to string and sort them last_day_info['hour'] = last_day_info['hour'].astype(str) last_day_info['hour'] = pd.Categorical(last_day_info['hour'], categories=last_day_info['hour']) # melt data to plot temperatures temp_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['thermal_sensation', 'temperature_aemet', 'temperature_home'], var_name='temp_loc', value_name='temp_value') # change temp_loc to more readable strings for plotting temp_data_to_plot['temp_loc'].replace({'thermal_sensation': 'Thermal sensation (outside)', 'temperature_aemet': 'Temperature (outside)', 'temperature_home': 'Temperature (home)',}, inplace=True) # get home data home_temp_plot = temp_data_to_plot.loc[temp_data_to_plot.temp_loc == 'Temperature (home)', :] # make the plot temp_plot = ggplot(temp_data_to_plot, aes(x = 'hour', y = 'temp_value', color = 'temp_loc', group = 'temp_loc')) +\ geom_line() +\ geom_point(size = .5) +\ geom_point(aes(x='hour', y='temp_value'), size = .5, color = ['#FF6633' if value <= home_temp_threshold else '#64f564' for value in list(home_temp_plot['temp_value'])], data = home_temp_plot) +\ geom_hline(aes(yintercept= home_temp_threshold), size = 1, linetype = 'dotted', alpha = .2) +\ labs(title = 'Differences in temperature between outside and inside your house', x = 'Hour', y = 'Temperature (ºC)', color='') +\ scale_color_manual(values = ['#64f564', '#e6454a', '#6bb8ff']) +\ theme_classic() +\ theme(plot_title=element_text(face='bold', ha= 'center', size = 10)) ggsave(plot=temp_plot, filename='./today_plots/temp_plot.png', dpi=100) # ----------------------------------------------------------- # # HUMIDITY ANALYSIS # # ----------------------------------------------------------- # prepare plot hum_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['humidity_home', 'humidity_aemet'], var_name='hum_loc', value_name='hum_value') hum_data_to_plot.hum_value = pd.to_numeric(hum_data_to_plot.hum_value, errors = 'raise') hum_data_to_plot['hum_loc'].replace({'humidity_aemet': 'Humidity (outside)', 'humidity_home': 'Humidity (home)',}, inplace=True) # create the plot hum_plot = ggplot(hum_data_to_plot, aes(x = 'hour', y = 'hum_value', fill = 'hum_loc')) +\ geom_bar(stat = 'identity', position='dodge', color = 'grey') +\ labs(title = 'Differences in humidity between outside and inside your house', x = 'Hour', y = 'Relative humidity (%)', fill='') +\ scale_fill_manual(values = ['#9da6d4', '#4f66e0']) +\ theme_classic() +\ theme(plot_title=element_text(face='bold', ha= 'center', size = 10)) ggsave(plot=hum_plot, filename='./today_plots/hum_plot.png', dpi=100) # ----------------------------------------------------------- # # WIND ANALYSIS # # ----------------------------------------------------------- # Wind information # avg and max speed avg_wind_speed = round(last_day_info.avg_wind_speed.apply(lambda x: int(x)).mean(), 2) max_wind_speed = round(last_day_info.max_wind_speed.apply(lambda x: int(x)).max(), 2) # prepare plot # count number of cardinal directions cardinal_dir_list = ['N', 'NE', 'E', 'SE', 'S', 'SO', 'O', 'NO'] wind_dir_df = last_day_info.wind_direction.value_counts().to_frame() wind_dir_df.reset_index(inplace =True) wind_dir_df.rename(columns = {'index': 'cardinal_direction'}, inplace = True) wind_dir_df # complete cardinal column missing_dir = list(set(cardinal_dir_list) - set(wind_dir_df.cardinal_direction.to_list())) for direction in missing_dir: wind_dir_df = wind_dir_df.append({'cardinal_direction': direction, 'wind_direction': 0}, ignore_index=True) wind_dir_df # create column with correct order to plot wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_direction').reset_index(drop = True) wind_dir_df['cardinal_order'] = [2, 0, 1, 7, 6, 4, 3, 5] wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_order') wind_dir_df.index = wind_dir_df.cardinal_order # create x and y axis wind_dir_df['x_axis'] = [0, int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']), int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'E', 'wind_direction']), int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']), 0, int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'O', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])] wind_dir_df['y_axis'] = [int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'N', 'wind_direction']), int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']), 0, int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'S', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']), 0, int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])] # remove 0 columns to plot wind_dir_df = wind_dir_df.loc[wind_dir_df.wind_direction != 0, :] # create the plot wind_plot = ggplot(aes(x = 'x_axis', y = 'y_axis'), wind_dir_df) +\ geom_point(size = .3, color = 'darkgreen') +\ geom_polygon(alpha = .2) +\ xlim(-24, 24) +\ ylim(-24, 24) +\ geom_segment(aes(x=0, xend=22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ geom_segment(aes(x=0, xend=-22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ geom_segment(aes(x=0, xend=0, y=0, yend=22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ geom_segment(aes(x=0, xend=0, y=0, yend=-22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ annotate('text', x=23, y= 0, label = 'E', color = 'darkgreen') +\ annotate('text', x=-23.3, y= 0, label = 'O', color = 'darkgreen') +\ annotate('text', x=0, y= 24, label = 'N', color = 'darkgreen') +\ annotate('text', x=0, y= -24, label = 'S', color = 'darkgreen') +\ labs(title = 'Wind direction over the last 24 hours', x = '', y = '') +\ theme_classic() +\ theme(plot_title=element_text(face='bold', ha= 'center', size = 15), panel_grid_major = element_blank(), panel_grid_minor = element_blank(), panel_background = element_blank(), axis_line = element_blank(), axis_ticks_major = element_blank(), axis_text = element_blank()) ggsave(plot=wind_plot, filename='./today_plots/wind_plot.png', dpi=100) # ----------------------------------------------------------- # # SKY ANALYSIS # # ----------------------------------------------------------- most_common_sky = last_day_info.sky_condition.value_counts().idxmax() snow_probability = round(last_day_info.snow_probability.apply(lambda x: int(x)).mean(), 2) precipitation_probability = round(last_day_info.precipitation_probability.apply(lambda x: int(x)).mean(), 2) most_common_warning_lvl = last_day_info.warning_level.value_counts().idxmax() total_precipitation = round(last_day_info.precipitation.apply(lambda x: int(x)).sum(), 2) # ----------------------------------------------------------- # # PEOPLE ANALYSIS # # ----------------------------------------------------------- # Check number of people people_df = last_day_info.loc[:, ['hour', 'pic_name']] people_df.pic_name = people_df.pic_name.fillna('No_0_data') people_df['people_count'] = people_df.pic_name.apply(lambda x: int(x.split('_')[1])) hours_with_people_at_home = people_df.loc[people_df.people_count > 0].shape[0] most_people_in_room = people_df.people_count.value_counts(ascending = True).index[0] rows_with_most_people = people_df.loc[people_df.people_count == most_people_in_room] hours_with_most_people = rows_with_most_people.hour.to_list() pics_names = rows_with_most_people.pic_name.to_list() # ----------------------------------------------------------- # # PDF CREATION # # ----------------------------------------------------------- # export information in pdf # extract date today_timestamp = int(last_day_info.timestamp.reset_index(drop =True)[5]) today_date = datetime.utcfromtimestamp(today_timestamp).strftime('%d/%m/%Y') # create pdf to export pdf = FPDF() pdf.add_page() pdf.set_xy(0, 5) pdf.set_font('arial', 'B', 12) pdf.cell(0, 10, 'Home report from {}'.format(today_date), 0, 2, 'C') # title pdf.cell(5) # subtitle pdf.set_font('arial', '', 10) pdf.cell(0, 10, 'This report was extracted from the information gathered by the sensors from your Raspberry and Aemet.', 0, 2, 'C') pdf.set_font('arial', 'B', 12) # First analysis - Temperature and Humidity pdf.cell(60, 10, 'Temperature Analysis:', 0, 0, 'R') pdf.cell(85, 10, 'Humidity Analysis:', 0, 2, 'R') pdf.image('./today_plots/temp_plot.png', x = 3, y = 35, w = 110, h = 70, type = '', link = '') pdf.image('./today_plots/hum_plot.png', x = 110, y = 35, w = 100, h = 70, type = '', link = '') # second analysis - Sky and wind pdf.set_x(60) pdf.set_y(110) pdf.cell(0, 10, 'Sky Analysis:', 0, 2, 'L') pdf.set_font('arial', '', 10) pdf.cell(0, 7, 'Most common sky in 24 hours: {}'.format(most_common_sky), 0, 2, 'L') pdf.cell(0, 7, 'Most common warning level in 24 hours: {}'.format(most_common_warning_lvl), 0, 2, 'L') pdf.cell(0, 7, 'Probability of Precipitation in 24 hours: {} %'.format(precipitation_probability), 0, 2, 'L') pdf.cell(0, 7, 'Probability of Snow in 24 hours: {} %'.format(snow_probability), 0, 2, 'L') pdf.cell(0, 7, 'Total Precipitation in 24 hours: {} mm'.format(total_precipitation), 0, 2, 'L') pdf.image('./today_plots/wind_plot.png', x = 110, y = 112, w = 70, h = 60, type = '', link = '') # third analysis - Pictures from people pdf.set_y(170) pdf.set_font('arial', 'B', 12) pdf.cell(0, 10, 'Camera Analysis:', 0, 2, 'L') pdf.set_font('arial', '', 10) pdf.cell(0, 7, 'Number of hours with people at home: {}'.format(hours_with_people_at_home), 0, 2, 'L') pdf.cell(0, 7, 'How many people were in the room at the time of maximum capacity?: {}'.format(most_people_in_room), 0, 2, 'L') pdf.cell(0, 7, 'How many hours was the house with the maximum number of people?: {}'.format(rows_with_most_people.shape[0]), 0, 2, 'L') pdf.cell(0, 7, 'What were the hours when the house had the maximum number of people?: {}'.format(', '.join(hours_with_most_people)), 0, 2, 'L') pdf.cell(0, 7, 'What are the pictura names that correspond to those hours?: {}'.format(', '.join(pics_names)), 0, 2, 'L') pdf.image('../rapsberry/camera/images/{}'.format(pics_names[0]), x = 15, y = 200, w = 70, h = 60, type = '', link = '') # save output pdf.output('test.pdf', 'F')
45.487633
210
0.607395
import requests import pandas as pd from plotnine import * import json import time from fpdf import FPDF from datetime import datetime pd.options.display.max_columns = 101 pd.options.display.max_rows = 200 pd.options.display.precision = 7 last_day = { 'date_start': int(time.time()) - 86400, 'date_end': int(time.time()) } response_aemet = requests.post('url_to_aws_lambda/get-aemet-data', json=last_day) aemet_info = json.loads(response_aemet.text) response_home = requests.post('url_to_aws_lambda/get-home-data', json=last_day) home_info = json.loads(response_home.text) aemet_info_df = pd.DataFrame(aemet_info) aemet_info_df.sort_values(by="timestamp", inplace=True) home_info_df = pd.DataFrame(home_info) home_info_df.sort_values(by="timestamp", inplace=True) last_day_info = pd.merge(aemet_info_df, home_info_df, on='timestamp', suffixes=("_aemet", "_home")) last_day_info = last_day_info.iloc[100:124, :] home_temp_threshold = 20 last_day_info['hour'] = last_day_info['hour'].astype(str) last_day_info['hour'] = pd.Categorical(last_day_info['hour'], categories=last_day_info['hour']) temp_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['thermal_sensation', 'temperature_aemet', 'temperature_home'], var_name='temp_loc', value_name='temp_value') temp_data_to_plot['temp_loc'].replace({'thermal_sensation': 'Thermal sensation (outside)', 'temperature_aemet': 'Temperature (outside)', 'temperature_home': 'Temperature (home)',}, inplace=True) home_temp_plot = temp_data_to_plot.loc[temp_data_to_plot.temp_loc == 'Temperature (home)', :] temp_plot = ggplot(temp_data_to_plot, aes(x = 'hour', y = 'temp_value', color = 'temp_loc', group = 'temp_loc')) +\ geom_line() +\ geom_point(size = .5) +\ geom_point(aes(x='hour', y='temp_value'), size = .5, color = ['#FF6633' if value <= home_temp_threshold else '#64f564' for value in list(home_temp_plot['temp_value'])], data = home_temp_plot) +\ geom_hline(aes(yintercept= home_temp_threshold), size = 1, linetype = 'dotted', alpha = .2) +\ labs(title = 'Differences in temperature between outside and inside your house', x = 'Hour', y = 'Temperature (ºC)', color='') +\ scale_color_manual(values = ['#64f564', '#e6454a', '#6bb8ff']) +\ theme_classic() +\ theme(plot_title=element_text(face='bold', ha= 'center', size = 10)) ggsave(plot=temp_plot, filename='./today_plots/temp_plot.png', dpi=100) hum_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['humidity_home', 'humidity_aemet'], var_name='hum_loc', value_name='hum_value') hum_data_to_plot.hum_value = pd.to_numeric(hum_data_to_plot.hum_value, errors = 'raise') hum_data_to_plot['hum_loc'].replace({'humidity_aemet': 'Humidity (outside)', 'humidity_home': 'Humidity (home)',}, inplace=True) hum_plot = ggplot(hum_data_to_plot, aes(x = 'hour', y = 'hum_value', fill = 'hum_loc')) +\ geom_bar(stat = 'identity', position='dodge', color = 'grey') +\ labs(title = 'Differences in humidity between outside and inside your house', x = 'Hour', y = 'Relative humidity (%)', fill='') +\ scale_fill_manual(values = ['#9da6d4', '#4f66e0']) +\ theme_classic() +\ theme(plot_title=element_text(face='bold', ha= 'center', size = 10)) ggsave(plot=hum_plot, filename='./today_plots/hum_plot.png', dpi=100) avg_wind_speed = round(last_day_info.avg_wind_speed.apply(lambda x: int(x)).mean(), 2) max_wind_speed = round(last_day_info.max_wind_speed.apply(lambda x: int(x)).max(), 2) cardinal_dir_list = ['N', 'NE', 'E', 'SE', 'S', 'SO', 'O', 'NO'] wind_dir_df = last_day_info.wind_direction.value_counts().to_frame() wind_dir_df.reset_index(inplace =True) wind_dir_df.rename(columns = {'index': 'cardinal_direction'}, inplace = True) wind_dir_df missing_dir = list(set(cardinal_dir_list) - set(wind_dir_df.cardinal_direction.to_list())) for direction in missing_dir: wind_dir_df = wind_dir_df.append({'cardinal_direction': direction, 'wind_direction': 0}, ignore_index=True) wind_dir_df wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_direction').reset_index(drop = True) wind_dir_df['cardinal_order'] = [2, 0, 1, 7, 6, 4, 3, 5] wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_order') wind_dir_df.index = wind_dir_df.cardinal_order wind_dir_df['x_axis'] = [0, int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']), int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'E', 'wind_direction']), int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']), 0, int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'O', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])] wind_dir_df['y_axis'] = [int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'N', 'wind_direction']), int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']), 0, int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'S', 'wind_direction']), int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']), 0, int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])] wind_dir_df = wind_dir_df.loc[wind_dir_df.wind_direction != 0, :] wind_plot = ggplot(aes(x = 'x_axis', y = 'y_axis'), wind_dir_df) +\ geom_point(size = .3, color = 'darkgreen') +\ geom_polygon(alpha = .2) +\ xlim(-24, 24) +\ ylim(-24, 24) +\ geom_segment(aes(x=0, xend=22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ geom_segment(aes(x=0, xend=-22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ geom_segment(aes(x=0, xend=0, y=0, yend=22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ geom_segment(aes(x=0, xend=0, y=0, yend=-22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\ annotate('text', x=23, y= 0, label = 'E', color = 'darkgreen') +\ annotate('text', x=-23.3, y= 0, label = 'O', color = 'darkgreen') +\ annotate('text', x=0, y= 24, label = 'N', color = 'darkgreen') +\ annotate('text', x=0, y= -24, label = 'S', color = 'darkgreen') +\ labs(title = 'Wind direction over the last 24 hours', x = '', y = '') +\ theme_classic() +\ theme(plot_title=element_text(face='bold', ha= 'center', size = 15), panel_grid_major = element_blank(), panel_grid_minor = element_blank(), panel_background = element_blank(), axis_line = element_blank(), axis_ticks_major = element_blank(), axis_text = element_blank()) ggsave(plot=wind_plot, filename='./today_plots/wind_plot.png', dpi=100) most_common_sky = last_day_info.sky_condition.value_counts().idxmax() snow_probability = round(last_day_info.snow_probability.apply(lambda x: int(x)).mean(), 2) precipitation_probability = round(last_day_info.precipitation_probability.apply(lambda x: int(x)).mean(), 2) most_common_warning_lvl = last_day_info.warning_level.value_counts().idxmax() total_precipitation = round(last_day_info.precipitation.apply(lambda x: int(x)).sum(), 2) people_df = last_day_info.loc[:, ['hour', 'pic_name']] people_df.pic_name = people_df.pic_name.fillna('No_0_data') people_df['people_count'] = people_df.pic_name.apply(lambda x: int(x.split('_')[1])) hours_with_people_at_home = people_df.loc[people_df.people_count > 0].shape[0] most_people_in_room = people_df.people_count.value_counts(ascending = True).index[0] rows_with_most_people = people_df.loc[people_df.people_count == most_people_in_room] hours_with_most_people = rows_with_most_people.hour.to_list() pics_names = rows_with_most_people.pic_name.to_list() today_timestamp = int(last_day_info.timestamp.reset_index(drop =True)[5]) today_date = datetime.utcfromtimestamp(today_timestamp).strftime('%d/%m/%Y') pdf = FPDF() pdf.add_page() pdf.set_xy(0, 5) pdf.set_font('arial', 'B', 12) pdf.cell(0, 10, 'Home report from {}'.format(today_date), 0, 2, 'C') pdf.cell(5) pdf.set_font('arial', '', 10) pdf.cell(0, 10, 'This report was extracted from the information gathered by the sensors from your Raspberry and Aemet.', 0, 2, 'C') pdf.set_font('arial', 'B', 12) pdf.cell(60, 10, 'Temperature Analysis:', 0, 0, 'R') pdf.cell(85, 10, 'Humidity Analysis:', 0, 2, 'R') pdf.image('./today_plots/temp_plot.png', x = 3, y = 35, w = 110, h = 70, type = '', link = '') pdf.image('./today_plots/hum_plot.png', x = 110, y = 35, w = 100, h = 70, type = '', link = '') pdf.set_x(60) pdf.set_y(110) pdf.cell(0, 10, 'Sky Analysis:', 0, 2, 'L') pdf.set_font('arial', '', 10) pdf.cell(0, 7, 'Most common sky in 24 hours: {}'.format(most_common_sky), 0, 2, 'L') pdf.cell(0, 7, 'Most common warning level in 24 hours: {}'.format(most_common_warning_lvl), 0, 2, 'L') pdf.cell(0, 7, 'Probability of Precipitation in 24 hours: {} %'.format(precipitation_probability), 0, 2, 'L') pdf.cell(0, 7, 'Probability of Snow in 24 hours: {} %'.format(snow_probability), 0, 2, 'L') pdf.cell(0, 7, 'Total Precipitation in 24 hours: {} mm'.format(total_precipitation), 0, 2, 'L') pdf.image('./today_plots/wind_plot.png', x = 110, y = 112, w = 70, h = 60, type = '', link = '') pdf.set_y(170) pdf.set_font('arial', 'B', 12) pdf.cell(0, 10, 'Camera Analysis:', 0, 2, 'L') pdf.set_font('arial', '', 10) pdf.cell(0, 7, 'Number of hours with people at home: {}'.format(hours_with_people_at_home), 0, 2, 'L') pdf.cell(0, 7, 'How many people were in the room at the time of maximum capacity?: {}'.format(most_people_in_room), 0, 2, 'L') pdf.cell(0, 7, 'How many hours was the house with the maximum number of people?: {}'.format(rows_with_most_people.shape[0]), 0, 2, 'L') pdf.cell(0, 7, 'What were the hours when the house had the maximum number of people?: {}'.format(', '.join(hours_with_most_people)), 0, 2, 'L') pdf.cell(0, 7, 'What are the pictura names that correspond to those hours?: {}'.format(', '.join(pics_names)), 0, 2, 'L') pdf.image('../rapsberry/camera/images/{}'.format(pics_names[0]), x = 15, y = 200, w = 70, h = 60, type = '', link = '') pdf.output('test.pdf', 'F')
true
true
f72c5491decdb5fc627448e653e80715d6890df3
473
py
Python
duck/FlyBehavior.py
rinman24/headfirst-python
1c6a12dc04475fae06e333a9abcdefee0bdda5d6
[ "MIT" ]
null
null
null
duck/FlyBehavior.py
rinman24/headfirst-python
1c6a12dc04475fae06e333a9abcdefee0bdda5d6
[ "MIT" ]
null
null
null
duck/FlyBehavior.py
rinman24/headfirst-python
1c6a12dc04475fae06e333a9abcdefee0bdda5d6
[ "MIT" ]
null
null
null
from abc import ABC, abstractmethod # abstract class class FlyBehavior(ABC): @staticmethod @abstractmethod def fly(): pass # Concrete implementations class FlyWithWings(FlyBehavior): @staticmethod def fly(): print("I'm flying!!") class FlyNoWay(FlyBehavior): @staticmethod def fly(): print("I can't fly.") class FlyWithRockets(FlyBehavior): @staticmethod def fly(): print("I'm flying with rockets!!")
18.92
42
0.649049
from abc import ABC, abstractmethod class FlyBehavior(ABC): @staticmethod @abstractmethod def fly(): pass class FlyWithWings(FlyBehavior): @staticmethod def fly(): print("I'm flying!!") class FlyNoWay(FlyBehavior): @staticmethod def fly(): print("I can't fly.") class FlyWithRockets(FlyBehavior): @staticmethod def fly(): print("I'm flying with rockets!!")
true
true
f72c564b609e2ec63105a6116e9ade4a3f942eae
1,684
py
Python
api/chat_api/migrations/0001_create_message_model.py
gda2048/ChatAPI
6efab6fb5b9d1ff74b44075cd2d13cbb6cd06189
[ "MIT" ]
null
null
null
api/chat_api/migrations/0001_create_message_model.py
gda2048/ChatAPI
6efab6fb5b9d1ff74b44075cd2d13cbb6cd06189
[ "MIT" ]
5
2020-06-06T01:18:14.000Z
2021-06-10T19:45:08.000Z
api/chat_api/migrations/0001_create_message_model.py
gda2048/ChatAPI
6efab6fb5b9d1ff74b44075cd2d13cbb6cd06189
[ "MIT" ]
null
null
null
# Generated by Django 2.2.5 on 2020-02-04 21:51 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.CharField(help_text='Содержание письма может быть максимум в 4095 символов', max_length=4095, verbose_name='Содержание сообщения')), ('subject', models.CharField(help_text='Тема сообщения может быть максимум в 255 символов', max_length=255, verbose_name='Тема сообщения')), ('is_read', models.BooleanField(default=False, verbose_name='Прочитано ли?')), ('creation_date', models.DateTimeField(auto_now=True, verbose_name='Дата создания')), ('receiver', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='got_messages', to=settings.AUTH_USER_MODEL, verbose_name='Получатель')), ('sender', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='sent_messages', to=settings.AUTH_USER_MODEL, verbose_name='Создатель')), ], options={ 'verbose_name': 'Сообщение', 'verbose_name_plural': 'Сообщения', 'db_table': 'messages', 'ordering': ['-creation_date'], }, ), ]
46.777778
190
0.64905
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.CharField(help_text='Содержание письма может быть максимум в 4095 символов', max_length=4095, verbose_name='Содержание сообщения')), ('subject', models.CharField(help_text='Тема сообщения может быть максимум в 255 символов', max_length=255, verbose_name='Тема сообщения')), ('is_read', models.BooleanField(default=False, verbose_name='Прочитано ли?')), ('creation_date', models.DateTimeField(auto_now=True, verbose_name='Дата создания')), ('receiver', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='got_messages', to=settings.AUTH_USER_MODEL, verbose_name='Получатель')), ('sender', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='sent_messages', to=settings.AUTH_USER_MODEL, verbose_name='Создатель')), ], options={ 'verbose_name': 'Сообщение', 'verbose_name_plural': 'Сообщения', 'db_table': 'messages', 'ordering': ['-creation_date'], }, ), ]
true
true
f72c5744bbab84a804af1d39c17f0245e4c8220a
19,980
py
Python
Tools/python37/Lib/textwrap.py
xxroot/android_universal
af2d8627182f936383d792c1f775d87da50f2f6d
[ "MIT" ]
207
2018-10-01T08:53:01.000Z
2022-03-14T12:15:54.000Z
Tools/python37/Lib/textwrap.py
xxroot/android_universal
af2d8627182f936383d792c1f775d87da50f2f6d
[ "MIT" ]
8
2019-06-29T14:18:51.000Z
2022-02-19T07:30:27.000Z
Tools/python37/Lib/textwrap.py
xxroot/android_universal
af2d8627182f936383d792c1f775d87da50f2f6d
[ "MIT" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward <gward@python.net> import re __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that # some Unicode spaces (like \u00a0) are non-breaking whitespaces. _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 0 .. 'tabsize' spaces, depending on its position in its line. If false, each tab is treated as a single character. tabsize (default: 8) Expand tabs in input text to 0 .. 'tabsize' spaces, unless 'expand_tabs' is false. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. break_on_hyphens (default: true) Allow breaking hyphenated words. If true, wrapping will occur preferably on whitespaces and right after hyphens part of compound words. drop_whitespace (default: true) Drop leading and trailing whitespace from lines. max_lines (default: None) Truncate wrapped lines. placeholder (default: ' [...]') Append to the last line of truncated text. """ unicode_whitespace_trans = {} uspace = ord(' ') for x in _whitespace: unicode_whitespace_trans[ord(x)] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). word_punct = r'[\w!"\'&.,?]' letter = r'[^\d\W]' whitespace = r'[%s]' % re.escape(_whitespace) nowhitespace = '[^' + whitespace[1:] wordsep_re = re.compile(r''' ( # any whitespace %(ws)s+ | # em-dash between words (?<=%(wp)s) -{2,} (?=\w) | # word, possibly hyphenated %(nws)s+? (?: # hyphenated word -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-)) (?= %(lt)s -? %(lt)s) | # end of word (?=%(ws)s|\Z) | # em-dash (?<=%(wp)s) (?=-{2,}\w) ) )''' % {'wp': word_punct, 'lt': letter, 'ws': whitespace, 'nws': nowhitespace}, re.VERBOSE) del word_punct, letter, nowhitespace # This less funky little regex just split on recognized spaces. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ wordsep_simple_re = re.compile(r'(%s+)' % whitespace) del whitespace # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[a-z]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote r'\Z') # end of chunk def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None, placeholder=' [...]'): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.drop_whitespace = drop_whitespace self.break_on_hyphens = break_on_hyphens self.tabsize = tabsize self.max_lines = max_lines self.placeholder = placeholder # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs(self.tabsize) if self.replace_whitespace: text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see _wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' if break_on_hyphens is True, or in: 'Look,', ' ', 'goof-ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', option!' otherwise. """ if self.break_on_hyphens is True: chunks = self.wordsep_re.split(text) else: chunks = self.wordsep_simple_re.split(text) chunks = [c for c in chunks if c] return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 patsearch = self.sentence_end_re.search while i < len(chunks)-1: if chunks[i+1] == " " and patsearch(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ # Figure out when indent is larger than the specified width, and make # sure at least one character is stripped off on every pass if width < 1: space_left = 1 else: space_left = width - cur_len # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(reversed_chunks.pop()) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) if self.max_lines is not None: if self.max_lines > 1: indent = self.subsequent_indent else: indent = self.initial_indent if len(indent) + len(self.placeholder.lstrip()) > self.width: raise ValueError("placeholder too large for max width") # Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse() while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l # Nope, this line is full. else: break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) cur_len = sum(map(len, cur_line)) # If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': cur_len -= len(cur_line[-1]) del cur_line[-1] if cur_line: if (self.max_lines is None or len(lines) + 1 < self.max_lines or (not chunks or self.drop_whitespace and len(chunks) == 1 and not chunks[0].strip()) and cur_len <= width): # Convert current line back to a string and store it in # list of all lines (return value). lines.append(indent + ''.join(cur_line)) else: while cur_line: if (cur_line[-1].strip() and cur_len + len(self.placeholder) <= width): cur_line.append(self.placeholder) lines.append(indent + ''.join(cur_line)) break cur_len -= len(cur_line[-1]) del cur_line[-1] else: if lines: prev_line = lines[-1].rstrip() if (len(prev_line) + len(self.placeholder) <= self.width): lines[-1] = prev_line + self.placeholder break lines.append(indent + self.placeholder.lstrip()) break return lines def _split_chunks(self, text): text = self._munge_whitespace(text) return self._split(text) # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ chunks = self._split_chunks(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) def shorten(text, width, **kwargs): """Collapse and truncate the given text to fit in the given width. The text first has its whitespace collapsed. If it then fits in the *width*, it is returned as is. Otherwise, as many words as possible are joined and then the placeholder is appended:: >>> textwrap.shorten("Hello world!", width=12) 'Hello world!' >>> textwrap.shorten("Hello world!", width=11) 'Hello [...]' """ w = TextWrapper(width=width, max_lines=1, **kwargs) return w.fill(' '.join(text.strip().split())) # -- Loosely related functionality ------------------------------------- _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.) """ # Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply indented than previous winner: # no change (previous winner is still on top). elif indent.startswith(margin): pass # Current line consistent with and no deeper than previous winner: # it's the new winner. elif margin.startswith(indent): margin = indent # Find the largest common whitespace between current line and previous # winner. else: for i, (x, y) in enumerate(zip(margin, indent)): if x != y: margin = margin[:i] break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text def indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that do not consist solely of whitespace characters. """ if predicate is None: def predicate(line): return line.strip() def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if predicate(line) else line) return ''.join(prefixed_lines()) if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print(dedent("Hello there.\n This is indented."))
41.026694
81
0.565716
import re __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten'] _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: unicode_whitespace_trans = {} uspace = ord(' ') for x in _whitespace: unicode_whitespace_trans[ord(x)] = uspace word_punct = r'[\w!"\'&.,?]' letter = r'[^\d\W]' whitespace = r'[%s]' % re.escape(_whitespace) nowhitespace = '[^' + whitespace[1:] wordsep_re = re.compile(r''' ( # any whitespace %(ws)s+ | # em-dash between words (?<=%(wp)s) -{2,} (?=\w) | # word, possibly hyphenated %(nws)s+? (?: # hyphenated word -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-)) (?= %(lt)s -? %(lt)s) | # end of word (?=%(ws)s|\Z) | # em-dash (?<=%(wp)s) (?=-{2,}\w) ) )''' % {'wp': word_punct, 'lt': letter, 'ws': whitespace, 'nws': nowhitespace}, re.VERBOSE) del word_punct, letter, nowhitespace # This less funky little regex just split on recognized spaces. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ wordsep_simple_re = re.compile(r'(%s+)' % whitespace) del whitespace # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[a-z]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' r'\Z') def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None, placeholder=' [...]'): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.drop_whitespace = drop_whitespace self.break_on_hyphens = break_on_hyphens self.tabsize = tabsize self.max_lines = max_lines self.placeholder = placeholder def _munge_whitespace(self, text): if self.expand_tabs: text = text.expandtabs(self.tabsize) if self.replace_whitespace: text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): if self.break_on_hyphens is True: chunks = self.wordsep_re.split(text) else: chunks = self.wordsep_simple_re.split(text) chunks = [c for c in chunks if c] return chunks def _fix_sentence_endings(self, chunks): i = 0 patsearch = self.sentence_end_re.search while i < len(chunks)-1: if chunks[i+1] == " " and patsearch(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): if width < 1: space_left = 1 else: space_left = width - cur_len # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- elif not cur_line: cur_line.append(reversed_chunks.pop()) # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) if self.max_lines is not None: if self.max_lines > 1: indent = self.subsequent_indent else: indent = self.initial_indent if len(indent) + len(self.placeholder.lstrip()) > self.width: raise ValueError("placeholder too large for max width") chunks.reverse() while chunks: cur_line = [] cur_len = 0 if lines: indent = self.subsequent_indent else: indent = self.initial_indent width = self.width - len(indent) if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l else: break if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) cur_len = sum(map(len, cur_line)) if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': cur_len -= len(cur_line[-1]) del cur_line[-1] if cur_line: if (self.max_lines is None or len(lines) + 1 < self.max_lines or (not chunks or self.drop_whitespace and len(chunks) == 1 and not chunks[0].strip()) and cur_len <= width): lines.append(indent + ''.join(cur_line)) else: while cur_line: if (cur_line[-1].strip() and cur_len + len(self.placeholder) <= width): cur_line.append(self.placeholder) lines.append(indent + ''.join(cur_line)) break cur_len -= len(cur_line[-1]) del cur_line[-1] else: if lines: prev_line = lines[-1].rstrip() if (len(prev_line) + len(self.placeholder) <= self.width): lines[-1] = prev_line + self.placeholder break lines.append(indent + self.placeholder.lstrip()) break return lines def _split_chunks(self, text): text = self._munge_whitespace(text) return self._split(text) def wrap(self, text): chunks = self._split_chunks(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): return "\n".join(self.wrap(text)) def wrap(text, width=70, **kwargs): w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): w = TextWrapper(width=width, **kwargs) return w.fill(text) def shorten(text, width, **kwargs): w = TextWrapper(width=width, max_lines=1, **kwargs) return w.fill(' '.join(text.strip().split())) _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent elif indent.startswith(margin): pass elif margin.startswith(indent): margin = indent # Find the largest common whitespace between current line and previous # winner. else: for i, (x, y) in enumerate(zip(margin, indent)): if x != y: margin = margin[:i] break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text def indent(text, prefix, predicate=None): if predicate is None: def predicate(line): return line.strip() def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if predicate(line) else line) return ''.join(prefixed_lines()) if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print(dedent("Hello there.\n This is indented."))
true
true
f72c58b092c81a2ecfe08da7855f4be4cca37499
104,175
py
Python
game2d.py
JeffreyTsang/Brickbreaker
37f0d143e9f937027fc281aef1511d0e9c804b8b
[ "MIT" ]
null
null
null
game2d.py
JeffreyTsang/Brickbreaker
37f0d143e9f937027fc281aef1511d0e9c804b8b
[ "MIT" ]
null
null
null
game2d.py
JeffreyTsang/Brickbreaker
37f0d143e9f937027fc281aef1511d0e9c804b8b
[ "MIT" ]
null
null
null
# game2d.py # Walker M. White (wmw2) # November 14, 2015 """Module to provide simple 2D game support. This module provides all of the classes that are to use (or subclass) to create your game. DO NOT MODIFY THE CODE IN THIS FILE. See the online documentation in Assignment 7 for more guidance. It includes information not displayed in this module.""" # Basic Kivy Modules import kivy import kivy.app # Lower-level kivy modules to support animation from kivy.graphics import * from kivy.graphics.instructions import * from kivy.core.audio import SoundLoader from kivy.config import Config from kivy.clock import Clock from kivy.metrics import dp # Widgets necessary for some technical workarounds from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.uix.image import Image # Additional miscellaneous modules import os, sys, os.path import numpy as np import colormodel # User-defined resources FONT_PATH = str(os.path.join(os.path.dirname(__file__), 'Fonts')) SOUND_PATH = str(os.path.join(os.path.dirname(__file__), 'Sounds')) IMAGE_PATH = str(os.path.join(os.path.dirname(__file__), 'Images')) import kivy.resources kivy.resources.resource_add_path(FONT_PATH) kivy.resources.resource_add_path(SOUND_PATH) kivy.resources.resource_add_path(IMAGE_PATH) ################# TYPING HELPER FUNCTIONS ################# pass # #mark TYPING HELPER FUNCTIONS def _same_side(p1, p2, a, b): """Returns: True if p1, p2 are on the same side of segment ba. Parameter p1: A point Precondition: p1 is a 2-element sequence of numbers (int or float) Parameter p2: A point Precondition: p2 is a 2-element sequence of numbers (int or float) Parameter a: One end of a line segment Precondition: a is a 2-element sequence of numbers (int or float) Parameter b: Another end of a line segment Precondition: b is a 2-element sequence of numbers (int or float) """ ba = np.append(np.subtract(b,a),[0]) cp1 = np.cross(ba,np.subtract(p1,a)) cp2 = np.cross(ba,np.subtract(p2,a)) return np.dot(cp1,cp2) >= 0 def _in_triangle(p, t): """Returns: True if p is in triangle t Parameter p: A point Precondition: p is a 2-element sequence of numbers (int or float) Parameter t: A triangle (defined by 3 vertices) Precondition: t is a 6-element sequence of numbers (int or float) """ return (_same_side(p, t[0:2], t[2:4], t[4:6]) and _same_side(p, t[2:4], t[0:2], t[4:6]) and _same_side(p, t[4:6], t[0:2], t[2:4])) def _is_num(x): """Returns: True if x is an int or float; False otherwise. Parameter x: The value to test Precondition: NONE""" return type(x) in [int,float] def _is_num_tuple(t,size): """Returns: True if t is a sequence of numbers; False otherwise. If the sequence is not of the given size, it also returns False. Parameter t: The value to test Precondition: NONE Parameter size: The size of the sequence Precondition: size is an int >= 0 """ try: return len(t) == size and reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float], t)) except: return False def _is_point_tuple(t,msize): """Returns: True if t is a point sequence (i.e. even sequence of numbers) The point tuple must be size greater than msize, or the function returns False. Parameter t: The value to test Precondition: NONE Parameter msize: The minimum size of the sequence Precondition: msize is an int >= 0 """ try: return len(t) % 2 == 0 and len(t) > msize and \ reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float], t)) except: return False def _is_gobject_list(g): """Returns: True if g is a sequence of GObjects Parameter g: The value to test Precondition: NONE """ try: return len(g) >= 0 and reduce(lambda x, y: x and y, map(lambda z: isinstance(z,GObject), g)) except: return False def _is_color(c): """Returns: True if c represents a color As with Turtles, colors may be colormodel objects or strings. They may also be sequences of 3 or 4 elements. In the case of the latter, the elements of the sequence must all be in the range 0..1. Parameter c: The value to test Precondition: NONE """ if type(c) in [colormodel.RGB, colormodel.HSV]: return True if type(c) in [tuple, list] and 3 <= len(c) <= 4: return reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float] and 0 <= z <= 1, c)) return type(c) == str and c in colormodel._TK_COLOR_MAP def _is_image_file(name): """Returns: True if name is the name of an image file Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(IMAGE_PATH+'/'+name) def _is_font_file(name): """Returns: True if name is the name of an font file Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(FONT_PATH+'/'+name) def _is_sound_file(name): """Returns: True if name is the name of an font file. Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(SOUND_PATH+'/'+name) ################# GEOMETRY PRIMITIVES ################# pass # #mark GEOMETRY PRIMITIVES class GPoint(object): """Instances are points in 2D space. This class is used primarily for recording and handling mouse locations. However, it may also be used for geometry calculations in conjunction with `GMatrix`.""" # PROPERTIES @property def x(self): """The x coordinate of the point. **Invariant**: Must be an int or float.""" return self._x @x.setter def x(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._x = float(value) @property def y(self): """The y coordinate of the point. **Invariant**: Must be an int or float.""" return self._y @y.setter def y(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._y = float(value) # METHODS def __init__(self, x=0, y=0): """**Constructor**: creates a new GPoint value (x,y). :param x: initial x value **Precondition**: value is an int or float. :param y: initial y value **Precondition**: value is an int or float. All values are 0.0 by default. """ self.x = x self.y = y def __eq__(self, other): """**Returns**: True if self and other are equivalent GPoint. This method uses np to test whether the coordinates are "close enough". It does not require exact equality for floats. :param other: value to compare against """ return (type(other) == GPoint and np.allclose(self.list(),other.list())) def __ne__(self, other): """**Returns**: True if self and other are not equivalent GPoint. :param other: value to compare against """ return not self == other def __str__(self): """**Returns**: Readable String representation of this GPoint. """ return "("+str(self.x)+","+str(self.y)+")" def __repr__(self): """**Returns**: Unambiguous String representation of this GPoint. """ return "%s%s" % (self.__class__,self.__str__()) def list(self): """**Returns**: A python list with the contents of this GPoint.""" return [self.x,self.y] def __add__(self, other): """**Returns**: the sum of self and other. The value returned has the same type as self (so it is either a GPoint or is a subclass of GPoint). The contents of this object are not altered. :param other: tuple value to add **Precondition**: value has the same type as self. """ assert (type(other) == type(self)), "value %(value)s is not a of type %(type)s" \ % {'value': `other`, 'type':`type(self)`} result = copy.copy(self) result.x += other.x result.y += other.y return result def __sub__(self, other): """**Returns**: the vector from tail to self. The value returned is a GPoint representing a vector with this point at its head. :param other: the tail value for the new Vector **Precondition**: value is a Point object. """ assert (type(other) == type(self)), "value %(value)s is not a of type %(type)s" \ % {'value': `other`, 'type':`type(self)`} result = copy.copy(self) result.x -= other.x result.y -= other.y return result def __mul__(self, scalar): """**Returns**: the scalar multiple of self and other. The value returned is a new GPoint. The contents of this GPoint are not altered. :param scalar: scalar to multiply by **Precondition**: value is an int or float. """ assert _is_num(scalar), "value %s is not a number" % `scalar` result = copy.copy(self) result.x *= scalar result.y *= scalar result.z *= scalar return result def __rmul__(self, scalar): """**Returns**: the scalar multiple of self and other. The value returned is a new GPoint. The contents of this GPoint are not altered. :param scalar: scalar to multiply by **Precondition**: value is an int or float. """ return self.__mul__(scalar) def interpolate(self, other, alpha): """**Returns**: the interpolation of self and other via alpha. The value returned has the same type as self (so it is either a GPoint or is a subclass of GPoint). The contents of this object are not altered. The resulting value is alpha*self+(1-alpha)*other according to GPoint addition and scalar multiplication. :param other: tuple value to interpolate with **Precondition**: value has the same type as self. :param alpha: scalar to interpolate by **Precondition**: value is an int or float. """ assert (type(other) == type(self)), "value %(value)s is not a of type %(type)s" \ % {'value': `other`, 'type':`type(self)`} assert (type(alpha) in [int,float]), "value %s is not a number" % `alpha` return alpha*self+(1-alpha)*other def distanceTo(self, other): """**Returns**: the Euclidean distance from this point to other :param other: value to compare against **Precondition**: value is a Tuple3D object. """ return np.sqrt((self.x-other.x)*(self.x-other.x)+ (self.y-other.y)*(self.y-other.y)) class GMatrix(object): """Instances are homongenous matrices for graphics transforms. This class is backed by np for fast computation. There are no publicly accessible attributes, as it is not safe to access the internals.""" def __init__(self): """**Constructor**: creates a new 4x4 identify matrix""" self._data = np.identity(4, dtype=np.float32) def __str__(self): """**Returns**: A string representation of this matrix""" return str(self._data) def __repr__(self): """**Returns**: An unambiguous string representation of this matrix""" return str(self.__class__)+str(self) def __mul__(self,other): """**Returns**: a new Matrix that is the premultiplication of this and other. This operation pre-multiplies the matrix on the right. As a result, this allows us to read graphics operations left to right (which is more natural) :param other: the matrix to pre-multiply **Precondition**: a Matrix object """ m = GMatrix() np.dot(other._data,self._data,m._data) return m def __imul__(self,other): """Premultiplies this matrix by other in place This operation pre-multiplies the matrix on the right. As a result, this allows us to read graphics operations left to right (which is more natural) :param other: the matrix to pre-multiply **Precondition**: a Matrix object """ tmp = np.dot(other._data,self._data) np.copyto(self._data,tmp) def copy(self): """**Returns**: a copy of this Matrix""" m = GMatrix() np.copyto(m._data,self._data) return m def inverse(self): """**Returns**: the inverse of this matrix""" m = GMatrix() np.copyto(m._data,np.linalg.inv(self._data)) return m def invert(self): """Inverts this matrix in place""" np.copyto(self._data,np.linalg.inv(self._data)) return self def transpose(self): """**Returns**: the transpose of this matrix""" m = GMatrix() np.copyto(m._data,np.transpose(self._data)) return m def translate(self,x=0,y=0,z=0): """Translates this matrix (in-place) by the given amount :param x: x-coordinate of translation (default 0) **Precondition**: an int or float :param y: y-coordinate of translation (default 0) **Precondition**: an int or float :param z: z-coordinate of translation (default 0) **Precondition**: an int or float """ r = np.identity(4, dtype=np.float32) r[0,3] = x r[1,3] = y r[2,3] = z tmp = np.dot(self._data,r) np.copyto(self._data,tmp) def rotate(self,ang=0,x=0,y=0,z=0): """Rotates this matrix (in place) about the given axis The rotation angle is given in degrees, not radians. Rotation is counterclockwise around the angle of rotation. :param angle: angle of rotation in degrees (default 0) **Precondition**: an int or float :param x: x-coordinate of rotation axis (default 0) **Precondition**: an int or float :param y: y-coordinate of rotation axis (default 0) **Precondition**: an int or float :param z: z-coordinate of rotation axis (default 0) **Precondition**: an int or float """ # Formula taken from https://en.wikipedia.org/wiki/Rotation_matrix c = np.cos(np.radians(ang)) s = np.sin(np.radians(ang)) f = 1-c r = np.identity(4, dtype=np.float32) r[0] = [x*x*f+c, x*y*f-z*s, x*z*f+y*s, 0] r[1] = [y*x*f+z*s, y*y*f+c, y*z*f-x*s, 0] r[2] = [z*x*f-y*s, z*y*f+x*s, z*z*f+c, 0] tmp = np.dot(self._data,r) np.copyto(self._data,tmp) def scale(self,x=1,y=1,z=1): """Scales this matrix (in-place) by the given amount :param x: x-coordinate of the scale (default 1) **Precondition**: an int or float :param y: y-coordinate of the scale (default 1) **Precondition**: an int or float :param z: z-coordinate of the scale (default 1) **Precondition**: an int or float """ s = np.identity(4, dtype=np.float32) s[0,0] = x s[1,1] = y s[2,2] = z tmp = np.dot(self._data,s) np.copyto(self._data,tmp) def _transform(self,x=0,y=0,z=0): """**Returns**: The given point transformed by this matrix The value returned is a tuple. :param x: x-coordinate to transform (default 0) **Precondition**: an int or float :param y: y-coordinate to transform (default 0) **Precondition**: an int or float :param z: z-coordinate to transform (default 0) **Precondition**: an int or float """ b = np.array([x,y,z,1], dtype=np.float32) tmp = np.dot(self._data,b) return map(float,tuple(tmp[:-1])) def transform(self,point): """**Returns**: The given point transformed by this matrix The value returned is a GPoint. :param point: the point to transform **Precondition**: a GPoint """ b = np.array([point.x,point.y,0,1], dtype=np.float32) tmp = np.dot(self._data,b) return GPoint(float(tmp[0]),float(tmp[1])) ################# RECTANGULAR PRIMITIVES ################# pass # #mark RECTANGULAR PRIMITIVES class GObject(object): """Instances provide basic geometry information for drawing to a `GView` You should never make a `GObject` directly. Instead, you should use one of the subclasses: `GRectangle`, `GEllipse`, `GImage`, `GLabel`, `GTriangle`, `GPolygon`, or `GPath`.""" # MUTABLE PROPERTIES @property def x(self): """The horizontal coordinate of the object center. **Invariant**: Must be an int or float.""" return self._trans.x @x.setter def x(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._trans.x = float(value) self._mtrue = False @property def y(self): """The vertical coordinate of the object center.. **Invariant**: Must be an int or float.""" return self._trans.y @y.setter def y(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._trans.y = float(value) self._mtrue = False @property def width(self): """The horizontal width of this shape. Positive values go to the right. **Invariant**: Must be an int or float > 0.""" return self._width @width.setter def width(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value > 0, 'value %s is not positive' % `value` self._width = float(value) if self._defined: self._reset() @property def height(self): """The vertical height of this shape. Positive values go up. **Invariant**: Must be an int or float > 0.""" return self._height @height.setter def height(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value > 0, 'value %s is not positive' % `value` self._height = float(value) if self._defined: self._reset() @property def scale(self): """The scaling factor of this shape. The scale is a fast way to cause a shape to grow or shrink in size. Essentially, the object will multiple the width and height by the scale. So a scale less than 1 will shrink the object, while a scale greater than 1 will enlarge the object. The scale may either be a single number, or a pair of two numbers. If it is a single number, it will scale the width and height by the same amount. If it is a pair, it will scale the width by the first value, and the height by the second. **Invariant**: Must be either a number (int or float) or a pair of numbers.""" return (self._scale.x,self._scale.y) @scale.setter def scale(self,value): # Do some checking here assert _is_num(value) or _is_num_tuple(value,2), \ 'value %s is not a valid scaling factor' % `value` if _is_num(value): self._scale.x = float(value) self._scale.y = float(value) else: self._scale.x = float(value[0]) self._scale.y = float(value[1]) self._mtrue = False @property def angle(self): """The angle of rotation about the center. The angle is measured in degrees (not radians) counter-clockwise. **Invariant**: Must be an int or float.""" return self._rotate.angle @angle.setter def angle(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = np.allclose([self._rotate.angle],[value]) self._rotate.angle = float(value) if not diff: self._mtrue = False @property def fillcolor(self): """The object fill color. This value is used to color the backgrounds or, in the case of solid shapes, the shape interior. The default representation of color in GObject is a 4-element list of floats between 0 and 1 (representing r, g, b, and a). As with the Turtle, you may also assign color an `RGB` or `HSV` object from `colormodel`, or a string with a valid color name. If you chose either of these alternate representations (a string or an object from `colormodel`), Python will automatically convert the result into a 4-element list. **Invariant**: Must be a 4-element list of floats between 0 and 1.""" return self._fillcolor.rgba @fillcolor.setter def fillcolor(self,value): assert _is_color(value), 'value %s is not a valid color' % `value` if type(value) in [tuple, list] and len(value) == 3: value = list(value)+[1.0] elif type(value) in [colormodel.RGB, colormodel.HSV]: value = value.glColor() elif type(value) == str: if value[0] == '#': value = colormodel.RGB.CreateWebColor(c).glColor() else: value = colormodel.RGB.CreateName(c).glColor() self._fillcolor = Color(value[0],value[1],value[2],value[3]) if self._defined: self._reset() @property def linecolor(self): """The object line color. The default representation of color in GObject is a 4-element list of floats between 0 and 1 (representing r, g, b, and a). As with the Turtle, you may also assign color an `RGB` or `HSV` object from `colormodel`, or a string with a valid color name. If you chose either of these alternate representations (a string or an object from `colormodel`), Python will automatically convert the result into a 4-element list. **Invariant**: Must be a 4-element list of floats between 0 and 1.""" return self._linecolor.rgba @linecolor.setter def linecolor(self,value): assert _is_color(value), 'value %s is not a valid color' % `value` if type(value) in [tuple, list] and len(value) == 3: value = list(value)+[1.0] elif type(value) in [colormodel.RGB, colormodel.HSV]: value = value.glColor() elif type(value) == str: if value[0] == '#': value = colormodel.RGB.CreateWebColor(c).glColor() else: value = colormodel.RGB.CreateName(c).glColor() self._linecolor = Color(value[0],value[1],value[2],value[3]) if self._defined: self._reset() @property def name(self): """The name of this object. This value is for debugging purposes only. If you name an object, the name will appear when you convert the object to a string. This will allow you to tell which object is which in your watches. **Invariant**: Must be a string or None.""" return self._name @name.setter def name(self,value): assert value is None or type(value) == str, 'value %s is not a valid name' % `value` self._name = value # DERIVED PROPERTIES @property def left(self): """The left edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x-width/2`. Otherwise, it is the left-most value of the bounding box. Changing this value will shift the center of the object so that the left edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x-self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return min(p0,p1,p2,p3) @left.setter def left(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.left self.x += diff @property def right(self): """The right edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x+width/2`. Otherwise, it is the right-most value of the bounding box. Changing this value will shift the center of the object so that the right edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x+self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return max(p0,p1,p2,p3) @right.setter def right(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.right self.x += diff @property def top(self): """The vertical coordinate of the top edge. The value depends on the current angle of rotation. If rotation is 0, it is `y+height/2`. Otherwise, it is the top-most value of the bounding box. Changing this value will shift the center of the object so that the top edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y+self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return max(p0,p1,p2,p3) @top.setter def top(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.top self.y += diff @property def bottom(self): """The vertical coordinate of the bottom edge. The value depends on the current angle of rotation. If rotation is 0, it is `y-height/2`. Otherwise, it is the bottom-most value of the bounding box. Changing this value will shift the center of the object so that the bottom edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y-self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return min(p0,p1,p2,p3) @bottom.setter def bottom(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.bottom self.y += diff # IMMUTABLE PROPERTIES @property def matrix(self): """The transformation matrix for this object This value is constructed dynamically as needed. It should only be used internally to this file. **Invariant**: Either a GMatrix or None""" if not self._mtrue or self._matrix is None: self._matrix = GMatrix() self._matrix.translate(self._trans.x,self._trans.y) self._matrix.rotate(self._rotate.angle,z=1) self._matrix.scale(self._scale.x,self._scale.y) self._invrse = GMatrix() self._invrse.scale(1.0/self._scale.x,1.0/self._scale.y) self._invrse.rotate(-self._rotate.angle,z=1) self._invrse.translate(-self._trans.x,-self._trans.y) self._mtrue = True return self._matrix @property def inverse(self): """The transformation matrix for this object This value is constructed dynamically as needed. It should only be used internally to this file. **Invariant**: Either a GMatrix or None""" if not self._mtrue or self._matrix is None: self._matrix = GMatrix() self._matrix.translate(self._trans.x,self._trans.y) self._matrix.rotate(self._rotate.angle,z=1) self._matrix.scale(self._scale.x,self._scale.y) self._invrse = GMatrix() self._invrse.scale(1.0/self._scale.x,1.0/self._scale.y) self._invrse.rotate(-self._rotate.angle,z=1) self._invrse.translate(-self._trans.x,-self._trans.y) self._mtrue = True return self._invrse # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new GObject to be drawn. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to initialize the x position and the fill color, use the constructor call GObject(x=2,fillcolor=colormodel.RED) You do not need to provide the keywords as a dictionary. The ** in the parameter `keywords` does that automatically. Any attribute of this class may be used as a keyword. The argument must satisfy the invariants of that attribute. See the list of attributes of this class for more information.""" # Set the properties. self._defined = False # Create the Kivy transforms for position and size self._trans = Translate(0,0,0) self._rotate = Rotate(angle=0,axis=(0,0,1)) self._scale = Scale(1,1,1) # Now update these with the keywords; size first if 'width' in keywords: self.width = keywords['width'] else: self._width = 1 if 'height' in keywords: self.height = keywords['height'] else: self._height = 1 # Then angle if 'angle' in keywords: self.angle = keywords['angle'] # Finally, (relative) position if 'x' in keywords: self.x = keywords['x'] elif 'left' in keywords: self.left = keywords['left'] elif 'right' in keywords: self.right = keywords['right'] if 'y' in keywords: self.y = keywords['y'] elif 'bottom' in keywords: self.bottom = keywords['bottom'] elif 'top' in keywords: self.top = keywords['top'] # Top it off with color self.fillcolor = keywords['fillcolor'] if 'fillcolor' in keywords else (1,1,1,1) self.linecolor = keywords['linecolor'] if 'linecolor' in keywords else (0,0,0,1) # Add a name for debugging self.name = keywords['name'] if 'name' in keywords else None def __str__(self): """**Returns**: A string representation of this object.""" if self.name is None: s = '[' else: s = '[name=%s,' % self.name return '%s,center=(%s,%s),width=%s,height=%s,angle=%s]' \ % (s,`self.x`,`self.y`,`self.height`,`self.width`,`self.angle`) def __repr__(self): """**Returns**: An unambiguous representation of this object.""" return str(self.__class__)+str(self) # PUBLIC METHODS def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float By default, this method just checks the bounding box of the shape. **Warning**: Accessing this value on a rotated object may slow down your framerate significantly. """ if self._rotate.angle == 0.0: return abs(x-self.x) < self.width/2.0 and abs(y-self.y) < self.height/2.0 p = self.matrix.inverse()._transform(x,y) return abs(p[0]) < self.width/2.0 and abs(p[1]) < self.height/2.0 def transform(self,point): """**Returns**: The given point transformed to local coordinate system :param point: the point to transform **Precondition**: a GPoint or a pair of numbers (int or float) This method is important for mouse selection. It helps you understand where in the shape the selection takes place. In the case of objects with children, lik e`GScene`, this method is necessary to properly use the contains method on the children. The value returned is a GPoint.""" if isinstance(point,GPoint): return self.inverse.transform(point) else: assert len(point) == 2 and _is_num_tuple(point,2) p = self.inverse._transform(point[0],point[2]) return GPoint(p[0],p[1]) def draw(self, view): """Draw this shape in the provide view. :param view: view to draw to **Precondition**: an *instance of* `GView` Ideally, the view should be the one provided by `GameApp`.""" view.draw(self._cache) # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" self._cache = InstructionGroup() self._cache.add(PushMatrix()) self._cache.add(self._trans) self._cache.add(self._rotate) self._cache.add(self._scale) class GRectangle(GObject): """Instances represent a solid rectangle. As with `GObject`, the attributes x and y refer to the center of the rectangle. This is so that when you rotate the rectangle, it spins about the center. The interior (fill) color of this rectangle is `fillcolor`, while `linecolor` is the color of the border. The only new property for this class is `linewidth`, which controls the width of the border around the rectangle. For all other properties, see the documentation for `GObject`.""" # MUTABLE PROPERTIES @property def linewidth(self): """The width of the exterior line of this shape. Setting this to 0 means that the rectangle has no border. **Invariant**: Must be an int or float >= 0.""" return self._linewidth @linewidth.setter def linewidth(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value >= 0, 'value %s is negative' % `value` self._linewidth = value if self._defined: self._reset() # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new solid rectangle :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a red square centered at (0,0), use the constructor call GRectangle(x=0,y=0,width=10,height=10,fillcolor=colormodel.RED) This class supports the all same keywords as `GObject` plus the additional keyword `linewidth`.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 # Always delay the call to parent class, to avoid reset GObject.__init__(self,**keywords) self._reset() self._defined = True # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Rectangle(pos=(x,y), size=(self.width, self.height)) self._cache.add(self._fillcolor) self._cache.add(fill) if self.linewidth > 0: line = Line(rectangle=(x,y,self.width,self.height),joint='miter', close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GEllipse(GRectangle): """Instances represent a solid ellipse. The ellipse is the largest one that can be drawn inside of a rectangle whose bottom center is at (x,y), with the given width and height. The interior (fill) color of this ellipse is `fillcolor`, while `linecolor` is the color of the border. This class has exactly the same properties as `GRectangle`. See the documentation of that class and `GObject` for a complete list of properties.""" # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new solid ellipse :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a red circle centered at (0,0), use the constructor call GEllipse(x=0,y=0,width=10,height=10,fillcolor=colormodel.RED) This class supports the all same keywords as `GRectangle`.""" GRectangle.__init__(self,**keywords) # PUBLIC METHODS def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method is better than simple rectangle inclusion. It checks that the point is within the proper radius as well. **Warning**: Accessing this value on a rotated object may slow down your framerate significantly. """ rx = self.width/2.0 ry = self.height/2.0 if self._rotate.angle == 0.0: dx = (x-self.x)*(x-self.x)/(rx*rx) dy = (y-self.y)*(y-self.y)/(ry*ry) else: p = self.matrix.inverse()._transform(x,y) dx = p[0]*p[0]/(rx*rx) dy = p[1]*p[1]/(ry*ry) return (dx+dy) <= 1.0 # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Ellipse(pos=(x,y), size=(self.width,self.height)) self._cache.add(self._fillcolor) self._cache.add(fill) if self._linewidth > 0: line = Line(ellipse=(x,y,self.width,self.height),close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GImage(GRectangle): """Instances represents a rectangular image. The image is given by a JPEG, PNG, or GIF file whose name is stored in the attribute `source`. Image files should be stored in the **Images** directory so that Kivy can find them without the complete path name. This class acts much like is parent `GRectangle` and shares all of the same properties. As with that class, you can add a border to the rectangle if you want, using the attribute `linewidth`. If the attributes `width` and `height` do not agree with the actual size of the image, the image is scaled to fit.Furthermore, if you define `fillcolor`, Kivy will tint your image by the given color.` If the image supports transparency, then this object can be used to represent irregular shapes. However, the `contains` method still treats this shape as a rectangle. """ # MUTABLE PROPERTIES @property def source(self): """The source file for this image. **Invariant**. Must be a string refering to a valid file.""" return self._source @source.setter def source(self,value): assert value is None or _is_image_file(value), 'value %s is not an image file' % `value` self._source = value if self._defined: self._reset() # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new rectangle image :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to load the image `beach-ball.png`, use the constructor GImage(x=0,y=0,width=10,height=10,source='beach-ball.png') This class supports the all same keywords as `GRectangle`; the only new keyword is `source`. See the documentation of `GRectangle` and `GObject` for the other supported keywords.""" self._defined = False self.source = keywords['source'] if 'source' in keywords else None GRectangle.__init__(self,**keywords) self._defined = True # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Rectangle(pos=(x,y), size=(self.width, self.height),source=self.source) self._cache.add(self._fillcolor) self._cache.add(fill) if self.linewidth > 0: line = Line(rectangle=(x,y,self.width,self.height),joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GLabel(GRectangle): """Instances represent an (uneditable) text label This object is exactly like a GRectangle, except that it has the possibility of containing some text. The attribute `text` defines the text content of this label. Uses of the escape character '\\n' will result in a label that spans multiple lines. As with any `GRectangle`, the background color of this rectangle is `fillcolor`, while `linecolor` is the color of the text. The text itself is aligned within this rectangle according to the attributes `halign` and `valign`. See the documentation of these attributes for how alignment works. There are also attributes to change the point size, font style, and font name of the text. The `width` and `height` of this label will grow to ensure that the text will fit in the rectangle, no matter the font or point size. To change the font, you need a .ttf (TrueType Font) file in the Fonts folder; refer to the font by filename, including the .ttf. If you give no name, it will use the default Kivy font. The `bold` attribute only works for the default Kivy font; for other fonts you will need the .ttf file for the bold version of that font. See the provided `ComicSans.ttf` and `ComicSansBold.ttf` for an example.""" # MUTABLE PROPERTIES @property def font_size(self): """Size of the text font in points. **Invariant**: Must be a positive number (int or float)""" return self._fsize @font_size.setter def font_size(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._fsize = value self._label.font_size = value self._label.texture_update() @property def font_name(self): """File name for the .ttf file to use as a font **Invariant**: Must be a string referring to a .ttf file in folder Fonts""" return self._label.font_name @font_name.setter def font_name(self,value): assert _is_font_file(value), 'value %s is not a font name' % `value` self._label.font_name = value self._label.texture_update() @property def bold(self): """Boolean indicating whether or not the text should be bold. This value only works on the default Kivy font. It does not work on custom .ttf files. In that case, you need the bold version of the .ttf file. See `ComicSans.ttf` and `ComicSansBold.ttf` for an example. **Invariant**: Must be a boolean""" return self._label.bold @bold.setter def bold(self,value): assert type(value) == bool, `value`+' is not a bool' self._label.bold = value self._label.texture_update() @property def text(self): """Text for this label. The text in the label is displayed as a single line, or broken up into multiple lines in the presence of the escape character '\\n'. The `width` and `height` of this label will grow to ensure that the text will fit in the rectangle. **Invariant**: Must be a string""" return self._label.text @text.setter def text(self,value): assert type(value) == str, 'value %s is not a string' % `value` self._label.text = value self._label.texture_update() @property def halign(self): """Horizontal alignment for this label. The text is horizontally anchored inside of the label rectangle at either the left, the right or the center. This means that as the size of the label increases, the text will still stay rooted at that anchor. By default, the text is centered. **Invariant**: Must be one of 'left', 'right', or 'center'""" return self._halign @halign.setter def halign(self,value): assert value in ('left','right','center'), 'value %s is not a valid horizontal alignment' % `value` self._halign = value self._label.halign = value if self._defined: self._reset() @property def valign(self): """Vertical alignment for this label. The text is vertically anchored inside of the label rectangle at either the top, the bottom or the middle. This means that as the size of the label increases, the text will still stay rooted at that anchor. By default, the text is in the middle. **Invariant**: Must be one of 'top', 'bottom', or 'middle'""" return self._valign @valign.setter def valign(self,value): assert value in ('top','middle','bottom'), 'value %s is not a valid vertical alignment' % `value` self._valign = value self._label.valign = value if self._defined: self._reset() # REDEFINED PROPERTIES @property def x(self): """The horizontal coordinate of the object center. **Invariant**: Must be an int or float.""" return self._trans.x @x.setter def x(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._trans.x = float(value) self._mtrue = False self._hanchor = 'center' self._ha = value @property def y(self): """The vertical coordinate of the object center.. **Invariant**: Must be an int or float.""" return self._trans.y @y.setter def y(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._trans.y = float(value) self._mtrue = False self._vanchor = 'center' self._hv = value @property def left(self): """The left edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x-width/2`. Otherwise, it is the left-most value of the bounding box. Changing this value will shift the center of the object so that the left edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x-self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return min(p0,p1,p2,p3) @left.setter def left(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.left self.x += diff self._hanchor = 'left' self._ha = value @property def right(self): """The right edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x+width/2`. Otherwise, it is the right-most value of the bounding box. Changing this value will shift the center of the object so that the right edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x+self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return max(p0,p1,p2,p3) @right.setter def right(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.right self.x += diff self._hanchor = 'right' self._ha = value @property def top(self): """The vertical coordinate of the top edge. The value depends on the current angle of rotation. If rotation is 0, it is `y+height/2`. Otherwise, it is the top-most value of the bounding box. Changing this value will shift the center of the object so that the top edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y+self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return max(p0,p1,p2,p3) @top.setter def top(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.top self.y += diff self._vanchor = 'top' self._hv = value @property def bottom(self): """The vertical coordinate of the bottom edge. The value depends on the current angle of rotation. If rotation is 0, it is `y-height/2`. Otherwise, it is the bottom-most value of the bounding box. Changing this value will shift the center of the object so that the bottom edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y-self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return min(p0,p1,p2,p3) @bottom.setter def bottom(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.bottom self.y += diff self._vanchor = 'bottom' self._hv = value # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new text label. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a label containing the word 'Hello', use the constructor call GLabel(text='Hello') This class supports the same keywords as `GRectangle`, as well as additional attributes for the text properties (e.g. font size and name).""" self._defined = False self._hanchor = 'center' self._vanchor = 'center' self._label = Label(**keywords) self._label.size_hint = (None,None) self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 self.halign = keywords['halign'] if 'halign' in keywords else 'center' self.valign = keywords['valign'] if 'valign' in keywords else 'middle' GObject.__init__(self,**keywords) self._reset() self._defined = True self._label.bind(texture_size=self._callback) def __str__(self): """**Returns**: A string representation of this object.""" if self.name is None: s = '[' else: s = '[name=%s,' % self.name return '%s,text=%s,center=(%s,%s),angle=%s]' \ % (s,`self.text`,`self.x`,`self.y`,`self.angle`) # HIDDEN METHODS def _callback(self,instance=None,value=None): """Workaround to deal with parameter requirements for callbacks""" if self._defined: self._reset() def _reset(self): """Resets the drawing cache""" # Set up the label at the center. self._label.size = self._label.texture_size self._label.center = (0,0) self._label.color = self.linecolor # Resize the outside if necessary self._defined = False self.width = max(self.width, self._label.width) self.height = max(self.height,self._label.height) self._defined = True # Reset the absolute anchor if self._hanchor == 'left': self._trans.x = self._ha+self.width/2.0 elif self._hanchor == 'right': self._trans.x = self._ha-self.width/2.0 # Reset the absolute anchor if self._vanchor == 'top': self._trans.y = self._hv-self.height/2.0 elif self._vanchor == 'bottom': self._trans.y = self._hv+self.height/2.0 # Reset the label anchor. if self.halign == 'left': self._label.x = -self.width/2.0 elif self.halign == 'right': self._label.right = self.width/2.0 # Reset the label anchor. if self.valign == 'top': self._label.top = self.height/2.0 elif self.valign == 'bottom': self._label.bottom = -self.height/2.0 GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Rectangle(pos=(x,y), size=(self.width,self.height)) self._cache.add(self._fillcolor) self._cache.add(fill) self._cache.add(self._label.canvas) if self._linewidth > 0: line = Line(rectangle=(x,y,self.width,self.height),joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) ################# PATH PRIMITIVES ################# pass # #mark PATH PRIMITIVES class GPath(GObject): """Instances represent a sequence of line segments The path is defined by the `points` attribute which is an (even) sequence of alternating x and y values. When drawn in a `GView` object, the line starts from one x-y pair in `points` and goes to the next x-y pair. If `points` has length 2n, then the result is n-1 line segments. The object uses the attribute `linecolor` to determine the color of the line and the attribute `linewidth` to determine the width. The attribute `fillcolor` is unused (even though it is inherited from `GObject`). The attributes `width` and `height` are present in this object, but they are now read-only. These values are computed from the list of points. On the other hand, the attributes `x` and `y` are used. By default, these values are 0. However, if they are nonzero, then Python will add them to all of the points in the path, shifting the path accordingly. """ # MUTABLE PROPERTIES @property def points(self): """The sequence of points that make up this line. **Invariant**: Must be a sequence (list or tuple) of int or float. The length of this sequence must be even with length at least 4.""" return self._points @points.setter def points(self,value): assert _is_point_tuple(value,2),'value %s is not a valid list of points' % `value` self._points = tuple(value) if self._defined: self._reset() @property def linewidth(self): """The width of this path. Setting this value to 0 means that the path is invisible. **Invariant**: Must be an int or float >= 0.""" return self._linewidth @linewidth.setter def linewidth(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value >= 0, 'value %s is negative' % `value` self._linewidth = value if self._defined: self._reset() # IMMUTABLE PROPERTIES @property def width(self): """The horizontal width of this path. The value is the width of the smallest bounding box that contains all of the points in the line AND the origin (0,0). **Invariant**: Must be an int or float > 0.""" px = self.points[::2]+(0,0) return 2*max(max(px),-min(px)) @property def height(self): """The vertical height of this path. The value is the height of the smallest bounding box that contains all of the points in the line AND the origin (0,0). **Invariant**: Must be an int or float > 0.""" py = self.points[1::2]+(0,0) return 2*max(max(py),-min(py)) # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new sequence of line segments. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a line from (0,0) to (2,3) with width 2, use the constructor call GLine(points=[0,0,2,3],linewidth=2) This class supports the same keywords as `GObject`, though some of them are unused, as the `width` and `height` attributes are now immutable. The primary keywords for this class are `points`, `linecolor`, and `linewidth`.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 1.0 self.points = keywords['points'] if 'points' in keywords else (0,0,10,10) GObject.__init__(self,**keywords) self._reset() self._defined = True # PUBLIC METHODS def contains(self,x,y): """**Returns**: True if this path contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method always returns `False` as a `GPath` has no interior.""" return False def near(self,x,y): """**Returns**: True if this path is near the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float To determine if (x,y) is near the path, we compute the minimum distances from (x,y) to the path. If this distance is less than e-6, we return True.""" size = len(self.points)/2 epsilon = 1e-6 for ii in range(size-1): p = self.points[2*ii :2*ii+2] q = self.points[2*ii+2:2*ii+4] if p == q: test = np.sqrt((q[0]-x)*(q[0]-x)+(q[1]-y)*(q[1]-y)) < epsilon else: num = abs((q[0]-p[0])*x-(q[1]-p[1])*y+q[0]*p[1]-p[0]*q[1]) den = np.sqrt((q[0]-p[0])*(q[0]-p[0])+(q[1]-p[1])*(q[1]-p[1])) test = num/den if test: return True return self.contains(x,y) # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" GObject._reset(self) self._cache.add(self._linecolor) line = Line(points=self.points,cap='round',joint='round',width=self.linewidth) self._cache.add(line) self._cache.add(PopMatrix()) class GTriangle(GPath): """Instances represent a solid triangle. The triangle is defined as a sequence of three point. Just as with the `GPath` class (which is the parent of this class), it has an attribute `point` which represents this points as an even-length sequence of ints or floats. The interior (fill) color of this triangle is `fillcolor`, while `linecolor` is the color of the border. If `linewidth` is set to 0, then the border is not visible. As with `GPath`, the attributes `x` and `y` may be used to shift the triangle position. By default, these values are 0. However, if they are nonzero, then Python will add them to the triangle vertices. Similarly, the attributes `width` and `height` are immutable, and are computed directly from the points""" # MUTABLE PROPERTIES @property def points(self): """The sequence of vertices that make up this trianle. **Invariant**: Must be a sequence (list or tuple) of int or float. The length of this sequence must be exactly 6.""" return self._points @points.setter def points(self,value): assert _is_num_tuple(value,6),'value %s is not a valid list of points' % `value` self._points = tuple(value) if self._defined: self._reset() # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new solid triangle. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a red triangle with vertices (0,0), (2,3), and (0,4), use the constructor call GTriangle(points=[0,0,2,3,0,4],fillcolor=colormodel.RED) As with `GPath` the `width` and `height` attributes of this class are both immutable. They are computed from the list of points.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 self.points = keywords['points'] if 'points' in keywords else (-100,-58,0,116,100,-58) GObject.__init__(self,**keywords) self._reset() self._defined = True # PUBLIC METHODS def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method uses a standard test for triangle inclusion.""" return _in_triangle((x,y),self._points) # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" GObject._reset(self) vertices = () for x in range(3): # Need to tack on degenerate texture coords vertices += self.points[2*x:2*x+2]+(0,0) mesh = Mesh(vertices=vertices, indices=range(3), mode='triangle_strip') self._cache.add(self._fillcolor) self._cache.add(mesh) if self.linewidth > 0: line = Line(points=self.points,joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GPolygon(GPath): """Instances represent a solid polygon. The polygon is a triangle fan from the center of the polyon to the vertices in the attribute `points`. The center of the polygon is always the point (0,0), unless you reassign the attributes `x` and `y`. However, as with `GPath`, if you assign the attributes `x` and `y`, then Python will shift all of the vertices by that same amount. Hence the polygon vertices must be defined as triangle fan centered at the origin. The interior (fill) color of this triangle is `fillcolor`, while `linecolor` is the color of the border. If `linewidth` is set to 0, then the border is not visible. The polygon may also be textured by specifying a source image. The texture coordinates of each vertex will be relative to the size of the image. For example, if the image is 64x64, then the quad polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle equal to the image. You can adjust the size of the source image with the attributes `source_width` and `source_height`. If the polygon is larger than the image, then the texture will repeat. As with `GPath`, the attributes `width` and `height` are immutable, and are computed directly from the points""" # MUTABLE PROPERTIES @property def points(self): """The sequence of points that make up this polygon. **Invariant**: Must be a sequence (list or tuple) of int or float. The length of this sequence must be even with length at least 6.""" return self._points @points.setter def points(self,value): assert _is_point_tuple(value,4),'value %s is not a valid list of points' % `value` self._points = tuple(value) if self._defined: self._reset() @property def source(self): """The source image for texturing this polygon **Invariant**. Must be a string refering to a valid file.""" return self._source @source.setter def source(self,value): assert value is None or _is_image_file(value), 'value %s is not an image file' % `value` self._source = value if self._defined: self._reset() @property def source_width(self): """The width to scale the source image. The texture coordinates of each vertex will be relative to the size of the image. For example, if the image is 64x64, then the polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle equal to the image. This attribute allows you to resize the image for these texture coordinates. So if the image is 512x64, setting this value to 64 will be as if the image was originally 64x64. If this value is None, the Python will use the normal width of the image file **Invariant**. Must be a number (int or float) > 0 or None.""" return self._source_width @source_width.setter def source_width(self,value): assert value is None or _is_num(value), 'value %s is not a valid width' % `value` self._source_width = None if self._defined: self._reset() @property def source_height(self): """The height to scale the source image. The texture coordinates of each vertex will be relative to the size of the image. For example, if the image is 64x64, then the polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle equal to the image. This attribute allows you to resize the image for these texture coordinates. So if the image is 64x512, setting this value to 64 will be as if the image was originally 64x64. If this value is None, the Python will use the normal width of the image file **Invariant**. Must be a number (int or float) > 0 or None.""" return self._source_width @source_height.setter def source_height(self,value): assert value is None or _is_num(value), 'value %s is not a valid width' % `value` self._source_height = None if self._defined: self._reset() # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new solid polyon :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a hexagon, use the constructor call GPolygon(points=[87,50,0,100,-87,50,-87,-50,0,-100,87,-50]) As with `GPath` the `width` and `height` attributes of this class are both immutable. They are computed from the list of points.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 self.points = keywords['points'] if 'points' in keywords else (-100,-58,0,116,100,-58) self.source = keywords['source'] if 'source' in keywords else None self.source_width = keywords['source_width'] if 'source_width' in keywords else None self.source_height = keywords['source_height'] if 'source_height' in keywords else None GObject.__init__(self,**keywords) self._reset() self._defined = True # PUBLIC METHODS def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method cycles through each triangle in the triangle fan and tests each triangle for inclusion.""" found = False for i in xrange(4,len(self._points),2): t = (0,0)+self.points[i-4:i] found = found or _in_triangle((x,y),t) return found # HIDDEN METHODS def _make_mesh(self): """Creates the mesh for this polygon""" size = len(self.points)/2 try: texture = Image(source=self.source).texture texture.wrap = 'repeat' tw = float(texture.width) if self.source_width is None else self.source_width th = float(texture.height) if self.source_height is None else self.source_height # Centroid at 0, with texture centered verts = (0,0,0.5,0.5) # Create the fan. for x in range(size): pt = self.points[2*x:2*x+2] self._verts += pt+(pt[0]/tw+0.5,pt[1]/th+0.5) # Come back to the beginning pt = self.points[0:2] verts += pt+(pt[0]/tw+0.5,pt[1]/th+0.5) self._mesh = Mesh(vertices=verts, indices=range(size+2), mode='triangle_fan', texture=texture) except BaseException as e: # Make all texture coordinates degnerate verts = (0,0,0,0) for x in range(size): verts += self.points[2*x:2*x+2]+(0,0) verts += self.points[0:2]+(0,0) self._mesh = Mesh(vertices=verts, indices=range(size+2), mode='triangle_fan') def _reset(self): """Resets the drawing cache""" GObject._reset(self) self._make_mesh() self._cache.add(self._fillcolor) self._cache.add(self._mesh) if self.linewidth > 0: line = Line(points=self.points,joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) ################# SCENE GRAPH ################# pass # #mark SCENE GRAPH class GScene(GObject): """Instances are a node in a scene graph. A scene graph node is just a collection of GObjects. By placing them in the scene graph node, you can rotate and translate them all at once. Scene graphs are a sophisticated concept that allow you to do advanced animation. As `GScene` is a subclass of `GObject` you can nest scene graph nodes inside of other scene graph nodes. The result is a tree structure. The attributes `width` and `height` are present in this object, but they are now read-only. These values are computed from the list of GObjects stored in the scene. All GObjects stored in a GScene are drawn as if the point (x,y) is the origin. """ # MUTABLE PROPERTIES @property def children(self): """The list of GObjects stores in this scene. The objects are drawn as if (x,y) is the origin. Therefore, changing the attributes `x` and `y` will shift all of the children on the screen. **Invariant**: Must be a list or tuple of GObjects (possibly empty)""" return tuple(self._children) @children.setter def children(self,value): assert _is_gobject_list(value), 'value %s is not a list of GObjects' % `value` self._children = list(value) if self._defined: self._reset() # IMMUTABLE PROPERTIES @property def width(self): """The horizontal width of this path. The value is the width of the smallest bounding box that contains all of the objects in this scene (and the center) **Invariant**: Must be an int or float > 0.""" max = 0 for x in self.children: w = x.x+x.width/2.0 if w > max: max = w return max*2 @property def height(self): """The vertical height of this path. The value is the height of the smallest bounding box that contains all of the objects in this scene (and the center) **Invariant**: Must be an int or float > 0.""" max = 0 for x in self.children: h = x.y+x.height/2.0 if h > max: max = h return max*2 # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates a new scene graph node :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a scene with shapes rect, tri, and circ, call the constructor GScene(children=[rect,tri,circ]) This class supports the same keywords as `GObject`, though some of them are unused, as the `width` and `height` attributes are now immutable.""" self._defined = False self.children = keywords['children'] if 'children' in keywords else [] GObject.__init__(self,**keywords) self._reset() self._defined = True # HIDDEN METHODS def _reset(self): """Resets the drawing cache""" GObject._reset(self) for x in self.children: self._cache.add(x._cache) self._cache.add(PopMatrix()) ################# SOUND CLASSES ################# pass # #mark SOUND CLASSES class Sound(object): """Instances are a sound object that can be played. A sound is a WAV file that can be played on command via the method `play`. While some platforms may support MP3s, we can only guarantee that WAVs work on all platforms. In order for Kivy to find a WAV or OGG file, you should put it in the **Sounds** directory. Sounds in that folder can be referenced directly by name. When a sound is played, it cannot be played again until it finishes, or is stopped. This means that if you want multiple, simultaneous sound effects from the same WAV file.you will need to create multiple Sound objects. """ # This class is a simply replacement for the built-in Kivy Sound class. It is a # little better with error handling, since GStreamer appears to be quite unreliable. # MUTABLE PROPERTIES @property def volume(self): """The current sound volume. 1 means full volume, 0 means mute. The default value is 1. **Invariant**: Must float in the range 0..1.""" return self._sound.volume @volume.setter def volume(self,value): assert type(value) in [int, float] and value >= 0 and value <= 1, \ 'value %s is not a valid volume' % `value` self._sound.volume = value # IMMUTABLE PROPERTIES @property def source(self): """The source file for this sound. **Immutable**: This value cannot be changed after the sound is loaded. **Invariant**: Must be a nonempty string.""" return self._source def __init__(self,source): """**Constructor**: Loads a new sound from a file. :param source: The string providing the name of a sound file **Precondition**: source is the name of a valid sound file """ assert _is_sound_file(source), 'source %s is not a sound file' % `filename` self._source = source self._sound = SoundLoader.load(source) if self._sound is None: raise IOError('Module game2d cannot read the file %s' % `source`) def play(self): """Plays this sound. The sound will play until completion, or interrupted by another sound""" self._sound.play() class SoundLibrary(object): """Instances are a dictionary that maps sounds to Sound objects. This class implements to the dictionary interface to make it easier to load sounds and manage them. To load a sound, simply assign it to the library object, as follows: soundlib['soundname'] = 'soundfile.wav' The sound library will load the sound and map it to 'soundname' as the key. To play the sound, we access it as follows: soundlib['soundname'].play() """ def __init__(self): """**Constructor**: Creates a new, empty sound library.""" if not _INITIALIZED: init() self._data = {} def __len__(self): """**Returns**: The number of sounds in this library.""" return len(self._data) def __getitem__(self, key): """**Returns**: The Sound object for the given sound name. :param key: The key identifying a sound object **Precondition**:: key is a string. """ return self._data[key] def __setitem__(self, key, filename): """Creates a sound object from the file filename and assigns it the given name. :param key: The key identifying a sound object **Precondition**:: key is a string. :param filename: The name of the file containing the sound source **Precondition**:: filename is the name of a valid sound file. """ assert is_sound_file(filename), `filename`+' is not a sound file' self._data[key] = Sound(filename) def __delitem__(self, key): """Deletes the Sound object for the given sound name. :param key: The key identifying a sound object **Precondition**:: key is a string. """ del self._data[key] def __iter__(self): """**Returns**: The iterator for this sound dictionary.""" return self._data.iterkeys() def iterkeys(self): """**Returns**: The key iterator for this sound dictionary.""" return self._data.iterkeys() ################# VIEW CLASSES ################# pass # #mark VIEW CLASSES class GInput(object): """Instances represent an input handler An input handler receives mouse and keyboard information, and makes it available to the user. To access mouse information, simply access the attribute `touch`. To access keyboard information, use the method `is_key_down`. **You should never construct an object of this class**. Creating a new instance of this class will not properly hook it up to the keyboard and mouse. Instead, you should only use the one provided in the `input` attribute of `GameApp`. See the class `GameApp` for more information. """ # MUTABLE ATTRIBUTES @property def touch_enabled(self): """Whether the touch (mouse) interface is currently enabled. Setting this value to False will disable all mouse clicks or drags. The value is True by default. **Invariant**: Must be a bool""" return self._touch_enabled @touch_enabled.setter def touch_enabled(self,value): assert type(value) == bool, 'value %s is not a bool' % `value` if value and not self._touch_enabled: self._enable_touch() elif not value and self._touch_enabled: self._disable_touch() self._touch_enabled = value @property def keyboard_enabled(self): """Whether the keyboard interface is currently enabled. Setting this value to False will disable all key presses. The value is True by default. **Invariant**: Must be a bool""" return self._keyboard_enabled @keyboard_enabled.setter def keyboard_enabled(self,value): assert type(value) == bool, 'value %s is not a bool' % `value` if value and not self._keyboard_enabled: self._enable_keyboard() elif not value and self._keyboard_enabled: self._disable_keyboard() self._keyboard_enabled = value # IMMUTABLE ATTRIBUTES @property def touch(self): """The current (x,y) coordinate of the mouse, if pressed. This method only returns coordinates if the mouse button is pressed. If the mouse button is not pressed it returns None. The origin (0,0) corresponds to the bottom left corner of the application window. There is currently no way to get the location of the mouse when the button is not pressed. This a limitation of Kivy. **Immutable**: This value cannot be altered. **Invariant**: Must be either a GPoint or None (if there is no touch).""" if self._touch is None: return None return GPoint(self._touch.x/dp(1),self._touch.y/dp(1)) @property def key_count(self): """The number of keys currently held down. This attribute is a quick way to check whether the user has pressed any keys. **Immutable**: This value cannot be altered. **Invariant**: Must be an int > 0.""" return self._keycount @property def keys(self): """The list of keys that are currently held down. Using this attribute is much slower than the method `is_key_down`. You should use that method when you want to test a specific key. This attribute is primarily for debugging. **Immutable**: This value cannot be altered. **Invariant**: Must be a list of strings (possibly empty)""" return tuple(k for (k,v) in self._keystate.iteritems() if v) # BUILT-IN METHODS def __init__(self): """**Constructor**: Creates a new input handler This constructor does very little. It does not hook up the handler to the mouse or keyboard. That functionality happens behind the scenes with hidden methods. You should only use use the object provided in the `input` attribute of `GameApp`. See the class `GameApp` for more information.""" self._view = None self._touch = None self._keyboard = None self._touch_enabled = True self._keyboard_enabled = True self._keystate = {} self._keycount = 0 # PUBLIC METHODS def is_key_down(self,key): """**Returns**: True if the key is currently held down. :param key: the key to test **Precondition**: Must be a string. The key is a string describing the key pressed. For example, to determine whether the right-arrow key is pressed, use the method call `input.is_key_down('right')`. Similarly the method call `input.is_key_down('w')` will indicate whether the W key is pressed. For a complete list of key names, see the `Kivy documentation <http://kivy.org/docs/_modules/kivy/core/window.html>`_. """ return key in self._keystate and self._keystate[key] def is_touch_down(self): """**Returns**: True if the mouse is currently held down. If this method returns True, the attribute `touch` is guaranteed to not be None.""" return not self._touch is None # HIDDEN METHODS def _register(self,view): """Registers the view with this input handler; activating it. :param view: the view to register. **Precondition**: Must be a GView. The input handler can only have one view at a time. If there is an active view, it will unregister it first before registering the new one. """ self._view = view if self.touch_enabled: self._enable_touch() if self.keyboard_enabled: self._enable_keyboard() def _enable_touch(self): """Enables touch events for this input handler""" if self._view is None: return self._view.bind(on_touch_down=self._capture_touch) self._view.bind(on_touch_move=self._capture_touch) self._view.bind(on_touch_up=self._release_touch) def _disable_touch(self): """Disables touch events for this input handler""" if self._view is None: return self._view.unbind(on_touch_down=self._capture_touch) self._view.unbind(on_touch_move=self._capture_touch) self._view.unbind(on_touch_up=self._release_touch) self._touch = None def _enable_keyboard(self): """Enables keyboard events for this input handler""" if self._view is None: return from kivy.core.window import Window self._keyboard = Window.request_keyboard(self._disable_keyboard, self._view, 'text') self._keyboard.bind(on_key_down=self._capture_key) self._keyboard.bind(on_key_up=self._release_key) def _disable_keyboard(self): """Disables keyboard events for this input handler""" if self._view is None: return self._keyboard.unbind(on_key_down=self._capture_key) self._keyboard.unbind(on_key_up=self._release_key) self._keyboard = None self._keystate = {} self._keycount = 0 def _capture_key(self, keyboard, keycode, text, modifiers): """Captures a simple keypress and adds it to the key dictionary. :param keyboard: reference to the keyboard **Precondition**: Must be a Keyboard. :param keycode: the key pressed **Precondition**: Must be a pair of an int (keycode) and a string :param text: the text associated with the key **Precondition**: Must be a string :param modifiers: the modifiers associated with the press **Precondition**: Must be a list of key codes """ k = keycode[1] # Need to handle the case where a release was dropped if not k in self._keystate or not self._keystate[k]: self._keycount += 1 self._keystate[k] = True return True def _release_key(self, keyboard, keycode): """Releases a simple keypress and removes it from the key dictionary. :param keyboard: reference to the keyboard **Precondition**: Must be a Keyboard. :param keycode: the key pressed **Precondition**: Must be a pair of an int (keycode) and a string """ self._keystate[keycode[1]] = False self._keycount -= 1 return True def _capture_touch(self,view,touch): """Captures a the current mouse position if button is pressed. :param view: reference to the view window **Precondition**: Must be a GView. :param touch: the information about the mouse press **Precondition**: Must be a TouchEvent """ self._touch = touch #self._touch.grab(self) def _release_touch(self,view,touch): """Releases a the current mouse position from memory. :param view: reference to the view window **Precondition**: Must be a GView. :param touch: the information about the mouse release **Precondition**: Must be a TouchEvent """ self._touch = None class GView(FloatLayout): """Instances are a view class for a `GameApp` application. This is the class that you will use to draw shapes to the screen. Simply pass your `GObject` instances to the `draw` method. You must do this every animation frame, as the game is constantly clearing the window. **You should never construct an object of this class**. Creating a new instance of this class will not properly display it on the screen. Instead, you should only use the one provided in the `input` attribute of `GameApp`. See the class `GameApp` for more information. """ # BUILT-IN METHODS def __init__(self): """**Constructor**: Creates a new view for display This constructor does very little. It does not hook up the view to the game window. That functionality happens behind the scenes with hidden methods. You should only use use the object provided in the `view` attribute of `GameApp`. See the class `GameApp` for more information.""" FloatLayout.__init__(self) self._frame = InstructionGroup() self.bind(pos=self._reset) self.bind(size=self._reset) self._reset() # PUBLIC METHODS def draw(self,cmd): """Draws the given Kivy graphics command to this view. :param cmd: the command to draw **Precondition**: Must be a Kivy graphics command You should never call this method, since you do not understand raw Kivy graphics commands. Instead, you should use the `draw` method in `GObject` instead.""" self._frame.add(cmd) def clear(self): """Clears the contents of the view. This method is called for you automatically at the start of the animation frame. That way, you are not drawing images on top of one another.""" self._frame.clear() # HIDDEN METHODS def _reset(self,obj=None,value=None): """Resets the view canvas in response to a resizing event""" self.canvas.clear() self.canvas.add(Color(1,1,1)) self.canvas.add(Rectangle(pos=self.pos,size=self.size)) # Work-around for Retina Macs self.canvas.add(Scale(dp(1),dp(1),dp(1))) self.canvas.add(self._frame) ################# PRIMARY APP CLASS ################# pass # #mark PRIMARY APP CLASS class GameApp(kivy.app.App): """Instances are a controller class for a simple game application. This is the primary class for creating a game. To implement a game, you subclass this class and override three methods. The three methods are as follows: **start**: This method initializes the game state, defining all of the game attributes. This method is like __init__ except that you should not override that method. Overriding __init__ will break your game. Hence we have provided build as an alternative. **update**: This method updates the game state at the start of every animation frame. Any code that moves objects or processes user input (keyboard or mouse) goes in this method. **draw**: This method draws all of the objects to the screen. The only thing you should have in this method are calls to `self.view.draw()`. """ # MUTABLE ATTRIBUTES @property def fps(self): """The number of frames-per-second to animate By default this value is 60 FPS. However, we cannot guarantee that the FPS is achievable. If you are having performance stuttering, you might want to drop this value to 30 FPS instead. **Invariant**: Must be an int or float > 0.""" return self._fps @fps.setter def fps(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value > 0, 'value %s is not positive' % `value` Clock.unschedule(self._refresh) self._fps = value Clock.schedule_interval(self._refresh,1.0/self._fps) # IMMUTABLE PROPERTIES @property def width(self): """The window width **Invariant**: Must be an int or float > 0.""" return self._gwidth @property def height(self): """The window height **Invariant**: Must be an int or float > 0.""" return self._gheight @property def view(self): """The Game view. Use the `draw` method in this attribute to display any `GObject` instance on the screen. See the class `GView` for more information. **Invariant**: Must be instance of GView.""" return self._view @property def input(self): """The Game input handler. Use this attribute to get information about the mouse and keyboard. See the class `GInput` for more information. **Invariant**: Must be instance of GInput.""" return self._input # BUILT-IN METHODS def __init__(self,**keywords): """**Constructor**: Creates, but does not start, a new game. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. The primary user defined attributes are the window `width` and `height`. For example, to create a game that fits inside of a 400x400 window, the constructor Game(width=400,height=400) The game window will not show until you start the game. To start the game, use the method `run()`. **You will never call the constructor or `run` yourself. That is handled for you in the provided code.""" w = keywords['width'] if 'width' in keywords else 0.0 h = keywords['height'] if 'height' in keywords else 0.0 f = keywords['fps'] if 'fps' in keywords else 60.0 assert _is_num(w), 'width %s is not a number' % `w` assert _is_num(h), 'height %s is not a number' % `h` assert _is_num(f), 'fps %s is not a number' % `value` assert f > 0, 'fps %s is not positive' % `value` self._gwidth = w self._gheight = h self._fps = f Config.set('graphics', 'width', str(self.width)) Config.set('graphics', 'height', str(self.height)) # Tell Kivy to build the application kivy.app.App.__init__(self,**keywords) # PUBLIC METHODS def build(self): """Initializes the graphics window. This is a Kivy reserved method. It is part of the Kivy application process. It should **never** be overridden.""" self._view = GView() self._view.size_hint = (1,1) self._input = GInput() self._input._register(self._view) return self.view def run(self): """Displays the game window and start the game. This is a Kivy reserved method. It is part of the Kivy application process. It should **never** be overridden.""" Clock.schedule_once(self._bootstrap,-1) kivy.app.App.run(self) def stop(self): """Closes the game window and exit Python. This is a Kivy reserved method. It is part of the Kivy application process. It should **never** be overridden.""" kivy.app.App.stop(self) sys.exit(0) def start(self): """Initializes the game state, creating a new game. This method is distinct from the built-in initializer __init__. This method is called once the game is running. You should use it to initialize any game specific attributes. **Never overridden the built-in method __init__**""" pass def update(self,dt): """Updates the state of the game one animation frame. :param dt: time in seconds since last update **Precondition**: a number (int or float) This method is called 60x a second (depending on the `fps`) to provide on-screen animation. Any code that moves objects or processes user input (keyboard or mouse) goes in this method. Think of this method as the body of the loop. You will need to add attributes that represent the current animation state, so that they can persist across animation frames. These attributes should be initialized in `start`. """ pass def draw(self): """Draws the game objects on the screen. Every single object that you draw will need to be an attribute of the `GameApp` class. This method should largely be a sequence of calls to `self.view.draw()`. """ pass # HIDDEN METHODS def _bootstrap(self,dt): """Bootstraps the clock scheduler for the game.. This method is a callback-proxy for method `start`. It handles important issues behind the scenes, particularly with setting the FPS""" Clock.schedule_interval(self._refresh,1.0/self.fps) self.start() def _refresh(self,dt): """Processes a single animation frame. :param dt: time in seconds since last update **Precondition**: a number (int or float) This method a callback-proxy for the methods `update` and `draw`. It handles important issues behind the scenes, particularly with clearing the window.""" self.view.clear() self.update(dt) self.draw()
36.902232
109
0.596304
"""Module to provide simple 2D game support. This module provides all of the classes that are to use (or subclass) to create your game. DO NOT MODIFY THE CODE IN THIS FILE. See the online documentation in Assignment 7 for more guidance. It includes information not displayed in this module.""" import kivy import kivy.app from kivy.graphics import * from kivy.graphics.instructions import * from kivy.core.audio import SoundLoader from kivy.config import Config from kivy.clock import Clock from kivy.metrics import dp from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.uix.image import Image import os, sys, os.path import numpy as np import colormodel FONT_PATH = str(os.path.join(os.path.dirname(__file__), 'Fonts')) SOUND_PATH = str(os.path.join(os.path.dirname(__file__), 'Sounds')) IMAGE_PATH = str(os.path.join(os.path.dirname(__file__), 'Images')) import kivy.resources kivy.resources.resource_add_path(FONT_PATH) kivy.resources.resource_add_path(SOUND_PATH) kivy.resources.resource_add_path(IMAGE_PATH) (int or float) """ return (_same_side(p, t[0:2], t[2:4], t[4:6]) and _same_side(p, t[2:4], t[0:2], t[4:6]) and _same_side(p, t[4:6], t[0:2], t[2:4])) def _is_num(x): """Returns: True if x is an int or float; False otherwise. Parameter x: The value to test Precondition: NONE""" return type(x) in [int,float] def _is_num_tuple(t,size): """Returns: True if t is a sequence of numbers; False otherwise. If the sequence is not of the given size, it also returns False. Parameter t: The value to test Precondition: NONE Parameter size: The size of the sequence Precondition: size is an int >= 0 """ try: return len(t) == size and reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float], t)) except: return False def _is_point_tuple(t,msize): """Returns: True if t is a point sequence (i.e. even sequence of numbers) The point tuple must be size greater than msize, or the function returns False. Parameter t: The value to test Precondition: NONE Parameter msize: The minimum size of the sequence Precondition: msize is an int >= 0 """ try: return len(t) % 2 == 0 and len(t) > msize and \ reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float], t)) except: return False def _is_gobject_list(g): """Returns: True if g is a sequence of GObjects Parameter g: The value to test Precondition: NONE """ try: return len(g) >= 0 and reduce(lambda x, y: x and y, map(lambda z: isinstance(z,GObject), g)) except: return False def _is_color(c): """Returns: True if c represents a color As with Turtles, colors may be colormodel objects or strings. They may also be sequences of 3 or 4 elements. In the case of the latter, the elements of the sequence must all be in the range 0..1. Parameter c: The value to test Precondition: NONE """ if type(c) in [colormodel.RGB, colormodel.HSV]: return True if type(c) in [tuple, list] and 3 <= len(c) <= 4: return reduce(lambda x, y: x and y, map(lambda z: type(z) in [int, float] and 0 <= z <= 1, c)) return type(c) == str and c in colormodel._TK_COLOR_MAP def _is_image_file(name): """Returns: True if name is the name of an image file Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(IMAGE_PATH+'/'+name) def _is_font_file(name): """Returns: True if name is the name of an font file Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(FONT_PATH+'/'+name) def _is_sound_file(name): """Returns: True if name is the name of an font file. Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(SOUND_PATH+'/'+name) or**: creates a new GPoint value (x,y). :param x: initial x value **Precondition**: value is an int or float. :param y: initial y value **Precondition**: value is an int or float. All values are 0.0 by default. """ self.x = x self.y = y def __eq__(self, other): """**Returns**: True if self and other are equivalent GPoint. This method uses np to test whether the coordinates are "close enough". It does not require exact equality for floats. :param other: value to compare against """ return (type(other) == GPoint and np.allclose(self.list(),other.list())) def __ne__(self, other): """**Returns**: True if self and other are not equivalent GPoint. :param other: value to compare against """ return not self == other def __str__(self): """**Returns**: Readable String representation of this GPoint. """ return "("+str(self.x)+","+str(self.y)+")" def __repr__(self): """**Returns**: Unambiguous String representation of this GPoint. """ return "%s%s" % (self.__class__,self.__str__()) def list(self): """**Returns**: A python list with the contents of this GPoint.""" return [self.x,self.y] def __add__(self, other): """**Returns**: the sum of self and other. The value returned has the same type as self (so it is either a GPoint or is a subclass of GPoint). The contents of this object are not altered. :param other: tuple value to add **Precondition**: value has the same type as self. """ assert (type(other) == type(self)), "value %(value)s is not a of type %(type)s" \ % {'value': `other`, 'type':`type(self)`} result = copy.copy(self) result.x += other.x result.y += other.y return result def __sub__(self, other): """**Returns**: the vector from tail to self. The value returned is a GPoint representing a vector with this point at its head. :param other: the tail value for the new Vector **Precondition**: value is a Point object. """ assert (type(other) == type(self)), "value %(value)s is not a of type %(type)s" \ % {'value': `other`, 'type':`type(self)`} result = copy.copy(self) result.x -= other.x result.y -= other.y return result def __mul__(self, scalar): """**Returns**: the scalar multiple of self and other. The value returned is a new GPoint. The contents of this GPoint are not altered. :param scalar: scalar to multiply by **Precondition**: value is an int or float. """ assert _is_num(scalar), "value %s is not a number" % `scalar` result = copy.copy(self) result.x *= scalar result.y *= scalar result.z *= scalar return result def __rmul__(self, scalar): """**Returns**: the scalar multiple of self and other. The value returned is a new GPoint. The contents of this GPoint are not altered. :param scalar: scalar to multiply by **Precondition**: value is an int or float. """ return self.__mul__(scalar) def interpolate(self, other, alpha): """**Returns**: the interpolation of self and other via alpha. The value returned has the same type as self (so it is either a GPoint or is a subclass of GPoint). The contents of this object are not altered. The resulting value is alpha*self+(1-alpha)*other according to GPoint addition and scalar multiplication. :param other: tuple value to interpolate with **Precondition**: value has the same type as self. :param alpha: scalar to interpolate by **Precondition**: value is an int or float. """ assert (type(other) == type(self)), "value %(value)s is not a of type %(type)s" \ % {'value': `other`, 'type':`type(self)`} assert (type(alpha) in [int,float]), "value %s is not a number" % `alpha` return alpha*self+(1-alpha)*other def distanceTo(self, other): """**Returns**: the Euclidean distance from this point to other :param other: value to compare against **Precondition**: value is a Tuple3D object. """ return np.sqrt((self.x-other.x)*(self.x-other.x)+ (self.y-other.y)*(self.y-other.y)) class GMatrix(object): """Instances are homongenous matrices for graphics transforms. This class is backed by np for fast computation. There are no publicly accessible attributes, as it is not safe to access the internals.""" def __init__(self): """**Constructor**: creates a new 4x4 identify matrix""" self._data = np.identity(4, dtype=np.float32) def __str__(self): """**Returns**: A string representation of this matrix""" return str(self._data) def __repr__(self): """**Returns**: An unambiguous string representation of this matrix""" return str(self.__class__)+str(self) def __mul__(self,other): """**Returns**: a new Matrix that is the premultiplication of this and other. This operation pre-multiplies the matrix on the right. As a result, this allows us to read graphics operations left to right (which is more natural) :param other: the matrix to pre-multiply **Precondition**: a Matrix object """ m = GMatrix() np.dot(other._data,self._data,m._data) return m def __imul__(self,other): """Premultiplies this matrix by other in place This operation pre-multiplies the matrix on the right. As a result, this allows us to read graphics operations left to right (which is more natural) :param other: the matrix to pre-multiply **Precondition**: a Matrix object """ tmp = np.dot(other._data,self._data) np.copyto(self._data,tmp) def copy(self): """**Returns**: a copy of this Matrix""" m = GMatrix() np.copyto(m._data,self._data) return m def inverse(self): """**Returns**: the inverse of this matrix""" m = GMatrix() np.copyto(m._data,np.linalg.inv(self._data)) return m def invert(self): """Inverts this matrix in place""" np.copyto(self._data,np.linalg.inv(self._data)) return self def transpose(self): """**Returns**: the transpose of this matrix""" m = GMatrix() np.copyto(m._data,np.transpose(self._data)) return m def translate(self,x=0,y=0,z=0): """Translates this matrix (in-place) by the given amount :param x: x-coordinate of translation (default 0) **Precondition**: an int or float :param y: y-coordinate of translation (default 0) **Precondition**: an int or float :param z: z-coordinate of translation (default 0) **Precondition**: an int or float """ r = np.identity(4, dtype=np.float32) r[0,3] = x r[1,3] = y r[2,3] = z tmp = np.dot(self._data,r) np.copyto(self._data,tmp) def rotate(self,ang=0,x=0,y=0,z=0): """Rotates this matrix (in place) about the given axis The rotation angle is given in degrees, not radians. Rotation is counterclockwise around the angle of rotation. :param angle: angle of rotation in degrees (default 0) **Precondition**: an int or float :param x: x-coordinate of rotation axis (default 0) **Precondition**: an int or float :param y: y-coordinate of rotation axis (default 0) **Precondition**: an int or float :param z: z-coordinate of rotation axis (default 0) **Precondition**: an int or float """ c = np.cos(np.radians(ang)) s = np.sin(np.radians(ang)) f = 1-c r = np.identity(4, dtype=np.float32) r[0] = [x*x*f+c, x*y*f-z*s, x*z*f+y*s, 0] r[1] = [y*x*f+z*s, y*y*f+c, y*z*f-x*s, 0] r[2] = [z*x*f-y*s, z*y*f+x*s, z*z*f+c, 0] tmp = np.dot(self._data,r) np.copyto(self._data,tmp) def scale(self,x=1,y=1,z=1): """Scales this matrix (in-place) by the given amount :param x: x-coordinate of the scale (default 1) **Precondition**: an int or float :param y: y-coordinate of the scale (default 1) **Precondition**: an int or float :param z: z-coordinate of the scale (default 1) **Precondition**: an int or float """ s = np.identity(4, dtype=np.float32) s[0,0] = x s[1,1] = y s[2,2] = z tmp = np.dot(self._data,s) np.copyto(self._data,tmp) def _transform(self,x=0,y=0,z=0): """**Returns**: The given point transformed by this matrix The value returned is a tuple. :param x: x-coordinate to transform (default 0) **Precondition**: an int or float :param y: y-coordinate to transform (default 0) **Precondition**: an int or float :param z: z-coordinate to transform (default 0) **Precondition**: an int or float """ b = np.array([x,y,z,1], dtype=np.float32) tmp = np.dot(self._data,b) return map(float,tuple(tmp[:-1])) def transform(self,point): """**Returns**: The given point transformed by this matrix The value returned is a GPoint. :param point: the point to transform **Precondition**: a GPoint """ b = np.array([point.x,point.y,0,1], dtype=np.float32) tmp = np.dot(self._data,b) return GPoint(float(tmp[0]),float(tmp[1])) f._trans.y = float(value) self._mtrue = False @property def width(self): """The horizontal width of this shape. Positive values go to the right. **Invariant**: Must be an int or float > 0.""" return self._width @width.setter def width(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value > 0, 'value %s is not positive' % `value` self._width = float(value) if self._defined: self._reset() @property def height(self): """The vertical height of this shape. Positive values go up. **Invariant**: Must be an int or float > 0.""" return self._height @height.setter def height(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value > 0, 'value %s is not positive' % `value` self._height = float(value) if self._defined: self._reset() @property def scale(self): """The scaling factor of this shape. The scale is a fast way to cause a shape to grow or shrink in size. Essentially, the object will multiple the width and height by the scale. So a scale less than 1 will shrink the object, while a scale greater than 1 will enlarge the object. The scale may either be a single number, or a pair of two numbers. If it is a single number, it will scale the width and height by the same amount. If it is a pair, it will scale the width by the first value, and the height by the second. **Invariant**: Must be either a number (int or float) or a pair of numbers.""" return (self._scale.x,self._scale.y) @scale.setter def scale(self,value): assert _is_num(value) or _is_num_tuple(value,2), \ 'value %s is not a valid scaling factor' % `value` if _is_num(value): self._scale.x = float(value) self._scale.y = float(value) else: self._scale.x = float(value[0]) self._scale.y = float(value[1]) self._mtrue = False @property def angle(self): """The angle of rotation about the center. The angle is measured in degrees (not radians) counter-clockwise. **Invariant**: Must be an int or float.""" return self._rotate.angle @angle.setter def angle(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = np.allclose([self._rotate.angle],[value]) self._rotate.angle = float(value) if not diff: self._mtrue = False @property def fillcolor(self): """The object fill color. This value is used to color the backgrounds or, in the case of solid shapes, the shape interior. The default representation of color in GObject is a 4-element list of floats between 0 and 1 (representing r, g, b, and a). As with the Turtle, you may also assign color an `RGB` or `HSV` object from `colormodel`, or a string with a valid color name. If you chose either of these alternate representations (a string or an object from `colormodel`), Python will automatically convert the result into a 4-element list. **Invariant**: Must be a 4-element list of floats between 0 and 1.""" return self._fillcolor.rgba @fillcolor.setter def fillcolor(self,value): assert _is_color(value), 'value %s is not a valid color' % `value` if type(value) in [tuple, list] and len(value) == 3: value = list(value)+[1.0] elif type(value) in [colormodel.RGB, colormodel.HSV]: value = value.glColor() elif type(value) == str: if value[0] == '#': value = colormodel.RGB.CreateWebColor(c).glColor() else: value = colormodel.RGB.CreateName(c).glColor() self._fillcolor = Color(value[0],value[1],value[2],value[3]) if self._defined: self._reset() @property def linecolor(self): """The object line color. The default representation of color in GObject is a 4-element list of floats between 0 and 1 (representing r, g, b, and a). As with the Turtle, you may also assign color an `RGB` or `HSV` object from `colormodel`, or a string with a valid color name. If you chose either of these alternate representations (a string or an object from `colormodel`), Python will automatically convert the result into a 4-element list. **Invariant**: Must be a 4-element list of floats between 0 and 1.""" return self._linecolor.rgba @linecolor.setter def linecolor(self,value): assert _is_color(value), 'value %s is not a valid color' % `value` if type(value) in [tuple, list] and len(value) == 3: value = list(value)+[1.0] elif type(value) in [colormodel.RGB, colormodel.HSV]: value = value.glColor() elif type(value) == str: if value[0] == '#': value = colormodel.RGB.CreateWebColor(c).glColor() else: value = colormodel.RGB.CreateName(c).glColor() self._linecolor = Color(value[0],value[1],value[2],value[3]) if self._defined: self._reset() @property def name(self): """The name of this object. This value is for debugging purposes only. If you name an object, the name will appear when you convert the object to a string. This will allow you to tell which object is which in your watches. **Invariant**: Must be a string or None.""" return self._name @name.setter def name(self,value): assert value is None or type(value) == str, 'value %s is not a valid name' % `value` self._name = value @property def left(self): """The left edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x-width/2`. Otherwise, it is the left-most value of the bounding box. Changing this value will shift the center of the object so that the left edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x-self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return min(p0,p1,p2,p3) @left.setter def left(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.left self.x += diff @property def right(self): """The right edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x+width/2`. Otherwise, it is the right-most value of the bounding box. Changing this value will shift the center of the object so that the right edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x+self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return max(p0,p1,p2,p3) @right.setter def right(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.right self.x += diff @property def top(self): """The vertical coordinate of the top edge. The value depends on the current angle of rotation. If rotation is 0, it is `y+height/2`. Otherwise, it is the top-most value of the bounding box. Changing this value will shift the center of the object so that the top edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y+self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return max(p0,p1,p2,p3) @top.setter def top(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.top self.y += diff @property def bottom(self): """The vertical coordinate of the bottom edge. The value depends on the current angle of rotation. If rotation is 0, it is `y-height/2`. Otherwise, it is the bottom-most value of the bounding box. Changing this value will shift the center of the object so that the bottom edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y-self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return min(p0,p1,p2,p3) @bottom.setter def bottom(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.bottom self.y += diff @property def matrix(self): """The transformation matrix for this object This value is constructed dynamically as needed. It should only be used internally to this file. **Invariant**: Either a GMatrix or None""" if not self._mtrue or self._matrix is None: self._matrix = GMatrix() self._matrix.translate(self._trans.x,self._trans.y) self._matrix.rotate(self._rotate.angle,z=1) self._matrix.scale(self._scale.x,self._scale.y) self._invrse = GMatrix() self._invrse.scale(1.0/self._scale.x,1.0/self._scale.y) self._invrse.rotate(-self._rotate.angle,z=1) self._invrse.translate(-self._trans.x,-self._trans.y) self._mtrue = True return self._matrix @property def inverse(self): """The transformation matrix for this object This value is constructed dynamically as needed. It should only be used internally to this file. **Invariant**: Either a GMatrix or None""" if not self._mtrue or self._matrix is None: self._matrix = GMatrix() self._matrix.translate(self._trans.x,self._trans.y) self._matrix.rotate(self._rotate.angle,z=1) self._matrix.scale(self._scale.x,self._scale.y) self._invrse = GMatrix() self._invrse.scale(1.0/self._scale.x,1.0/self._scale.y) self._invrse.rotate(-self._rotate.angle,z=1) self._invrse.translate(-self._trans.x,-self._trans.y) self._mtrue = True return self._invrse def __init__(self,**keywords): """**Constructor**: Creates a new GObject to be drawn. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to initialize the x position and the fill color, use the constructor call GObject(x=2,fillcolor=colormodel.RED) You do not need to provide the keywords as a dictionary. The ** in the parameter `keywords` does that automatically. Any attribute of this class may be used as a keyword. The argument must satisfy the invariants of that attribute. See the list of attributes of this class for more information.""" self._defined = False self._trans = Translate(0,0,0) self._rotate = Rotate(angle=0,axis=(0,0,1)) self._scale = Scale(1,1,1) if 'width' in keywords: self.width = keywords['width'] else: self._width = 1 if 'height' in keywords: self.height = keywords['height'] else: self._height = 1 if 'angle' in keywords: self.angle = keywords['angle'] if 'x' in keywords: self.x = keywords['x'] elif 'left' in keywords: self.left = keywords['left'] elif 'right' in keywords: self.right = keywords['right'] if 'y' in keywords: self.y = keywords['y'] elif 'bottom' in keywords: self.bottom = keywords['bottom'] elif 'top' in keywords: self.top = keywords['top'] self.fillcolor = keywords['fillcolor'] if 'fillcolor' in keywords else (1,1,1,1) self.linecolor = keywords['linecolor'] if 'linecolor' in keywords else (0,0,0,1) self.name = keywords['name'] if 'name' in keywords else None def __str__(self): """**Returns**: A string representation of this object.""" if self.name is None: s = '[' else: s = '[name=%s,' % self.name return '%s,center=(%s,%s),width=%s,height=%s,angle=%s]' \ % (s,`self.x`,`self.y`,`self.height`,`self.width`,`self.angle`) def __repr__(self): """**Returns**: An unambiguous representation of this object.""" return str(self.__class__)+str(self) def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float By default, this method just checks the bounding box of the shape. **Warning**: Accessing this value on a rotated object may slow down your framerate significantly. """ if self._rotate.angle == 0.0: return abs(x-self.x) < self.width/2.0 and abs(y-self.y) < self.height/2.0 p = self.matrix.inverse()._transform(x,y) return abs(p[0]) < self.width/2.0 and abs(p[1]) < self.height/2.0 def transform(self,point): """**Returns**: The given point transformed to local coordinate system :param point: the point to transform **Precondition**: a GPoint or a pair of numbers (int or float) This method is important for mouse selection. It helps you understand where in the shape the selection takes place. In the case of objects with children, lik e`GScene`, this method is necessary to properly use the contains method on the children. The value returned is a GPoint.""" if isinstance(point,GPoint): return self.inverse.transform(point) else: assert len(point) == 2 and _is_num_tuple(point,2) p = self.inverse._transform(point[0],point[2]) return GPoint(p[0],p[1]) def draw(self, view): """Draw this shape in the provide view. :param view: view to draw to **Precondition**: an *instance of* `GView` Ideally, the view should be the one provided by `GameApp`.""" view.draw(self._cache) def _reset(self): """Resets the drawing cache""" self._cache = InstructionGroup() self._cache.add(PushMatrix()) self._cache.add(self._trans) self._cache.add(self._rotate) self._cache.add(self._scale) class GRectangle(GObject): """Instances represent a solid rectangle. As with `GObject`, the attributes x and y refer to the center of the rectangle. This is so that when you rotate the rectangle, it spins about the center. The interior (fill) color of this rectangle is `fillcolor`, while `linecolor` is the color of the border. The only new property for this class is `linewidth`, which controls the width of the border around the rectangle. For all other properties, see the documentation for `GObject`.""" @property def linewidth(self): """The width of the exterior line of this shape. Setting this to 0 means that the rectangle has no border. **Invariant**: Must be an int or float >= 0.""" return self._linewidth @linewidth.setter def linewidth(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value >= 0, 'value %s is negative' % `value` self._linewidth = value if self._defined: self._reset() def __init__(self,**keywords): """**Constructor**: Creates a new solid rectangle :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a red square centered at (0,0), use the constructor call GRectangle(x=0,y=0,width=10,height=10,fillcolor=colormodel.RED) This class supports the all same keywords as `GObject` plus the additional keyword `linewidth`.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 GObject.__init__(self,**keywords) self._reset() self._defined = True def _reset(self): """Resets the drawing cache""" GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Rectangle(pos=(x,y), size=(self.width, self.height)) self._cache.add(self._fillcolor) self._cache.add(fill) if self.linewidth > 0: line = Line(rectangle=(x,y,self.width,self.height),joint='miter', close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GEllipse(GRectangle): """Instances represent a solid ellipse. The ellipse is the largest one that can be drawn inside of a rectangle whose bottom center is at (x,y), with the given width and height. The interior (fill) color of this ellipse is `fillcolor`, while `linecolor` is the color of the border. This class has exactly the same properties as `GRectangle`. See the documentation of that class and `GObject` for a complete list of properties.""" def __init__(self,**keywords): """**Constructor**: Creates a new solid ellipse :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a red circle centered at (0,0), use the constructor call GEllipse(x=0,y=0,width=10,height=10,fillcolor=colormodel.RED) This class supports the all same keywords as `GRectangle`.""" GRectangle.__init__(self,**keywords) def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method is better than simple rectangle inclusion. It checks that the point is within the proper radius as well. **Warning**: Accessing this value on a rotated object may slow down your framerate significantly. """ rx = self.width/2.0 ry = self.height/2.0 if self._rotate.angle == 0.0: dx = (x-self.x)*(x-self.x)/(rx*rx) dy = (y-self.y)*(y-self.y)/(ry*ry) else: p = self.matrix.inverse()._transform(x,y) dx = p[0]*p[0]/(rx*rx) dy = p[1]*p[1]/(ry*ry) return (dx+dy) <= 1.0 def _reset(self): """Resets the drawing cache""" GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Ellipse(pos=(x,y), size=(self.width,self.height)) self._cache.add(self._fillcolor) self._cache.add(fill) if self._linewidth > 0: line = Line(ellipse=(x,y,self.width,self.height),close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GImage(GRectangle): """Instances represents a rectangular image. The image is given by a JPEG, PNG, or GIF file whose name is stored in the attribute `source`. Image files should be stored in the **Images** directory so that Kivy can find them without the complete path name. This class acts much like is parent `GRectangle` and shares all of the same properties. As with that class, you can add a border to the rectangle if you want, using the attribute `linewidth`. If the attributes `width` and `height` do not agree with the actual size of the image, the image is scaled to fit.Furthermore, if you define `fillcolor`, Kivy will tint your image by the given color.` If the image supports transparency, then this object can be used to represent irregular shapes. However, the `contains` method still treats this shape as a rectangle. """ @property def source(self): """The source file for this image. **Invariant**. Must be a string refering to a valid file.""" return self._source @source.setter def source(self,value): assert value is None or _is_image_file(value), 'value %s is not an image file' % `value` self._source = value if self._defined: self._reset() def __init__(self,**keywords): """**Constructor**: Creates a new rectangle image :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to load the image `beach-ball.png`, use the constructor GImage(x=0,y=0,width=10,height=10,source='beach-ball.png') This class supports the all same keywords as `GRectangle`; the only new keyword is `source`. See the documentation of `GRectangle` and `GObject` for the other supported keywords.""" self._defined = False self.source = keywords['source'] if 'source' in keywords else None GRectangle.__init__(self,**keywords) self._defined = True def _reset(self): """Resets the drawing cache""" GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Rectangle(pos=(x,y), size=(self.width, self.height),source=self.source) self._cache.add(self._fillcolor) self._cache.add(fill) if self.linewidth > 0: line = Line(rectangle=(x,y,self.width,self.height),joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GLabel(GRectangle): """Instances represent an (uneditable) text label This object is exactly like a GRectangle, except that it has the possibility of containing some text. The attribute `text` defines the text content of this label. Uses of the escape character '\\n' will result in a label that spans multiple lines. As with any `GRectangle`, the background color of this rectangle is `fillcolor`, while `linecolor` is the color of the text. The text itself is aligned within this rectangle according to the attributes `halign` and `valign`. See the documentation of these attributes for how alignment works. There are also attributes to change the point size, font style, and font name of the text. The `width` and `height` of this label will grow to ensure that the text will fit in the rectangle, no matter the font or point size. To change the font, you need a .ttf (TrueType Font) file in the Fonts folder; refer to the font by filename, including the .ttf. If you give no name, it will use the default Kivy font. The `bold` attribute only works for the default Kivy font; for other fonts you will need the .ttf file for the bold version of that font. See the provided `ComicSans.ttf` and `ComicSansBold.ttf` for an example.""" @property def font_size(self): """Size of the text font in points. **Invariant**: Must be a positive number (int or float)""" return self._fsize @font_size.setter def font_size(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._fsize = value self._label.font_size = value self._label.texture_update() @property def font_name(self): """File name for the .ttf file to use as a font **Invariant**: Must be a string referring to a .ttf file in folder Fonts""" return self._label.font_name @font_name.setter def font_name(self,value): assert _is_font_file(value), 'value %s is not a font name' % `value` self._label.font_name = value self._label.texture_update() @property def bold(self): """Boolean indicating whether or not the text should be bold. This value only works on the default Kivy font. It does not work on custom .ttf files. In that case, you need the bold version of the .ttf file. See `ComicSans.ttf` and `ComicSansBold.ttf` for an example. **Invariant**: Must be a boolean""" return self._label.bold @bold.setter def bold(self,value): assert type(value) == bool, `value`+' is not a bool' self._label.bold = value self._label.texture_update() @property def text(self): """Text for this label. The text in the label is displayed as a single line, or broken up into multiple lines in the presence of the escape character '\\n'. The `width` and `height` of this label will grow to ensure that the text will fit in the rectangle. **Invariant**: Must be a string""" return self._label.text @text.setter def text(self,value): assert type(value) == str, 'value %s is not a string' % `value` self._label.text = value self._label.texture_update() @property def halign(self): """Horizontal alignment for this label. The text is horizontally anchored inside of the label rectangle at either the left, the right or the center. This means that as the size of the label increases, the text will still stay rooted at that anchor. By default, the text is centered. **Invariant**: Must be one of 'left', 'right', or 'center'""" return self._halign @halign.setter def halign(self,value): assert value in ('left','right','center'), 'value %s is not a valid horizontal alignment' % `value` self._halign = value self._label.halign = value if self._defined: self._reset() @property def valign(self): """Vertical alignment for this label. The text is vertically anchored inside of the label rectangle at either the top, the bottom or the middle. This means that as the size of the label increases, the text will still stay rooted at that anchor. By default, the text is in the middle. **Invariant**: Must be one of 'top', 'bottom', or 'middle'""" return self._valign @valign.setter def valign(self,value): assert value in ('top','middle','bottom'), 'value %s is not a valid vertical alignment' % `value` self._valign = value self._label.valign = value if self._defined: self._reset() @property def x(self): """The horizontal coordinate of the object center. **Invariant**: Must be an int or float.""" return self._trans.x @x.setter def x(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._trans.x = float(value) self._mtrue = False self._hanchor = 'center' self._ha = value @property def y(self): """The vertical coordinate of the object center.. **Invariant**: Must be an int or float.""" return self._trans.y @y.setter def y(self,value): assert _is_num(value), 'value %s is not a number' % `value` self._trans.y = float(value) self._mtrue = False self._vanchor = 'center' self._hv = value @property def left(self): """The left edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x-width/2`. Otherwise, it is the left-most value of the bounding box. Changing this value will shift the center of the object so that the left edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x-self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return min(p0,p1,p2,p3) @left.setter def left(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.left self.x += diff self._hanchor = 'left' self._ha = value @property def right(self): """The right edge of this shape. The value depends on the current angle of rotation. If rotation is 0, it is `x+width/2`. Otherwise, it is the right-most value of the bounding box. Changing this value will shift the center of the object so that the right edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.x+self.width/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[0] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[0] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[0] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[0] return max(p0,p1,p2,p3) @right.setter def right(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.right self.x += diff self._hanchor = 'right' self._ha = value @property def top(self): """The vertical coordinate of the top edge. The value depends on the current angle of rotation. If rotation is 0, it is `y+height/2`. Otherwise, it is the top-most value of the bounding box. Changing this value will shift the center of the object so that the top edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y+self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return max(p0,p1,p2,p3) @top.setter def top(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.top self.y += diff self._vanchor = 'top' self._hv = value @property def bottom(self): """The vertical coordinate of the bottom edge. The value depends on the current angle of rotation. If rotation is 0, it is `y-height/2`. Otherwise, it is the bottom-most value of the bounding box. Changing this value will shift the center of the object so that the bottom edge matches the new value. **Warning**: Accessing this value on a rotated object will slow down your framerate significantly. **Invariant**: Must be an int or float.""" if self._rotate.angle == 0.0: return self.y-self.height/2.0 p0 = self.matrix._transform(self.x-self.width/2.0, self.y-self.height/2.0)[1] p1 = self.matrix._transform(self.x+self.width/2.0, self.y-self.height/2.0)[1] p2 = self.matrix._transform(self.x+self.width/2.0, self.y+self.height/2.0)[1] p3 = self.matrix._transform(self.x-self.width/2.0, self.y+self.height/2.0)[1] return min(p0,p1,p2,p3) @bottom.setter def bottom(self,value): assert _is_num(value), 'value %s is not a number' % `value` diff = value-self.bottom self.y += diff self._vanchor = 'bottom' self._hv = value def __init__(self,**keywords): """**Constructor**: Creates a new text label. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a label containing the word 'Hello', use the constructor call GLabel(text='Hello') This class supports the same keywords as `GRectangle`, as well as additional attributes for the text properties (e.g. font size and name).""" self._defined = False self._hanchor = 'center' self._vanchor = 'center' self._label = Label(**keywords) self._label.size_hint = (None,None) self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 self.halign = keywords['halign'] if 'halign' in keywords else 'center' self.valign = keywords['valign'] if 'valign' in keywords else 'middle' GObject.__init__(self,**keywords) self._reset() self._defined = True self._label.bind(texture_size=self._callback) def __str__(self): """**Returns**: A string representation of this object.""" if self.name is None: s = '[' else: s = '[name=%s,' % self.name return '%s,text=%s,center=(%s,%s),angle=%s]' \ % (s,`self.text`,`self.x`,`self.y`,`self.angle`) def _callback(self,instance=None,value=None): """Workaround to deal with parameter requirements for callbacks""" if self._defined: self._reset() def _reset(self): """Resets the drawing cache""" self._label.size = self._label.texture_size self._label.center = (0,0) self._label.color = self.linecolor self._defined = False self.width = max(self.width, self._label.width) self.height = max(self.height,self._label.height) self._defined = True if self._hanchor == 'left': self._trans.x = self._ha+self.width/2.0 elif self._hanchor == 'right': self._trans.x = self._ha-self.width/2.0 if self._vanchor == 'top': self._trans.y = self._hv-self.height/2.0 elif self._vanchor == 'bottom': self._trans.y = self._hv+self.height/2.0 if self.halign == 'left': self._label.x = -self.width/2.0 elif self.halign == 'right': self._label.right = self.width/2.0 if self.valign == 'top': self._label.top = self.height/2.0 elif self.valign == 'bottom': self._label.bottom = -self.height/2.0 GObject._reset(self) x = -self.width/2.0 y = -self.height/2.0 fill = Rectangle(pos=(x,y), size=(self.width,self.height)) self._cache.add(self._fillcolor) self._cache.add(fill) self._cache.add(self._label.canvas) if self._linewidth > 0: line = Line(rectangle=(x,y,self.width,self.height),joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) t, these values are 0. However, if they are nonzero, then Python will add them to all of the points in the path, shifting the path accordingly. """ @property def points(self): """The sequence of points that make up this line. **Invariant**: Must be a sequence (list or tuple) of int or float. The length of this sequence must be even with length at least 4.""" return self._points @points.setter def points(self,value): assert _is_point_tuple(value,2),'value %s is not a valid list of points' % `value` self._points = tuple(value) if self._defined: self._reset() @property def linewidth(self): """The width of this path. Setting this value to 0 means that the path is invisible. **Invariant**: Must be an int or float >= 0.""" return self._linewidth @linewidth.setter def linewidth(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value >= 0, 'value %s is negative' % `value` self._linewidth = value if self._defined: self._reset() @property def width(self): """The horizontal width of this path. The value is the width of the smallest bounding box that contains all of the points in the line AND the origin (0,0). **Invariant**: Must be an int or float > 0.""" px = self.points[::2]+(0,0) return 2*max(max(px),-min(px)) @property def height(self): """The vertical height of this path. The value is the height of the smallest bounding box that contains all of the points in the line AND the origin (0,0). **Invariant**: Must be an int or float > 0.""" py = self.points[1::2]+(0,0) return 2*max(max(py),-min(py)) def __init__(self,**keywords): """**Constructor**: Creates a new sequence of line segments. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a line from (0,0) to (2,3) with width 2, use the constructor call GLine(points=[0,0,2,3],linewidth=2) This class supports the same keywords as `GObject`, though some of them are unused, as the `width` and `height` attributes are now immutable. The primary keywords for this class are `points`, `linecolor`, and `linewidth`.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 1.0 self.points = keywords['points'] if 'points' in keywords else (0,0,10,10) GObject.__init__(self,**keywords) self._reset() self._defined = True def contains(self,x,y): """**Returns**: True if this path contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method always returns `False` as a `GPath` has no interior.""" return False def near(self,x,y): """**Returns**: True if this path is near the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float To determine if (x,y) is near the path, we compute the minimum distances from (x,y) to the path. If this distance is less than e-6, we return True.""" size = len(self.points)/2 epsilon = 1e-6 for ii in range(size-1): p = self.points[2*ii :2*ii+2] q = self.points[2*ii+2:2*ii+4] if p == q: test = np.sqrt((q[0]-x)*(q[0]-x)+(q[1]-y)*(q[1]-y)) < epsilon else: num = abs((q[0]-p[0])*x-(q[1]-p[1])*y+q[0]*p[1]-p[0]*q[1]) den = np.sqrt((q[0]-p[0])*(q[0]-p[0])+(q[1]-p[1])*(q[1]-p[1])) test = num/den if test: return True return self.contains(x,y) def _reset(self): """Resets the drawing cache""" GObject._reset(self) self._cache.add(self._linecolor) line = Line(points=self.points,cap='round',joint='round',width=self.linewidth) self._cache.add(line) self._cache.add(PopMatrix()) class GTriangle(GPath): """Instances represent a solid triangle. The triangle is defined as a sequence of three point. Just as with the `GPath` class (which is the parent of this class), it has an attribute `point` which represents this points as an even-length sequence of ints or floats. The interior (fill) color of this triangle is `fillcolor`, while `linecolor` is the color of the border. If `linewidth` is set to 0, then the border is not visible. As with `GPath`, the attributes `x` and `y` may be used to shift the triangle position. By default, these values are 0. However, if they are nonzero, then Python will add them to the triangle vertices. Similarly, the attributes `width` and `height` are immutable, and are computed directly from the points""" @property def points(self): """The sequence of vertices that make up this trianle. **Invariant**: Must be a sequence (list or tuple) of int or float. The length of this sequence must be exactly 6.""" return self._points @points.setter def points(self,value): assert _is_num_tuple(value,6),'value %s is not a valid list of points' % `value` self._points = tuple(value) if self._defined: self._reset() def __init__(self,**keywords): """**Constructor**: Creates a new solid triangle. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a red triangle with vertices (0,0), (2,3), and (0,4), use the constructor call GTriangle(points=[0,0,2,3,0,4],fillcolor=colormodel.RED) As with `GPath` the `width` and `height` attributes of this class are both immutable. They are computed from the list of points.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 self.points = keywords['points'] if 'points' in keywords else (-100,-58,0,116,100,-58) GObject.__init__(self,**keywords) self._reset() self._defined = True def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method uses a standard test for triangle inclusion.""" return _in_triangle((x,y),self._points) def _reset(self): """Resets the drawing cache""" GObject._reset(self) vertices = () for x in range(3): vertices += self.points[2*x:2*x+2]+(0,0) mesh = Mesh(vertices=vertices, indices=range(3), mode='triangle_strip') self._cache.add(self._fillcolor) self._cache.add(mesh) if self.linewidth > 0: line = Line(points=self.points,joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) class GPolygon(GPath): """Instances represent a solid polygon. The polygon is a triangle fan from the center of the polyon to the vertices in the attribute `points`. The center of the polygon is always the point (0,0), unless you reassign the attributes `x` and `y`. However, as with `GPath`, if you assign the attributes `x` and `y`, then Python will shift all of the vertices by that same amount. Hence the polygon vertices must be defined as triangle fan centered at the origin. The interior (fill) color of this triangle is `fillcolor`, while `linecolor` is the color of the border. If `linewidth` is set to 0, then the border is not visible. The polygon may also be textured by specifying a source image. The texture coordinates of each vertex will be relative to the size of the image. For example, if the image is 64x64, then the quad polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle equal to the image. You can adjust the size of the source image with the attributes `source_width` and `source_height`. If the polygon is larger than the image, then the texture will repeat. As with `GPath`, the attributes `width` and `height` are immutable, and are computed directly from the points""" @property def points(self): """The sequence of points that make up this polygon. **Invariant**: Must be a sequence (list or tuple) of int or float. The length of this sequence must be even with length at least 6.""" return self._points @points.setter def points(self,value): assert _is_point_tuple(value,4),'value %s is not a valid list of points' % `value` self._points = tuple(value) if self._defined: self._reset() @property def source(self): """The source image for texturing this polygon **Invariant**. Must be a string refering to a valid file.""" return self._source @source.setter def source(self,value): assert value is None or _is_image_file(value), 'value %s is not an image file' % `value` self._source = value if self._defined: self._reset() @property def source_width(self): """The width to scale the source image. The texture coordinates of each vertex will be relative to the size of the image. For example, if the image is 64x64, then the polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle equal to the image. This attribute allows you to resize the image for these texture coordinates. So if the image is 512x64, setting this value to 64 will be as if the image was originally 64x64. If this value is None, the Python will use the normal width of the image file **Invariant**. Must be a number (int or float) > 0 or None.""" return self._source_width @source_width.setter def source_width(self,value): assert value is None or _is_num(value), 'value %s is not a valid width' % `value` self._source_width = None if self._defined: self._reset() @property def source_height(self): """The height to scale the source image. The texture coordinates of each vertex will be relative to the size of the image. For example, if the image is 64x64, then the polygon (-32,-32,-32,32,32,32,32,-32) will be a rectangle equal to the image. This attribute allows you to resize the image for these texture coordinates. So if the image is 64x512, setting this value to 64 will be as if the image was originally 64x64. If this value is None, the Python will use the normal width of the image file **Invariant**. Must be a number (int or float) > 0 or None.""" return self._source_width @source_height.setter def source_height(self,value): assert value is None or _is_num(value), 'value %s is not a valid width' % `value` self._source_height = None if self._defined: self._reset() def __init__(self,**keywords): """**Constructor**: Creates a new solid polyon :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a hexagon, use the constructor call GPolygon(points=[87,50,0,100,-87,50,-87,-50,0,-100,87,-50]) As with `GPath` the `width` and `height` attributes of this class are both immutable. They are computed from the list of points.""" self._defined = False self.linewidth = keywords['linewidth'] if 'linewidth' in keywords else 0.0 self.points = keywords['points'] if 'points' in keywords else (-100,-58,0,116,100,-58) self.source = keywords['source'] if 'source' in keywords else None self.source_width = keywords['source_width'] if 'source_width' in keywords else None self.source_height = keywords['source_height'] if 'source_height' in keywords else None GObject.__init__(self,**keywords) self._reset() self._defined = True def contains(self,x,y): """**Returns**: True if this shape contains the point (x,y), False otherwise. :param x: x coordinate of point to check **Precondition**: an int or float :param y: y coordinate of point to check **Precondition**: an int or float This method cycles through each triangle in the triangle fan and tests each triangle for inclusion.""" found = False for i in xrange(4,len(self._points),2): t = (0,0)+self.points[i-4:i] found = found or _in_triangle((x,y),t) return found def _make_mesh(self): """Creates the mesh for this polygon""" size = len(self.points)/2 try: texture = Image(source=self.source).texture texture.wrap = 'repeat' tw = float(texture.width) if self.source_width is None else self.source_width th = float(texture.height) if self.source_height is None else self.source_height verts = (0,0,0.5,0.5) for x in range(size): pt = self.points[2*x:2*x+2] self._verts += pt+(pt[0]/tw+0.5,pt[1]/th+0.5) pt = self.points[0:2] verts += pt+(pt[0]/tw+0.5,pt[1]/th+0.5) self._mesh = Mesh(vertices=verts, indices=range(size+2), mode='triangle_fan', texture=texture) except BaseException as e: verts = (0,0,0,0) for x in range(size): verts += self.points[2*x:2*x+2]+(0,0) verts += self.points[0:2]+(0,0) self._mesh = Mesh(vertices=verts, indices=range(size+2), mode='triangle_fan') def _reset(self): """Resets the drawing cache""" GObject._reset(self) self._make_mesh() self._cache.add(self._fillcolor) self._cache.add(self._mesh) if self.linewidth > 0: line = Line(points=self.points,joint='miter',close=True,width=self.linewidth) self._cache.add(self._linecolor) self._cache.add(line) self._cache.add(PopMatrix()) en(self): """The list of GObjects stores in this scene. The objects are drawn as if (x,y) is the origin. Therefore, changing the attributes `x` and `y` will shift all of the children on the screen. **Invariant**: Must be a list or tuple of GObjects (possibly empty)""" return tuple(self._children) @children.setter def children(self,value): assert _is_gobject_list(value), 'value %s is not a list of GObjects' % `value` self._children = list(value) if self._defined: self._reset() @property def width(self): """The horizontal width of this path. The value is the width of the smallest bounding box that contains all of the objects in this scene (and the center) **Invariant**: Must be an int or float > 0.""" max = 0 for x in self.children: w = x.x+x.width/2.0 if w > max: max = w return max*2 @property def height(self): """The vertical height of this path. The value is the height of the smallest bounding box that contains all of the objects in this scene (and the center) **Invariant**: Must be an int or float > 0.""" max = 0 for x in self.children: h = x.y+x.height/2.0 if h > max: max = h return max*2 def __init__(self,**keywords): """**Constructor**: Creates a new scene graph node :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to create a scene with shapes rect, tri, and circ, call the constructor GScene(children=[rect,tri,circ]) This class supports the same keywords as `GObject`, though some of them are unused, as the `width` and `height` attributes are now immutable.""" self._defined = False self.children = keywords['children'] if 'children' in keywords else [] GObject.__init__(self,**keywords) self._reset() self._defined = True def _reset(self): """Resets the drawing cache""" GObject._reset(self) for x in self.children: self._cache.add(x._cache) self._cache.add(PopMatrix()) e. The default value is 1. **Invariant**: Must float in the range 0..1.""" return self._sound.volume @volume.setter def volume(self,value): assert type(value) in [int, float] and value >= 0 and value <= 1, \ 'value %s is not a valid volume' % `value` self._sound.volume = value @property def source(self): """The source file for this sound. **Immutable**: This value cannot be changed after the sound is loaded. **Invariant**: Must be a nonempty string.""" return self._source def __init__(self,source): """**Constructor**: Loads a new sound from a file. :param source: The string providing the name of a sound file **Precondition**: source is the name of a valid sound file """ assert _is_sound_file(source), 'source %s is not a sound file' % `filename` self._source = source self._sound = SoundLoader.load(source) if self._sound is None: raise IOError('Module game2d cannot read the file %s' % `source`) def play(self): """Plays this sound. The sound will play until completion, or interrupted by another sound""" self._sound.play() class SoundLibrary(object): """Instances are a dictionary that maps sounds to Sound objects. This class implements to the dictionary interface to make it easier to load sounds and manage them. To load a sound, simply assign it to the library object, as follows: soundlib['soundname'] = 'soundfile.wav' The sound library will load the sound and map it to 'soundname' as the key. To play the sound, we access it as follows: soundlib['soundname'].play() """ def __init__(self): """**Constructor**: Creates a new, empty sound library.""" if not _INITIALIZED: init() self._data = {} def __len__(self): """**Returns**: The number of sounds in this library.""" return len(self._data) def __getitem__(self, key): """**Returns**: The Sound object for the given sound name. :param key: The key identifying a sound object **Precondition**:: key is a string. """ return self._data[key] def __setitem__(self, key, filename): """Creates a sound object from the file filename and assigns it the given name. :param key: The key identifying a sound object **Precondition**:: key is a string. :param filename: The name of the file containing the sound source **Precondition**:: filename is the name of a valid sound file. """ assert is_sound_file(filename), `filename`+' is not a sound file' self._data[key] = Sound(filename) def __delitem__(self, key): """Deletes the Sound object for the given sound name. :param key: The key identifying a sound object **Precondition**:: key is a string. """ del self._data[key] def __iter__(self): """**Returns**: The iterator for this sound dictionary.""" return self._data.iterkeys() def iterkeys(self): """**Returns**: The key iterator for this sound dictionary.""" return self._data.iterkeys() sable all mouse clicks or drags. The value is True by default. **Invariant**: Must be a bool""" return self._touch_enabled @touch_enabled.setter def touch_enabled(self,value): assert type(value) == bool, 'value %s is not a bool' % `value` if value and not self._touch_enabled: self._enable_touch() elif not value and self._touch_enabled: self._disable_touch() self._touch_enabled = value @property def keyboard_enabled(self): """Whether the keyboard interface is currently enabled. Setting this value to False will disable all key presses. The value is True by default. **Invariant**: Must be a bool""" return self._keyboard_enabled @keyboard_enabled.setter def keyboard_enabled(self,value): assert type(value) == bool, 'value %s is not a bool' % `value` if value and not self._keyboard_enabled: self._enable_keyboard() elif not value and self._keyboard_enabled: self._disable_keyboard() self._keyboard_enabled = value @property def touch(self): """The current (x,y) coordinate of the mouse, if pressed. This method only returns coordinates if the mouse button is pressed. If the mouse button is not pressed it returns None. The origin (0,0) corresponds to the bottom left corner of the application window. There is currently no way to get the location of the mouse when the button is not pressed. This a limitation of Kivy. **Immutable**: This value cannot be altered. **Invariant**: Must be either a GPoint or None (if there is no touch).""" if self._touch is None: return None return GPoint(self._touch.x/dp(1),self._touch.y/dp(1)) @property def key_count(self): """The number of keys currently held down. This attribute is a quick way to check whether the user has pressed any keys. **Immutable**: This value cannot be altered. **Invariant**: Must be an int > 0.""" return self._keycount @property def keys(self): """The list of keys that are currently held down. Using this attribute is much slower than the method `is_key_down`. You should use that method when you want to test a specific key. This attribute is primarily for debugging. **Immutable**: This value cannot be altered. **Invariant**: Must be a list of strings (possibly empty)""" return tuple(k for (k,v) in self._keystate.iteritems() if v) def __init__(self): """**Constructor**: Creates a new input handler This constructor does very little. It does not hook up the handler to the mouse or keyboard. That functionality happens behind the scenes with hidden methods. You should only use use the object provided in the `input` attribute of `GameApp`. See the class `GameApp` for more information.""" self._view = None self._touch = None self._keyboard = None self._touch_enabled = True self._keyboard_enabled = True self._keystate = {} self._keycount = 0 def is_key_down(self,key): """**Returns**: True if the key is currently held down. :param key: the key to test **Precondition**: Must be a string. The key is a string describing the key pressed. For example, to determine whether the right-arrow key is pressed, use the method call `input.is_key_down('right')`. Similarly the method call `input.is_key_down('w')` will indicate whether the W key is pressed. For a complete list of key names, see the `Kivy documentation <http://kivy.org/docs/_modules/kivy/core/window.html>`_. """ return key in self._keystate and self._keystate[key] def is_touch_down(self): """**Returns**: True if the mouse is currently held down. If this method returns True, the attribute `touch` is guaranteed to not be None.""" return not self._touch is None def _register(self,view): """Registers the view with this input handler; activating it. :param view: the view to register. **Precondition**: Must be a GView. The input handler can only have one view at a time. If there is an active view, it will unregister it first before registering the new one. """ self._view = view if self.touch_enabled: self._enable_touch() if self.keyboard_enabled: self._enable_keyboard() def _enable_touch(self): """Enables touch events for this input handler""" if self._view is None: return self._view.bind(on_touch_down=self._capture_touch) self._view.bind(on_touch_move=self._capture_touch) self._view.bind(on_touch_up=self._release_touch) def _disable_touch(self): """Disables touch events for this input handler""" if self._view is None: return self._view.unbind(on_touch_down=self._capture_touch) self._view.unbind(on_touch_move=self._capture_touch) self._view.unbind(on_touch_up=self._release_touch) self._touch = None def _enable_keyboard(self): """Enables keyboard events for this input handler""" if self._view is None: return from kivy.core.window import Window self._keyboard = Window.request_keyboard(self._disable_keyboard, self._view, 'text') self._keyboard.bind(on_key_down=self._capture_key) self._keyboard.bind(on_key_up=self._release_key) def _disable_keyboard(self): """Disables keyboard events for this input handler""" if self._view is None: return self._keyboard.unbind(on_key_down=self._capture_key) self._keyboard.unbind(on_key_up=self._release_key) self._keyboard = None self._keystate = {} self._keycount = 0 def _capture_key(self, keyboard, keycode, text, modifiers): """Captures a simple keypress and adds it to the key dictionary. :param keyboard: reference to the keyboard **Precondition**: Must be a Keyboard. :param keycode: the key pressed **Precondition**: Must be a pair of an int (keycode) and a string :param text: the text associated with the key **Precondition**: Must be a string :param modifiers: the modifiers associated with the press **Precondition**: Must be a list of key codes """ k = keycode[1] if not k in self._keystate or not self._keystate[k]: self._keycount += 1 self._keystate[k] = True return True def _release_key(self, keyboard, keycode): """Releases a simple keypress and removes it from the key dictionary. :param keyboard: reference to the keyboard **Precondition**: Must be a Keyboard. :param keycode: the key pressed **Precondition**: Must be a pair of an int (keycode) and a string """ self._keystate[keycode[1]] = False self._keycount -= 1 return True def _capture_touch(self,view,touch): """Captures a the current mouse position if button is pressed. :param view: reference to the view window **Precondition**: Must be a GView. :param touch: the information about the mouse press **Precondition**: Must be a TouchEvent """ self._touch = touch def _release_touch(self,view,touch): """Releases a the current mouse position from memory. :param view: reference to the view window **Precondition**: Must be a GView. :param touch: the information about the mouse release **Precondition**: Must be a TouchEvent """ self._touch = None class GView(FloatLayout): """Instances are a view class for a `GameApp` application. This is the class that you will use to draw shapes to the screen. Simply pass your `GObject` instances to the `draw` method. You must do this every animation frame, as the game is constantly clearing the window. **You should never construct an object of this class**. Creating a new instance of this class will not properly display it on the screen. Instead, you should only use the one provided in the `input` attribute of `GameApp`. See the class `GameApp` for more information. """ def __init__(self): """**Constructor**: Creates a new view for display This constructor does very little. It does not hook up the view to the game window. That functionality happens behind the scenes with hidden methods. You should only use use the object provided in the `view` attribute of `GameApp`. See the class `GameApp` for more information.""" FloatLayout.__init__(self) self._frame = InstructionGroup() self.bind(pos=self._reset) self.bind(size=self._reset) self._reset() def draw(self,cmd): """Draws the given Kivy graphics command to this view. :param cmd: the command to draw **Precondition**: Must be a Kivy graphics command You should never call this method, since you do not understand raw Kivy graphics commands. Instead, you should use the `draw` method in `GObject` instead.""" self._frame.add(cmd) def clear(self): """Clears the contents of the view. This method is called for you automatically at the start of the animation frame. That way, you are not drawing images on top of one another.""" self._frame.clear() def _reset(self,obj=None,value=None): """Resets the view canvas in response to a resizing event""" self.canvas.clear() self.canvas.add(Color(1,1,1)) self.canvas.add(Rectangle(pos=self.pos,size=self.size)) self.canvas.add(Scale(dp(1),dp(1),dp(1))) self.canvas.add(self._frame) s to `self.view.draw()`. """ @property def fps(self): """The number of frames-per-second to animate By default this value is 60 FPS. However, we cannot guarantee that the FPS is achievable. If you are having performance stuttering, you might want to drop this value to 30 FPS instead. **Invariant**: Must be an int or float > 0.""" return self._fps @fps.setter def fps(self,value): assert _is_num(value), 'value %s is not a number' % `value` assert value > 0, 'value %s is not positive' % `value` Clock.unschedule(self._refresh) self._fps = value Clock.schedule_interval(self._refresh,1.0/self._fps) @property def width(self): """The window width **Invariant**: Must be an int or float > 0.""" return self._gwidth @property def height(self): """The window height **Invariant**: Must be an int or float > 0.""" return self._gheight @property def view(self): """The Game view. Use the `draw` method in this attribute to display any `GObject` instance on the screen. See the class `GView` for more information. **Invariant**: Must be instance of GView.""" return self._view @property def input(self): """The Game input handler. Use this attribute to get information about the mouse and keyboard. See the class `GInput` for more information. **Invariant**: Must be instance of GInput.""" return self._input def __init__(self,**keywords): """**Constructor**: Creates, but does not start, a new game. :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. The primary user defined attributes are the window `width` and `height`. For example, to create a game that fits inside of a 400x400 window, the constructor Game(width=400,height=400) The game window will not show until you start the game. To start the game, use the method `run()`. **You will never call the constructor or `run` yourself. That is handled for you in the provided code.""" w = keywords['width'] if 'width' in keywords else 0.0 h = keywords['height'] if 'height' in keywords else 0.0 f = keywords['fps'] if 'fps' in keywords else 60.0 assert _is_num(w), 'width %s is not a number' % `w` assert _is_num(h), 'height %s is not a number' % `h` assert _is_num(f), 'fps %s is not a number' % `value` assert f > 0, 'fps %s is not positive' % `value` self._gwidth = w self._gheight = h self._fps = f Config.set('graphics', 'width', str(self.width)) Config.set('graphics', 'height', str(self.height)) kivy.app.App.__init__(self,**keywords) def build(self): """Initializes the graphics window. This is a Kivy reserved method. It is part of the Kivy application process. It should **never** be overridden.""" self._view = GView() self._view.size_hint = (1,1) self._input = GInput() self._input._register(self._view) return self.view def run(self): """Displays the game window and start the game. This is a Kivy reserved method. It is part of the Kivy application process. It should **never** be overridden.""" Clock.schedule_once(self._bootstrap,-1) kivy.app.App.run(self) def stop(self): """Closes the game window and exit Python. This is a Kivy reserved method. It is part of the Kivy application process. It should **never** be overridden.""" kivy.app.App.stop(self) sys.exit(0) def start(self): """Initializes the game state, creating a new game. This method is distinct from the built-in initializer __init__. This method is called once the game is running. You should use it to initialize any game specific attributes. **Never overridden the built-in method __init__**""" pass def update(self,dt): """Updates the state of the game one animation frame. :param dt: time in seconds since last update **Precondition**: a number (int or float) This method is called 60x a second (depending on the `fps`) to provide on-screen animation. Any code that moves objects or processes user input (keyboard or mouse) goes in this method. Think of this method as the body of the loop. You will need to add attributes that represent the current animation state, so that they can persist across animation frames. These attributes should be initialized in `start`. """ pass def draw(self): """Draws the game objects on the screen. Every single object that you draw will need to be an attribute of the `GameApp` class. This method should largely be a sequence of calls to `self.view.draw()`. """ pass def _bootstrap(self,dt): """Bootstraps the clock scheduler for the game.. This method is a callback-proxy for method `start`. It handles important issues behind the scenes, particularly with setting the FPS""" Clock.schedule_interval(self._refresh,1.0/self.fps) self.start() def _refresh(self,dt): """Processes a single animation frame. :param dt: time in seconds since last update **Precondition**: a number (int or float) This method a callback-proxy for the methods `update` and `draw`. It handles important issues behind the scenes, particularly with clearing the window.""" self.view.clear() self.update(dt) self.draw()
false
true
f72c596ca53720016e67120b1a4e92b4a9a60f51
2,775
py
Python
training/utils/utils.py
Tbarkin121/Tensegrity_IsaacGym
0b6b5227e76b18396862c242a4e8e743248844b3
[ "MIT" ]
317
2021-09-08T01:28:49.000Z
2022-03-31T07:52:36.000Z
training/utils/utils.py
Tbarkin121/Tensegrity_IsaacGym
0b6b5227e76b18396862c242a4e8e743248844b3
[ "MIT" ]
24
2021-11-05T14:15:47.000Z
2022-03-31T11:58:18.000Z
training/utils/utils.py
Tbarkin121/Tensegrity_IsaacGym
0b6b5227e76b18396862c242a4e8e743248844b3
[ "MIT" ]
58
2021-10-31T07:15:43.000Z
2022-03-29T14:51:02.000Z
# Copyright (c) 2018-2021, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # python import numpy as np import torch import random import os def set_np_formatting(): """ formats numpy print """ np.set_printoptions(edgeitems=30, infstr='inf', linewidth=4000, nanstr='nan', precision=2, suppress=False, threshold=10000, formatter=None) def set_seed(seed, torch_deterministic=False): """ set seed across modules """ if seed == -1 and torch_deterministic: seed = 42 elif seed == -1: seed = np.random.randint(0, 10000) print("Setting seed: {}".format(seed)) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) if torch_deterministic: # refer to https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.use_deterministic_algorithms(True) else: torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False return seed # EOF
39.084507
91
0.728649
import numpy as np import torch import random import os def set_np_formatting(): np.set_printoptions(edgeitems=30, infstr='inf', linewidth=4000, nanstr='nan', precision=2, suppress=False, threshold=10000, formatter=None) def set_seed(seed, torch_deterministic=False): if seed == -1 and torch_deterministic: seed = 42 elif seed == -1: seed = np.random.randint(0, 10000) print("Setting seed: {}".format(seed)) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) if torch_deterministic: S_WORKSPACE_CONFIG'] = ':4096:8' torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.use_deterministic_algorithms(True) else: torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False return seed
true
true
f72c59b6c86d8d1a0d95172b56d5bdce1315051e
32,056
py
Python
scripts/automation/trex_control_plane/interactive/trex/console/trex_console.py
klement/trex-core
b98e2e6d2b8c6caeb233ce36fcbc131ffc45e35e
[ "Apache-2.0" ]
1
2020-09-06T00:58:34.000Z
2020-09-06T00:58:34.000Z
scripts/automation/trex_control_plane/interactive/trex/console/trex_console.py
klement/trex-core
b98e2e6d2b8c6caeb233ce36fcbc131ffc45e35e
[ "Apache-2.0" ]
null
null
null
scripts/automation/trex_control_plane/interactive/trex/console/trex_console.py
klement/trex-core
b98e2e6d2b8c6caeb233ce36fcbc131ffc45e35e
[ "Apache-2.0" ]
1
2021-09-13T13:43:10.000Z
2021-09-13T13:43:10.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Dan Klein, Itay Marom Cisco Systems, Inc. Copyright (c) 2015-2015 Cisco Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import print_function import collections import subprocess import inspect import cmd import json import argparse import random import readline import string import os import sys import tty, termios from threading import Lock from functools import wraps, partial import threading import atexit import tempfile if __package__ == None: print("TRex console must be launched as a module") sys.exit(1) from ..stl.api import * from ..astf.api import * from ..common.trex_client import TRexClient from ..utils.text_opts import * from ..utils.common import user_input, get_current_user, set_window_always_on_top from ..utils import parsing_opts from .trex_capture import CaptureManager from .plugins_mngr import PluginsManager from . import trex_tui __version__ = "3.0" # readline.write_history_file can fail with IOError in Python2 def write_history_file(hist_file): hist_end = readline.get_current_history_length() hist_start = max(0, hist_end - readline.get_history_length()) with open(hist_file, 'w') as f: for i in range(hist_start, hist_end): f.write('%s\n' % readline.get_history_item(i + 1)) # console custom logger class ConsoleLogger(Logger): def __init__ (self): Logger.__init__(self) self.prompt_redraw = lambda: None self.tid = threading.current_thread().ident def _write (self, msg, newline = True): # if printed from another thread - handle it specifcially if threading.current_thread().ident != self.tid: self._write_async(msg, newline) else: self._write_sync(msg, newline) def _write_sync (self, msg, newline): if newline: print(msg) else: print(msg, end=' ') def _write_async (self, msg, newline): print('\n') self._write_sync(msg, newline) self.prompt_redraw() self._flush() def _flush (self): sys.stdout.flush() class TRexGeneralCmd(cmd.Cmd): def __init__(self, client_mode): cmd.Cmd.__init__(self) # configure history behaviour self._history_file_dir = "/tmp/trex/console/" self._history_file = self.get_history_file_full_path(client_mode) readline.set_history_length(100) # load history, if any self.load_console_history() atexit.register(self.save_console_history) def get_history_file_full_path(self, client_mode): return "{dir}{filename}_{mode}.hist".format(dir=self._history_file_dir, filename=self.get_console_identifier(), mode=client_mode) def load_console_history(self): if os.path.exists(self._history_file): readline.read_history_file(self._history_file) return def save_console_history(self): if not os.path.exists(self._history_file_dir): # make the directory available for every user try: original_umask = os.umask(0) os.makedirs(self._history_file_dir, mode = 0o777) finally: os.umask(original_umask) # os.mknod(self._history_file) try: write_history_file(self._history_file) except BaseException as e: print(bold('\nCould not save history file: %s\nError: %s\n' % (self._history_file, e))) def print_history (self): length = readline.get_current_history_length() for i in range(1, length + 1): cmd = readline.get_history_item(i) print("{:<5} {:}".format(i, cmd)) def get_history_item (self, index): length = readline.get_current_history_length() if index > length: print(format_text("please select an index between {0} and {1}".format(0, length))) return None return readline.get_history_item(index) def emptyline(self): """Called when an empty line is entered in response to the prompt. This overriding is such that when empty line is passed, **nothing happens**. """ return def completenames(self, text, *ignored): """ This overriding is such that a space is added to name completion. """ dotext = 'do_'+text return [a[3:]+' ' for a in self.get_names() if a.startswith(dotext)] # main console object class TRexConsole(TRexGeneralCmd): """Trex Console""" def __init__(self, client, verbose = False): # cmd lock is used to make sure background job # of the console is not done while the user excutes commands self.cmd_lock = Lock() self.client = client self.verbose = verbose TRexGeneralCmd.__init__(self, client.get_mode()) self.plugins_mngr = PluginsManager(self) self.intro = "\n-=TRex Console v{ver}=-\n".format(ver=__version__) self.intro += "\nType 'help' or '?' for supported actions\n" self.terminal = None self.tui = trex_tui.TrexTUI(self) self.cap_mngr = CaptureManager(client, self.cmd_lock) self.load_client_console_functions() self.postcmd(False, "") ################### internal section ######################## def verify_connected(f): @wraps(f) def wrap(*args): inst = args[0] func_name = f.__name__ if func_name.startswith("do_"): func_name = func_name[3:] if not inst.client.is_connected(): print(format_text("\n'{0}' cannot be executed on offline mode\n".format(func_name), 'bold')) return ret = f(*args) return ret return wrap def history_preserver(self, func, line): filename = self._push_history() try: func(line) finally: self._pop_history(filename) def load_client_console_functions (self): for cmd_name, cmd_func in self.client.get_console_methods().items(): # register the function and its help if cmd_func.preserve_history: f = partial(self.history_preserver, cmd_func) f.__doc__ = cmd_func.__doc__ f.name = cmd_func.name f.group = cmd_func.group setattr(self.__class__, 'do_' + cmd_name, f) else: setattr(self.__class__, 'do_' + cmd_name, cmd_func) setattr(self.__class__, 'help_' + cmd_name, lambda _, func = cmd_func: func('-h')) def load_client_plugin_functions (self, client, func_prefix): for cmd_name, cmd_func in client.get_plugin_methods().items(): cmd_name = func_prefix + cmd_name # register the function and its help if cmd_func.preserve_history: f = partial(self.history_preserver, cmd_func) f.__doc__ = cmd_func.__doc__ f.name = cmd_func.name f.group = cmd_func.group setattr(self.__class__, 'do_' + cmd_name, f) else: setattr(self.__class__, 'do_' + cmd_name, cmd_func) setattr(self.__class__, 'help_' + cmd_name, lambda _, func = cmd_func: func('-h')) def unload_client_plugin_functions (self, func_prefix): do_func_pre, help_func_pre = 'do_%s' % func_prefix, 'help_%s' % func_prefix for cmd_name, cmd_func in inspect.getmembers(self.__class__, predicate=inspect.ismethod): if cmd_name.startswith(do_func_pre) or cmd_name.startswith(help_func_pre): delattr(self.__class__, cmd_name) def generate_prompt (self, prefix = 'trex'): if not self.client.is_connected(): return "{0}(offline)>".format(prefix) elif not self.client.get_acquired_ports(): return "{0}(read-only)>".format(prefix) elif self.client.is_all_ports_acquired(): p = prefix # HACK service_ports = self.client.get_service_enabled_ports() filtered_ports = self.client.get_service_filtered_ports() if (self.client.get_mode() == "STL" or self.client.get_mode() == "ASTF") and (service_ports or filtered_ports): if filtered_ports == self.client.get_acquired_ports(): p += '(service-filtered)' elif service_ports == self.client.get_acquired_ports(): p += '(service)' else: p += '(service: {0})'.format(', '.join(map(str, service_ports))) return "{0}>".format(p) else: return "{0} (ports: {1})>".format(prefix, ', '.join(map(str, self.client.get_acquired_ports()))) def prompt_redraw (self): self.postcmd(False, "") sys.stdout.write("\n" + self.prompt + readline.get_line_buffer()) sys.stdout.flush() def get_console_identifier(self): conn = self.client.get_connection_info() return "%s_%s_%s_%s" % (get_current_user(), conn['server'], conn['sync_port'], conn['async_port']) def register_main_console_methods(self): main_names = set(self.trex_console.get_names()).difference(set(dir(self.__class__))) for name in main_names: for prefix in 'do_', 'help_', 'complete_': if name.startswith(prefix): self.__dict__[name] = getattr(self.trex_console, name) def precmd(self, line): lines = line.split(';') try: self.cmd_lock.acquire() for line in lines: stop = self.onecmd(line) stop = self.postcmd(stop, line) if stop: return "quit" return "" except KeyboardInterrupt: print(bold('Interrupted by a keyboard signal (probably ctrl + c)')) except TRexError as e: print(e) finally: self.cmd_lock.release() return '' def postcmd(self, stop, line): self.prompt = self.generate_prompt(prefix = 'trex') return stop def default(self, line): print("'{0}' is an unrecognized command. type 'help' or '?' for a list\n".format(line)) @staticmethod def tree_autocomplete(text): dir = os.path.dirname(text) if dir: path = dir else: path = "." start_string = os.path.basename(text) targets = [] for x in os.listdir(path): if x.startswith(start_string): y = os.path.join(path, x) if os.path.isfile(y): targets.append(x + ' ') elif os.path.isdir(y): targets.append(x + '/') return targets ####################### shell commands ####################### # set verbose on / off def do_verbose(self, line): '''Shows or set verbose mode\n''' if line == "": print("\nverbose is " + ("on\n" if self.verbose else "off\n")) elif line == "on": self.verbose = True self.client.set_verbose("debug") print(format_text("\nverbose set to on\n", 'green', 'bold')) elif line == "off": self.verbose = False self.client.set_verbose("info") print(format_text("\nverbose set to off\n", 'green', 'bold')) else: print(format_text("\nplease specify 'on' or 'off'\n", 'bold')) # show history def help_history (self): self.do_history("-h") def do_shell (self, line): self.do_history(line) def help_plugins(self): self.do_plugins('-h') @verify_connected def do_capture (self, line): '''Manage PCAP captures''' self.cap_mngr.parse_line(line) def help_capture (self): self.do_capture("-h") # save current history to a temp file def _push_history(self): tmp_file = tempfile.NamedTemporaryFile() write_history_file(tmp_file.name) readline.clear_history() return tmp_file # restore history from a temp file def _pop_history(self, tmp_file): readline.clear_history() readline.read_history_file(tmp_file.name) tmp_file.close() def do_debug(self, line): '''Internal debugger for development. Requires IPython module installed ''' parser = parsing_opts.gen_parser(self.client, "debug", self.do_debug.__doc__) opts = parser.parse_args(line.split()) try: from IPython.terminal.ipapp import load_default_config from IPython.terminal.embed import InteractiveShellEmbed from IPython import embed except ImportError: embed = None if not embed: try: import code except ImportError: self.client.logger.info(format_text("\n*** 'IPython' and 'code' library are not available ***\n", 'bold')) return auto_completer = readline.get_completer() console_history_file = self._push_history() client = self.client descr = 'IPython' if embed else "'code' library" self.client.logger.info(format_text("\n*** Starting Python shell (%s)... use 'client' as client object, Ctrl + D to exit ***\n" % descr, 'bold')) try: if embed: cfg = load_default_config() cfg['TerminalInteractiveShell']['confirm_exit'] = False embed(config = cfg, display_banner = False) #InteractiveShellEmbed.clear_instance() else: ns = {} ns.update(globals()) ns.update(locals()) code.InteractiveConsole(ns).interact('') finally: readline.set_completer(auto_completer) self._pop_history(console_history_file) self.client.logger.info(format_text("\n*** Leaving Python shell ***\n")) def do_history (self, line): '''Manage the command history\n''' item = parsing_opts.ArgumentPack(['item'], {"nargs": '?', 'metavar': 'item', 'type': parsing_opts.check_negative, 'help': "an history item index", 'default': 0}) parser = parsing_opts.gen_parser(self.client, "history", self.do_history.__doc__, item) try: opts = parser.parse_args(line.split()) except TRexError: return if opts.item == 0: self.print_history() else: cmd = self.get_history_item(opts.item) if cmd == None: return print("Executing '{0}'".format(cmd)) return self.onecmd(cmd) def do_plugins(self, line): '''Show / load / use plugins\n''' self.plugins_mngr.do_plugins(line) def complete_plugins(self, text, line, start_index, end_index): return self.plugins_mngr.complete_plugins(text, line, start_index, end_index) def complete_emu_load_profile(self, text, line, start_index, end_index): return self.complete_start(text, line, start_index, end_index) ############### connect def do_connect (self, line): '''Connects to the server and acquire ports\n''' self.client.connect_line(line) def do_disconnect (self, line): '''Disconnect from the server\n''' # stop any monitors before disconnecting self.plugins_mngr._unload_plugin() self.cap_mngr.stop() self.client.disconnect_line(line) ############### start def complete_start(self, text, line, begidx, endidx): s = line.split() l = len(s) file_flags = parsing_opts.get_flags(parsing_opts.FILE_PATH) if (l > 1) and (s[l - 1] in file_flags): return TRexConsole.tree_autocomplete("") if (l > 2) and (s[l - 2] in file_flags): return TRexConsole.tree_autocomplete(s[l - 1]) complete_push = complete_start complete_hello = complete_start def complete_profile(self, text, line, begidx, endidx): return self.complete_start(text,line, begidx, endidx) # tui @verify_connected def do_tui (self, line): '''Shows a graphical console\n''' parser = parsing_opts.gen_parser(self.client, "tui", self.do_tui.__doc__, parsing_opts.XTERM, parsing_opts.LOCKED) try: opts = parser.parse_args(line.split()) except TRexError: return if opts.xterm: if not os.path.exists('/usr/bin/xterm'): print(format_text("XTERM does not exists on this machine", 'bold')) return info = self.client.get_connection_info() exe = './trex-console --top -t -q -s {0} -p {1} --async_port {2}'.format(info['server'], info['sync_port'], info['async_port']) cmd = ['/usr/bin/xterm', '-geometry', '{0}x{1}'.format(self.tui.MIN_COLS, self.tui.MIN_ROWS), '-sl', '0', '-title', 'trex_tui', '-e', exe] # detach child self.terminal = subprocess.Popen(cmd, preexec_fn = os.setpgrp) return try: with self.client.logger.supress(verbose = 'none'): self.tui.show(self.client, self.save_console_history, locked = opts.locked) except self.tui.ScreenSizeException as e: print(format_text(str(e) + "\n", 'bold')) def help_tui (self): do_tui("-h") # quit function def do_quit(self, line): '''Exit the console\n''' return True def do_help (self, line): '''Shows This Help Screen\n''' if line: try: func = getattr(self, 'help_' + line) except AttributeError: try: doc = getattr(self, 'do_' + line).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (line,))) return func() return cmds = [x[3:] for x in self.get_names() if x.startswith("do_")] hidden = ['EOF', 'q', 'exit', 'h', 'shell'] categories = collections.defaultdict(list) for cmd in cmds: if cmd in hidden: continue category = getattr(getattr(self, 'do_' + cmd), 'group', 'basic') categories[category].append(cmd) # basic commands if 'basic' in categories: self._help_cmds('Console Commands', categories['basic']) # common if 'common' in categories: self._help_cmds('Common Commands', categories['common']) if 'STL' in categories: self._help_cmds('Stateless Commands', categories['STL']) if 'ASTF' in categories: self._help_cmds('Advanced Stateful Commands', categories['ASTF']) if 'emu' in categories: self._help_cmds('Emulation Commands', categories['emu']) def _help_cmds (self, title, cmds): print(format_text("\n{0}:\n".format(title), 'bold', 'underline')) for cmd in cmds: try: doc = getattr(self, 'do_' + cmd).__doc__ if doc: help = str(doc) else: help = "*** Undocumented Function ***\n" except AttributeError: help = "*** Undocumented Function ***\n" l=help.splitlines() print("{:<30} {:<30}".format(cmd + " - ",l[0] )) # a custorm cmdloop wrapper def start(self): try: while True: try: self.cmdloop() break except KeyboardInterrupt as e: if not readline.get_line_buffer(): raise KeyboardInterrupt else: print("") self.intro = None continue finally: # capture manager is not presistent - kill it before going out self.plugins_mngr._unload_plugin() self.cap_mngr.stop() if self.terminal: self.terminal.kill() # aliases do_exit = do_EOF = do_q = do_quit do_h = do_history # run a script of commands def run_script_file(filename, client): client.logger.info(format_text("\nRunning script file '{0}'...".format(filename), 'bold')) with open(filename) as f: script_lines = f.readlines() # register all the commands cmd_table = {} for cmd_name, cmd_func in client.get_console_methods().items(): cmd_table[cmd_name] = cmd_func for index, line in enumerate(script_lines, start = 1): line = line.strip() if line == "": continue if line.startswith("#"): continue sp = line.split(' ', 1) cmd = sp[0] if len(sp) == 2: args = sp[1] else: args = "" client.logger.info(format_text("Executing line {0} : '{1}'\n".format(index, line))) if cmd not in cmd_table: client.logger.error(format_text("Unknown command '%s', available commands are:\n%s" % (cmd, '\n'.join(sorted(cmd_table.keys()))), 'bold')) return False rc = cmd_table[cmd](args) if isinstance(rc, RC) and not rc: return False client.logger.info(format_text("\n[Done]", 'bold')) return True # def is_valid_file(filename): if not os.path.isfile(filename): raise argparse.ArgumentTypeError("The file '%s' does not exist" % filename) return filename def setParserOptions(): parser = argparse.ArgumentParser(prog="trex_console.py") parser.add_argument("-s", "--server", help = "TRex Server [default is localhost]", default = "localhost", type = str) parser.add_argument("-p", "--port", help = "TRex Server Port [default is 4501]\n", default = 4501, type = int) parser.add_argument("--async_port", help = "TRex ASync Publisher Port [default is 4500]\n", default = 4500, dest='pub', type = int) parser.add_argument("-u", "--user", help = "User Name [default is currently logged in user]\n", default = get_current_user(), type = str) parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Switch ON verbose option. Default is: OFF.", default = False) parser.add_argument( "--timeout", dest="timeout", help="timeout for ZMQ connection, the default is 3 sec, higher value will make it more resilient to Firewalls", default = False,type = int) group = parser.add_mutually_exclusive_group() group.add_argument("-a", "--acquire", dest="acquire", nargs = '+', type = int, help="Acquire ports on connect. default is all available ports", default = None) group.add_argument("-r", "--readonly", dest="readonly", action="store_true", help="Starts console in a read only mode", default = False) parser.add_argument("--emu", action="store_true", help="Run emulation client on startup", default = False) parser.add_argument("--emu-server", help="Emulation client server, default is TRex server address") parser.add_argument("-f", "--force", dest="force", action="store_true", help="Force acquire the requested ports", default = False) parser.add_argument("--batch", dest="batch", nargs = 1, type = is_valid_file, help = "Run the console in a batch mode with file", default = None) parser.add_argument("-t", "--tui", dest="tui", action="store_true", help="Starts with TUI mode", default = False) parser.add_argument("-x", "--xtui", dest="xtui", action="store_true", help="Starts with XTERM TUI mode", default = False) parser.add_argument("--top", dest="top", action="store_true", help="Set the window as always on top", default = False) parser.add_argument("-q", "--quiet", dest="quiet", action="store_true", help="Starts with all outputs suppressed", default = False) return parser # a simple info printed on log on def show_intro (logger, c): modes = {'STL': 'Stateless', 'ASTF': 'Advanced Stateful'} x = c.get_server_system_info() ver = c.get_server_version().get('version', 'N/A') mode = c.get_server_version().get('mode', 'N/A') # find out which NICs the server has port_types = {} for port in x['ports']: if 'supp_speeds' in port and port['supp_speeds']: speed = max(port['supp_speeds']) // 1000 else: speed = c.ports[port['index']].get_speed_gbps() key = (speed, port.get('description', port['driver'])) if key not in port_types: port_types[key] = 0 port_types[key] += 1 port_line = '' for k, v in port_types.items(): port_line += "{0} x {1}Gbps @ {2}\t".format(v, k[0], k[1]) logger.info(format_text("\nServer Info:\n", 'underline')) logger.info("Server version: {:>}".format(format_text(ver + ' @ ' + mode, 'bold'))) logger.info("Server mode: {:>}".format(format_text(modes.get(mode, 'N/A'), 'bold'))) logger.info("Server CPU: {:>}".format(format_text("{:>} x {:>}".format(x.get('dp_core_count'), x.get('core_type')), 'bold'))) logger.info("Ports count: {:>}".format(format_text(port_line, 'bold'))) def probe_server_mode (options): # first we create a 'dummy' client and probe the server client = TRexClient(username = options.user, server = options.server, sync_port = options.port, async_port = options.pub, logger = ConsoleLogger(), verbose_level = 'error') return client.probe_server()['mode'] def run_console(client, logger, options): # console try: show_intro(logger, client) # a script mode if options.batch: cont = run_script_file(options.batch[0], client) if not cont: return console = TRexConsole(client, options.verbose) # run emu if needed console.emu_server = options.emu_server if options.emu: console.do_plugins('load emu') logger.prompt_redraw = console.prompt_redraw # TUI if options.tui: console.do_tui("-x" if options.xtui else "-l") else: console.start() except KeyboardInterrupt as e: print("\n\n*** Caught Ctrl + C... Exiting...\n\n") finally: with client.logger.supress(): client.disconnect(stop_traffic = False) def main(): parser = setParserOptions() options = parser.parse_args() if options.emu_server is None: options.emu_server = options.server if options.xtui: options.tui = True # always on top if options.top: set_window_always_on_top('trex_tui') # verbose if options.quiet: verbose_level = "none" elif options.verbose: verbose_level = "debug" else: verbose_level = "info" sync_timeout = None async_timeout = None if options.timeout: sync_timeout = options.timeout async_timeout = options.timeout logger = ConsoleLogger() # determine server mode try: mode = probe_server_mode(options) except TRexError as e: logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold')) return acquire_options = {'force': options.force} if mode == 'STL': acquire_options['ports'] = options.acquire client = STLClient(username = options.user, server = options.server, sync_port = options.port, async_port = options.pub, logger = logger, verbose_level = verbose_level, sync_timeout = sync_timeout, async_timeout = async_timeout) elif mode == 'ASTF': if options.acquire: logger.critical('Acquire option is not available in ASTF. Must acquire all ports.') return client = ASTFClient(username = options.user, server = options.server, sync_port = options.port, async_port = options.pub, logger = logger, verbose_level = verbose_level, sync_timeout = sync_timeout, async_timeout = async_timeout) else: logger.critical("Unknown server mode: '{0}'".format(mode)) return try: client.connect() except TRexError as e: logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold')) return # TUI or no acquire will give us READ ONLY mode if not options.tui and not options.readonly: try: # acquire ports client.acquire(**acquire_options) except TRexError as e: logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold')) logger.error("\n*** Failed to acquire all required ports ***\n") return if options.readonly: logger.info(format_text("\nRead only mode - only few commands will be available", 'bold')) run_console(client, logger, options) if __name__ == '__main__': main()
32.088088
153
0.551816
from __future__ import print_function import collections import subprocess import inspect import cmd import json import argparse import random import readline import string import os import sys import tty, termios from threading import Lock from functools import wraps, partial import threading import atexit import tempfile if __package__ == None: print("TRex console must be launched as a module") sys.exit(1) from ..stl.api import * from ..astf.api import * from ..common.trex_client import TRexClient from ..utils.text_opts import * from ..utils.common import user_input, get_current_user, set_window_always_on_top from ..utils import parsing_opts from .trex_capture import CaptureManager from .plugins_mngr import PluginsManager from . import trex_tui __version__ = "3.0" def write_history_file(hist_file): hist_end = readline.get_current_history_length() hist_start = max(0, hist_end - readline.get_history_length()) with open(hist_file, 'w') as f: for i in range(hist_start, hist_end): f.write('%s\n' % readline.get_history_item(i + 1)) class ConsoleLogger(Logger): def __init__ (self): Logger.__init__(self) self.prompt_redraw = lambda: None self.tid = threading.current_thread().ident def _write (self, msg, newline = True): if threading.current_thread().ident != self.tid: self._write_async(msg, newline) else: self._write_sync(msg, newline) def _write_sync (self, msg, newline): if newline: print(msg) else: print(msg, end=' ') def _write_async (self, msg, newline): print('\n') self._write_sync(msg, newline) self.prompt_redraw() self._flush() def _flush (self): sys.stdout.flush() class TRexGeneralCmd(cmd.Cmd): def __init__(self, client_mode): cmd.Cmd.__init__(self) self._history_file_dir = "/tmp/trex/console/" self._history_file = self.get_history_file_full_path(client_mode) readline.set_history_length(100) self.load_console_history() atexit.register(self.save_console_history) def get_history_file_full_path(self, client_mode): return "{dir}{filename}_{mode}.hist".format(dir=self._history_file_dir, filename=self.get_console_identifier(), mode=client_mode) def load_console_history(self): if os.path.exists(self._history_file): readline.read_history_file(self._history_file) return def save_console_history(self): if not os.path.exists(self._history_file_dir): try: original_umask = os.umask(0) os.makedirs(self._history_file_dir, mode = 0o777) finally: os.umask(original_umask) try: write_history_file(self._history_file) except BaseException as e: print(bold('\nCould not save history file: %s\nError: %s\n' % (self._history_file, e))) def print_history (self): length = readline.get_current_history_length() for i in range(1, length + 1): cmd = readline.get_history_item(i) print("{:<5} {:}".format(i, cmd)) def get_history_item (self, index): length = readline.get_current_history_length() if index > length: print(format_text("please select an index between {0} and {1}".format(0, length))) return None return readline.get_history_item(index) def emptyline(self): return def completenames(self, text, *ignored): dotext = 'do_'+text return [a[3:]+' ' for a in self.get_names() if a.startswith(dotext)] class TRexConsole(TRexGeneralCmd): def __init__(self, client, verbose = False): self.cmd_lock = Lock() self.client = client self.verbose = verbose TRexGeneralCmd.__init__(self, client.get_mode()) self.plugins_mngr = PluginsManager(self) self.intro = "\n-=TRex Console v{ver}=-\n".format(ver=__version__) self.intro += "\nType 'help' or '?' for supported actions\n" self.terminal = None self.tui = trex_tui.TrexTUI(self) self.cap_mngr = CaptureManager(client, self.cmd_lock) self.load_client_console_functions() self.postcmd(False, "") help_' + cmd_name, lambda _, func = cmd_func: func('-h')) def load_client_plugin_functions (self, client, func_prefix): for cmd_name, cmd_func in client.get_plugin_methods().items(): cmd_name = func_prefix + cmd_name if cmd_func.preserve_history: f = partial(self.history_preserver, cmd_func) f.__doc__ = cmd_func.__doc__ f.name = cmd_func.name f.group = cmd_func.group setattr(self.__class__, 'do_' + cmd_name, f) else: setattr(self.__class__, 'do_' + cmd_name, cmd_func) setattr(self.__class__, 'help_' + cmd_name, lambda _, func = cmd_func: func('-h')) def unload_client_plugin_functions (self, func_prefix): do_func_pre, help_func_pre = 'do_%s' % func_prefix, 'help_%s' % func_prefix for cmd_name, cmd_func in inspect.getmembers(self.__class__, predicate=inspect.ismethod): if cmd_name.startswith(do_func_pre) or cmd_name.startswith(help_func_pre): delattr(self.__class__, cmd_name) def generate_prompt (self, prefix = 'trex'): if not self.client.is_connected(): return "{0}(offline)>".format(prefix) elif not self.client.get_acquired_ports(): return "{0}(read-only)>".format(prefix) elif self.client.is_all_ports_acquired(): p = prefix service_ports = self.client.get_service_enabled_ports() filtered_ports = self.client.get_service_filtered_ports() if (self.client.get_mode() == "STL" or self.client.get_mode() == "ASTF") and (service_ports or filtered_ports): if filtered_ports == self.client.get_acquired_ports(): p += '(service-filtered)' elif service_ports == self.client.get_acquired_ports(): p += '(service)' else: p += '(service: {0})'.format(', '.join(map(str, service_ports))) return "{0}>".format(p) else: return "{0} (ports: {1})>".format(prefix, ', '.join(map(str, self.client.get_acquired_ports()))) def prompt_redraw (self): self.postcmd(False, "") sys.stdout.write("\n" + self.prompt + readline.get_line_buffer()) sys.stdout.flush() def get_console_identifier(self): conn = self.client.get_connection_info() return "%s_%s_%s_%s" % (get_current_user(), conn['server'], conn['sync_port'], conn['async_port']) def register_main_console_methods(self): main_names = set(self.trex_console.get_names()).difference(set(dir(self.__class__))) for name in main_names: for prefix in 'do_', 'help_', 'complete_': if name.startswith(prefix): self.__dict__[name] = getattr(self.trex_console, name) def precmd(self, line): lines = line.split(';') try: self.cmd_lock.acquire() for line in lines: stop = self.onecmd(line) stop = self.postcmd(stop, line) if stop: return "quit" return "" except KeyboardInterrupt: print(bold('Interrupted by a keyboard signal (probably ctrl + c)')) except TRexError as e: print(e) finally: self.cmd_lock.release() return '' def postcmd(self, stop, line): self.prompt = self.generate_prompt(prefix = 'trex') return stop def default(self, line): print("'{0}' is an unrecognized command. type 'help' or '?' for a list\n".format(line)) @staticmethod def tree_autocomplete(text): dir = os.path.dirname(text) if dir: path = dir else: path = "." start_string = os.path.basename(text) targets = [] for x in os.listdir(path): if x.startswith(start_string): y = os.path.join(path, x) if os.path.isfile(y): targets.append(x + ' ') elif os.path.isdir(y): targets.append(x + '/') return targets "debug", self.do_debug.__doc__) opts = parser.parse_args(line.split()) try: from IPython.terminal.ipapp import load_default_config from IPython.terminal.embed import InteractiveShellEmbed from IPython import embed except ImportError: embed = None if not embed: try: import code except ImportError: self.client.logger.info(format_text("\n*** 'IPython' and 'code' library are not available ***\n", 'bold')) return auto_completer = readline.get_completer() console_history_file = self._push_history() client = self.client descr = 'IPython' if embed else "'code' library" self.client.logger.info(format_text("\n*** Starting Python shell (%s)... use 'client' as client object, Ctrl + D to exit ***\n" % descr, 'bold')) try: if embed: cfg = load_default_config() cfg['TerminalInteractiveShell']['confirm_exit'] = False embed(config = cfg, display_banner = False) else: ns = {} ns.update(globals()) ns.update(locals()) code.InteractiveConsole(ns).interact('') finally: readline.set_completer(auto_completer) self._pop_history(console_history_file) self.client.logger.info(format_text("\n*** Leaving Python shell ***\n")) def do_history (self, line): item = parsing_opts.ArgumentPack(['item'], {"nargs": '?', 'metavar': 'item', 'type': parsing_opts.check_negative, 'help': "an history item index", 'default': 0}) parser = parsing_opts.gen_parser(self.client, "history", self.do_history.__doc__, item) try: opts = parser.parse_args(line.split()) except TRexError: return if opts.item == 0: self.print_history() else: cmd = self.get_history_item(opts.item) if cmd == None: return print("Executing '{0}'".format(cmd)) return self.onecmd(cmd) def do_plugins(self, line): self.plugins_mngr.do_plugins(line) def complete_plugins(self, text, line, start_index, end_index): return self.plugins_mngr.complete_plugins(text, line, start_index, end_index) def complete_emu_load_profile(self, text, line, start_index, end_index): return self.complete_start(text, line, start_index, end_index) .client.disconnect_line(line) 1) and (s[l - 1] in file_flags): return TRexConsole.tree_autocomplete("") if (l > 2) and (s[l - 2] in file_flags): return TRexConsole.tree_autocomplete(s[l - 1]) complete_push = complete_start complete_hello = complete_start def complete_profile(self, text, line, begidx, endidx): return self.complete_start(text,line, begidx, endidx) @verify_connected def do_tui (self, line): parser = parsing_opts.gen_parser(self.client, "tui", self.do_tui.__doc__, parsing_opts.XTERM, parsing_opts.LOCKED) try: opts = parser.parse_args(line.split()) except TRexError: return if opts.xterm: if not os.path.exists('/usr/bin/xterm'): print(format_text("XTERM does not exists on this machine", 'bold')) return info = self.client.get_connection_info() exe = './trex-console --top -t -q -s {0} -p {1} --async_port {2}'.format(info['server'], info['sync_port'], info['async_port']) cmd = ['/usr/bin/xterm', '-geometry', '{0}x{1}'.format(self.tui.MIN_COLS, self.tui.MIN_ROWS), '-sl', '0', '-title', 'trex_tui', '-e', exe] self.terminal = subprocess.Popen(cmd, preexec_fn = os.setpgrp) return try: with self.client.logger.supress(verbose = 'none'): self.tui.show(self.client, self.save_console_history, locked = opts.locked) except self.tui.ScreenSizeException as e: print(format_text(str(e) + "\n", 'bold')) def help_tui (self): do_tui("-h") def do_quit(self, line): return True def do_help (self, line): if line: try: func = getattr(self, 'help_' + line) except AttributeError: try: doc = getattr(self, 'do_' + line).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (line,))) return func() return cmds = [x[3:] for x in self.get_names() if x.startswith("do_")] hidden = ['EOF', 'q', 'exit', 'h', 'shell'] categories = collections.defaultdict(list) for cmd in cmds: if cmd in hidden: continue category = getattr(getattr(self, 'do_' + cmd), 'group', 'basic') categories[category].append(cmd) if 'basic' in categories: self._help_cmds('Console Commands', categories['basic']) if 'common' in categories: self._help_cmds('Common Commands', categories['common']) if 'STL' in categories: self._help_cmds('Stateless Commands', categories['STL']) if 'ASTF' in categories: self._help_cmds('Advanced Stateful Commands', categories['ASTF']) if 'emu' in categories: self._help_cmds('Emulation Commands', categories['emu']) def _help_cmds (self, title, cmds): print(format_text("\n{0}:\n".format(title), 'bold', 'underline')) for cmd in cmds: try: doc = getattr(self, 'do_' + cmd).__doc__ if doc: help = str(doc) else: help = "*** Undocumented Function ***\n" except AttributeError: help = "*** Undocumented Function ***\n" l=help.splitlines() print("{:<30} {:<30}".format(cmd + " - ",l[0] )) def start(self): try: while True: try: self.cmdloop() break except KeyboardInterrupt as e: if not readline.get_line_buffer(): raise KeyboardInterrupt else: print("") self.intro = None continue finally: self.plugins_mngr._unload_plugin() self.cap_mngr.stop() if self.terminal: self.terminal.kill() do_exit = do_EOF = do_q = do_quit do_h = do_history def run_script_file(filename, client): client.logger.info(format_text("\nRunning script file '{0}'...".format(filename), 'bold')) with open(filename) as f: script_lines = f.readlines() cmd_table = {} for cmd_name, cmd_func in client.get_console_methods().items(): cmd_table[cmd_name] = cmd_func for index, line in enumerate(script_lines, start = 1): line = line.strip() if line == "": continue if line.startswith("#"): continue sp = line.split(' ', 1) cmd = sp[0] if len(sp) == 2: args = sp[1] else: args = "" client.logger.info(format_text("Executing line {0} : '{1}'\n".format(index, line))) if cmd not in cmd_table: client.logger.error(format_text("Unknown command '%s', available commands are:\n%s" % (cmd, '\n'.join(sorted(cmd_table.keys()))), 'bold')) return False rc = cmd_table[cmd](args) if isinstance(rc, RC) and not rc: return False client.logger.info(format_text("\n[Done]", 'bold')) return True def is_valid_file(filename): if not os.path.isfile(filename): raise argparse.ArgumentTypeError("The file '%s' does not exist" % filename) return filename def setParserOptions(): parser = argparse.ArgumentParser(prog="trex_console.py") parser.add_argument("-s", "--server", help = "TRex Server [default is localhost]", default = "localhost", type = str) parser.add_argument("-p", "--port", help = "TRex Server Port [default is 4501]\n", default = 4501, type = int) parser.add_argument("--async_port", help = "TRex ASync Publisher Port [default is 4500]\n", default = 4500, dest='pub', type = int) parser.add_argument("-u", "--user", help = "User Name [default is currently logged in user]\n", default = get_current_user(), type = str) parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Switch ON verbose option. Default is: OFF.", default = False) parser.add_argument( "--timeout", dest="timeout", help="timeout for ZMQ connection, the default is 3 sec, higher value will make it more resilient to Firewalls", default = False,type = int) group = parser.add_mutually_exclusive_group() group.add_argument("-a", "--acquire", dest="acquire", nargs = '+', type = int, help="Acquire ports on connect. default is all available ports", default = None) group.add_argument("-r", "--readonly", dest="readonly", action="store_true", help="Starts console in a read only mode", default = False) parser.add_argument("--emu", action="store_true", help="Run emulation client on startup", default = False) parser.add_argument("--emu-server", help="Emulation client server, default is TRex server address") parser.add_argument("-f", "--force", dest="force", action="store_true", help="Force acquire the requested ports", default = False) parser.add_argument("--batch", dest="batch", nargs = 1, type = is_valid_file, help = "Run the console in a batch mode with file", default = None) parser.add_argument("-t", "--tui", dest="tui", action="store_true", help="Starts with TUI mode", default = False) parser.add_argument("-x", "--xtui", dest="xtui", action="store_true", help="Starts with XTERM TUI mode", default = False) parser.add_argument("--top", dest="top", action="store_true", help="Set the window as always on top", default = False) parser.add_argument("-q", "--quiet", dest="quiet", action="store_true", help="Starts with all outputs suppressed", default = False) return parser def show_intro (logger, c): modes = {'STL': 'Stateless', 'ASTF': 'Advanced Stateful'} x = c.get_server_system_info() ver = c.get_server_version().get('version', 'N/A') mode = c.get_server_version().get('mode', 'N/A') port_types = {} for port in x['ports']: if 'supp_speeds' in port and port['supp_speeds']: speed = max(port['supp_speeds']) // 1000 else: speed = c.ports[port['index']].get_speed_gbps() key = (speed, port.get('description', port['driver'])) if key not in port_types: port_types[key] = 0 port_types[key] += 1 port_line = '' for k, v in port_types.items(): port_line += "{0} x {1}Gbps @ {2}\t".format(v, k[0], k[1]) logger.info(format_text("\nServer Info:\n", 'underline')) logger.info("Server version: {:>}".format(format_text(ver + ' @ ' + mode, 'bold'))) logger.info("Server mode: {:>}".format(format_text(modes.get(mode, 'N/A'), 'bold'))) logger.info("Server CPU: {:>}".format(format_text("{:>} x {:>}".format(x.get('dp_core_count'), x.get('core_type')), 'bold'))) logger.info("Ports count: {:>}".format(format_text(port_line, 'bold'))) def probe_server_mode (options): client = TRexClient(username = options.user, server = options.server, sync_port = options.port, async_port = options.pub, logger = ConsoleLogger(), verbose_level = 'error') return client.probe_server()['mode'] def run_console(client, logger, options): try: show_intro(logger, client) if options.batch: cont = run_script_file(options.batch[0], client) if not cont: return console = TRexConsole(client, options.verbose) console.emu_server = options.emu_server if options.emu: console.do_plugins('load emu') logger.prompt_redraw = console.prompt_redraw if options.tui: console.do_tui("-x" if options.xtui else "-l") else: console.start() except KeyboardInterrupt as e: print("\n\n*** Caught Ctrl + C... Exiting...\n\n") finally: with client.logger.supress(): client.disconnect(stop_traffic = False) def main(): parser = setParserOptions() options = parser.parse_args() if options.emu_server is None: options.emu_server = options.server if options.xtui: options.tui = True if options.top: set_window_always_on_top('trex_tui') if options.quiet: verbose_level = "none" elif options.verbose: verbose_level = "debug" else: verbose_level = "info" sync_timeout = None async_timeout = None if options.timeout: sync_timeout = options.timeout async_timeout = options.timeout logger = ConsoleLogger() try: mode = probe_server_mode(options) except TRexError as e: logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold')) return acquire_options = {'force': options.force} if mode == 'STL': acquire_options['ports'] = options.acquire client = STLClient(username = options.user, server = options.server, sync_port = options.port, async_port = options.pub, logger = logger, verbose_level = verbose_level, sync_timeout = sync_timeout, async_timeout = async_timeout) elif mode == 'ASTF': if options.acquire: logger.critical('Acquire option is not available in ASTF. Must acquire all ports.') return client = ASTFClient(username = options.user, server = options.server, sync_port = options.port, async_port = options.pub, logger = logger, verbose_level = verbose_level, sync_timeout = sync_timeout, async_timeout = async_timeout) else: logger.critical("Unknown server mode: '{0}'".format(mode)) return try: client.connect() except TRexError as e: logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold')) return if not options.tui and not options.readonly: try: client.acquire(**acquire_options) except TRexError as e: logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold')) logger.error("\n*** Failed to acquire all required ports ***\n") return if options.readonly: logger.info(format_text("\nRead only mode - only few commands will be available", 'bold')) run_console(client, logger, options) if __name__ == '__main__': main()
true
true
f72c59dd8ce767d14399213927b2439b6c5d6359
5,582
bzl
Python
external_plugin_deps.bzl
davido/plugins_saml
a876ef94a1a2988882bca9665356dd90628a828e
[ "Apache-2.0" ]
null
null
null
external_plugin_deps.bzl
davido/plugins_saml
a876ef94a1a2988882bca9665356dd90628a828e
[ "Apache-2.0" ]
null
null
null
external_plugin_deps.bzl
davido/plugins_saml
a876ef94a1a2988882bca9665356dd90628a828e
[ "Apache-2.0" ]
null
null
null
load("//tools/bzl:maven_jar.bzl", "maven_jar") SHIBBOLETH = "https://build.shibboleth.net/nexus/content/repositories/releases/" OPENSAML_VERSION = "3.4.3" PAC4J_VERSION = "3.8.0" def external_plugin_deps(): # Transitive dependency of velocity maven_jar( name = "commons-collections", artifact = "commons-collections:commons-collections:3.2.2", sha1 = "8ad72fe39fa8c91eaaf12aadb21e0c3661fe26d5", ) maven_jar( name = "cryptacular", artifact = "org.cryptacular:cryptacular:1.2.1", sha1 = "c470bac7309ac04b0b9529bd7dcb1e0b75954f11", ) maven_jar( name = "joda-time", artifact = "joda-time:joda-time:2.9.9", sha1 = "f7b520c458572890807d143670c9b24f4de90897", ) maven_jar( name = "opensaml-core", artifact = "org.opensaml:opensaml-core:" + OPENSAML_VERSION, sha1 = "406eedd86ea88c1442a6b1c7625a45cf696b9f55", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-saml-api", artifact = "org.opensaml:opensaml-saml-api:" + OPENSAML_VERSION, sha1 = "b2c68a7265e8b059ecbfff0ac6525720cd3e1a86", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-storage-api", artifact = "org.opensaml:opensaml-storage-api:" + OPENSAML_VERSION, sha1 = "80ff32a3df660fe71527f293a317813c51375dcc", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-saml-impl", artifact = "org.opensaml:opensaml-saml-impl:" + OPENSAML_VERSION, sha1 = "c4bce04bec8fd065bbc014a2c4003172ec612ba6", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-soap-impl", artifact = "org.opensaml:opensaml-soap-impl:" + OPENSAML_VERSION, sha1 = "9a1b9bc0ed6a0c62f3f607cc2c1164c76a57303e", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-soap-api", artifact = "org.opensaml:opensaml-soap-api:" + OPENSAML_VERSION, sha1 = "4fe18269fff79f7172d9dbe0d421886282baa434", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-xmlsec-api", artifact = "org.opensaml:opensaml-xmlsec-api:" + OPENSAML_VERSION, sha1 = "b7f0f8a9c17997008bcef75a8886faeb5e9d9ea9", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-xmlsec-impl", artifact = "org.opensaml:opensaml-xmlsec-impl:" + OPENSAML_VERSION, sha1 = "3dbdf38773a07d37f013dc9a2ecc4d0295a724de", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-security-api", artifact = "org.opensaml:opensaml-security-api:" + OPENSAML_VERSION, sha1 = "b6878bd144c15612ab899643e561e52f04d332c1", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-security-impl", artifact = "org.opensaml:opensaml-security-impl:" + OPENSAML_VERSION, sha1 = "72edf27dbce57ed29aebab8563a41942f7f15527", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-profile-api", artifact = "org.opensaml:opensaml-profile-api:" + OPENSAML_VERSION, sha1 = "8daff1c6b7ff47178054e17e78b0d4b19b622434", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-profile-impl", artifact = "org.opensaml:opensaml-profile-impl:" + OPENSAML_VERSION, sha1 = "175bd3d0ba07a17f0222ea799c3971119c9b32b3", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-messaging-api", artifact = "org.opensaml:opensaml-messaging-api:" + OPENSAML_VERSION, sha1 = "18f68283a3729e4355a29936861f6472ab20b2be", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-messaging-impl", artifact = "org.opensaml:opensaml-messaging-impl:" + OPENSAML_VERSION, sha1 = "d0cd65f2b0a167dc25477245adf5417a8735e132", repository = SHIBBOLETH, ) maven_jar( name = "pac4j-saml", artifact = "org.pac4j:pac4j-saml:" + PAC4J_VERSION, sha1 = "6897faedf4131f71954963945e4dbc13788d8d22", ) maven_jar( name = "pac4j-core", artifact = "org.pac4j:pac4j-core:" + PAC4J_VERSION, sha1 = "e5a82ad0a4a0e246edc8950d1e2c632a36732715", ) maven_jar( name = "shibboleth-utilities", artifact = "net.shibboleth.utilities:java-support:7.4.0", sha1 = "e10c137cdb5045eea2c0ccf8ac5094052eaee36b", repository = SHIBBOLETH, ) maven_jar( name = "shibboleth-xmlsectool", artifact = "net.shibboleth.tool:xmlsectool:2.0.0", sha1 = "c57f887f522c0e930341c7d86eff4d8ec9b797a1", repository = SHIBBOLETH, ) maven_jar( name = "santuario-xmlsec", artifact = "org.apache.santuario:xmlsec:2.1.4", sha1 = "cb43326f02e3e77526c24269c8b5d3cc3f7f6653", ) maven_jar( name = "spring-core", artifact = "org.springframework:spring-core:5.1.5.RELEASE", sha1 = "aacc4555108f3da913a58114b2aebc819f58cce4", ) maven_jar( name = "stax2-api", artifact = "org.codehaus.woodstox:stax2-api:3.1.4", sha1 = "ac19014b1e6a7c08aad07fe114af792676b685b7", ) maven_jar( name = "velocity", artifact = "org.apache.velocity:velocity:1.7", sha1 = "2ceb567b8f3f21118ecdec129fe1271dbc09aa7a", ) maven_jar( name = "woodstox-core", artifact = "com.fasterxml.woodstox:woodstox-core:5.0.3", sha1 = "10aa199207fda142eff01cd61c69244877d71770", )
30.67033
80
0.640989
load("//tools/bzl:maven_jar.bzl", "maven_jar") SHIBBOLETH = "https://build.shibboleth.net/nexus/content/repositories/releases/" OPENSAML_VERSION = "3.4.3" PAC4J_VERSION = "3.8.0" def external_plugin_deps(): maven_jar( name = "commons-collections", artifact = "commons-collections:commons-collections:3.2.2", sha1 = "8ad72fe39fa8c91eaaf12aadb21e0c3661fe26d5", ) maven_jar( name = "cryptacular", artifact = "org.cryptacular:cryptacular:1.2.1", sha1 = "c470bac7309ac04b0b9529bd7dcb1e0b75954f11", ) maven_jar( name = "joda-time", artifact = "joda-time:joda-time:2.9.9", sha1 = "f7b520c458572890807d143670c9b24f4de90897", ) maven_jar( name = "opensaml-core", artifact = "org.opensaml:opensaml-core:" + OPENSAML_VERSION, sha1 = "406eedd86ea88c1442a6b1c7625a45cf696b9f55", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-saml-api", artifact = "org.opensaml:opensaml-saml-api:" + OPENSAML_VERSION, sha1 = "b2c68a7265e8b059ecbfff0ac6525720cd3e1a86", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-storage-api", artifact = "org.opensaml:opensaml-storage-api:" + OPENSAML_VERSION, sha1 = "80ff32a3df660fe71527f293a317813c51375dcc", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-saml-impl", artifact = "org.opensaml:opensaml-saml-impl:" + OPENSAML_VERSION, sha1 = "c4bce04bec8fd065bbc014a2c4003172ec612ba6", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-soap-impl", artifact = "org.opensaml:opensaml-soap-impl:" + OPENSAML_VERSION, sha1 = "9a1b9bc0ed6a0c62f3f607cc2c1164c76a57303e", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-soap-api", artifact = "org.opensaml:opensaml-soap-api:" + OPENSAML_VERSION, sha1 = "4fe18269fff79f7172d9dbe0d421886282baa434", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-xmlsec-api", artifact = "org.opensaml:opensaml-xmlsec-api:" + OPENSAML_VERSION, sha1 = "b7f0f8a9c17997008bcef75a8886faeb5e9d9ea9", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-xmlsec-impl", artifact = "org.opensaml:opensaml-xmlsec-impl:" + OPENSAML_VERSION, sha1 = "3dbdf38773a07d37f013dc9a2ecc4d0295a724de", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-security-api", artifact = "org.opensaml:opensaml-security-api:" + OPENSAML_VERSION, sha1 = "b6878bd144c15612ab899643e561e52f04d332c1", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-security-impl", artifact = "org.opensaml:opensaml-security-impl:" + OPENSAML_VERSION, sha1 = "72edf27dbce57ed29aebab8563a41942f7f15527", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-profile-api", artifact = "org.opensaml:opensaml-profile-api:" + OPENSAML_VERSION, sha1 = "8daff1c6b7ff47178054e17e78b0d4b19b622434", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-profile-impl", artifact = "org.opensaml:opensaml-profile-impl:" + OPENSAML_VERSION, sha1 = "175bd3d0ba07a17f0222ea799c3971119c9b32b3", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-messaging-api", artifact = "org.opensaml:opensaml-messaging-api:" + OPENSAML_VERSION, sha1 = "18f68283a3729e4355a29936861f6472ab20b2be", repository = SHIBBOLETH, ) maven_jar( name = "opensaml-messaging-impl", artifact = "org.opensaml:opensaml-messaging-impl:" + OPENSAML_VERSION, sha1 = "d0cd65f2b0a167dc25477245adf5417a8735e132", repository = SHIBBOLETH, ) maven_jar( name = "pac4j-saml", artifact = "org.pac4j:pac4j-saml:" + PAC4J_VERSION, sha1 = "6897faedf4131f71954963945e4dbc13788d8d22", ) maven_jar( name = "pac4j-core", artifact = "org.pac4j:pac4j-core:" + PAC4J_VERSION, sha1 = "e5a82ad0a4a0e246edc8950d1e2c632a36732715", ) maven_jar( name = "shibboleth-utilities", artifact = "net.shibboleth.utilities:java-support:7.4.0", sha1 = "e10c137cdb5045eea2c0ccf8ac5094052eaee36b", repository = SHIBBOLETH, ) maven_jar( name = "shibboleth-xmlsectool", artifact = "net.shibboleth.tool:xmlsectool:2.0.0", sha1 = "c57f887f522c0e930341c7d86eff4d8ec9b797a1", repository = SHIBBOLETH, ) maven_jar( name = "santuario-xmlsec", artifact = "org.apache.santuario:xmlsec:2.1.4", sha1 = "cb43326f02e3e77526c24269c8b5d3cc3f7f6653", ) maven_jar( name = "spring-core", artifact = "org.springframework:spring-core:5.1.5.RELEASE", sha1 = "aacc4555108f3da913a58114b2aebc819f58cce4", ) maven_jar( name = "stax2-api", artifact = "org.codehaus.woodstox:stax2-api:3.1.4", sha1 = "ac19014b1e6a7c08aad07fe114af792676b685b7", ) maven_jar( name = "velocity", artifact = "org.apache.velocity:velocity:1.7", sha1 = "2ceb567b8f3f21118ecdec129fe1271dbc09aa7a", ) maven_jar( name = "woodstox-core", artifact = "com.fasterxml.woodstox:woodstox-core:5.0.3", sha1 = "10aa199207fda142eff01cd61c69244877d71770", )
true
true
f72c5a8f517248059d2b01dd023847f9b1fa269d
2,726
py
Python
django_project/store_cms/settings/base.py
Chumbak/RetailstoreTV-Content-Player
ea26f14045c3d30a2e348abac4d0a0c8df171b4b
[ "Apache-2.0" ]
2
2017-08-31T10:35:47.000Z
2017-11-10T07:03:43.000Z
django_project/store_cms/settings/base.py
Chumbak/RetailstoreTV-Content-Player
ea26f14045c3d30a2e348abac4d0a0c8df171b4b
[ "Apache-2.0" ]
null
null
null
django_project/store_cms/settings/base.py
Chumbak/RetailstoreTV-Content-Player
ea26f14045c3d30a2e348abac4d0a0c8df171b4b
[ "Apache-2.0" ]
5
2017-08-31T09:53:12.000Z
2018-08-02T04:26:32.000Z
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = bool(os.environ.get('DEBUG', False)) ALLOWED_HOSTS = [] # Application definition DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = ['cloudinary', 'bulk_admin'] LOCAL_APPS = ['cms'] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'store_cms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.static' ], }, }, ] WSGI_APPLICATION = 'store_cms.wsgi.application' # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") SESSION_SAVE_EVERY_REQUEST = True
25.240741
91
0.696992
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = bool(os.environ.get('DEBUG', False)) ALLOWED_HOSTS = [] DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = ['cloudinary', 'bulk_admin'] LOCAL_APPS = ['cms'] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'store_cms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.static' ], }, }, ] WSGI_APPLICATION = 'store_cms.wsgi.application' S = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") SESSION_SAVE_EVERY_REQUEST = True
true
true
f72c5b38b7252471247fc6364be4f544e55a623c
1,047
py
Python
Day_23/car_manager.py
johnsons-ux/100-days-of-python
59f8f5b1be85542306103df44383423b00e48931
[ "CC0-1.0" ]
1
2022-03-12T07:17:56.000Z
2022-03-12T07:17:56.000Z
Day_23/car_manager.py
johnsons-ux/100-days-of-python
59f8f5b1be85542306103df44383423b00e48931
[ "CC0-1.0" ]
null
null
null
Day_23/car_manager.py
johnsons-ux/100-days-of-python
59f8f5b1be85542306103df44383423b00e48931
[ "CC0-1.0" ]
null
null
null
from turtle import Turtle import random COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 class CarManager: def __init__(self): self.all_cars = [] self.car_speed = STARTING_MOVE_DISTANCE def create_car(self): random_chance = random.randint(1, 6) if random_chance == 1: new_car = Turtle('square') new_car.shapesize(1, 2) new_car.penup() new_car.color(random.choice(COLORS)) y_value = random.randint(-250, 250) new_car.goto(300, y_value) self.all_cars.append(new_car) def move_cars(self): for car in self.all_cars: car.backward(self.car_speed) # #The car is moving 'backward' as the 'setheading' is 0. This # means that it is facing east. Having it move forward would mean that the squares would be moving from # left to right of the screen. def new_level(self): self.car_speed += MOVE_INCREMENT
30.794118
115
0.619866
from turtle import Turtle import random COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 class CarManager: def __init__(self): self.all_cars = [] self.car_speed = STARTING_MOVE_DISTANCE def create_car(self): random_chance = random.randint(1, 6) if random_chance == 1: new_car = Turtle('square') new_car.shapesize(1, 2) new_car.penup() new_car.color(random.choice(COLORS)) y_value = random.randint(-250, 250) new_car.goto(300, y_value) self.all_cars.append(new_car) def move_cars(self): for car in self.all_cars: car.backward(self.car_speed) self.car_speed += MOVE_INCREMENT
true
true
f72c5ca5cbb2721d967ad9ef9dfa896f7ccce240
2,924
py
Python
tensorflow/python/estimator/canned/optimizers.py
tianyapiaozi/tensorflow
fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a
[ "Apache-2.0" ]
522
2016-06-08T02:15:50.000Z
2022-03-02T05:30:36.000Z
tensorflow/python/estimator/canned/optimizers.py
tianyapiaozi/tensorflow
fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a
[ "Apache-2.0" ]
133
2017-04-26T16:49:49.000Z
2019-10-15T11:39:26.000Z
tensorflow/python/estimator/canned/optimizers.py
tianyapiaozi/tensorflow
fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a
[ "Apache-2.0" ]
108
2016-06-16T15:34:05.000Z
2022-03-12T13:23:11.000Z
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Methods related to optimizers used in canned_estimators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.python.training import adagrad from tensorflow.python.training import adam from tensorflow.python.training import ftrl from tensorflow.python.training import gradient_descent from tensorflow.python.training import optimizer as optimizer_lib from tensorflow.python.training import rmsprop _OPTIMIZER_CLS_NAMES = { 'Adagrad': adagrad.AdagradOptimizer, 'Adam': adam.AdamOptimizer, 'Ftrl': ftrl.FtrlOptimizer, 'RMSProp': rmsprop.RMSPropOptimizer, 'SGD': gradient_descent.GradientDescentOptimizer, } def get_optimizer_instance(opt, learning_rate=None): """Returns an optimizer instance. Supports the following types for the given `opt`: * An `Optimizer` instance: Returns the given `opt`. * A string: Creates an `Optimizer` subclass with the given `learning_rate`. Supported strings: * 'Adagrad': Returns an `AdagradOptimizer`. * 'Adam': Returns an `AdamOptimizer`. * 'Ftrl': Returns an `FtrlOptimizer`. * 'RMSProp': Returns an `RMSPropOptimizer`. * 'SGD': Returns a `GradientDescentOptimizer`. Args: opt: An `Optimizer` instance, or string, as discussed above. learning_rate: A float. Only used if `opt` is a string. Returns: An `Optimizer` instance. Raises: ValueError: If `opt` is an unsupported string. ValueError: If `opt` is a supported string but `learning_rate` was not specified. ValueError: If `opt` is none of the above types. """ if isinstance(opt, six.string_types): if opt in six.iterkeys(_OPTIMIZER_CLS_NAMES): if not learning_rate: raise ValueError('learning_rate must be specified when opt is string.') return _OPTIMIZER_CLS_NAMES[opt](learning_rate=learning_rate) raise ValueError( 'Unsupported optimizer name: {}. Supported names are: {}'.format( opt, tuple(sorted(six.iterkeys(_OPTIMIZER_CLS_NAMES))))) if not isinstance(opt, optimizer_lib.Optimizer): raise ValueError( 'The given object is not an Optimizer instance. Given: {}'.format(opt)) return opt
37.012658
80
0.719904
from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.python.training import adagrad from tensorflow.python.training import adam from tensorflow.python.training import ftrl from tensorflow.python.training import gradient_descent from tensorflow.python.training import optimizer as optimizer_lib from tensorflow.python.training import rmsprop _OPTIMIZER_CLS_NAMES = { 'Adagrad': adagrad.AdagradOptimizer, 'Adam': adam.AdamOptimizer, 'Ftrl': ftrl.FtrlOptimizer, 'RMSProp': rmsprop.RMSPropOptimizer, 'SGD': gradient_descent.GradientDescentOptimizer, } def get_optimizer_instance(opt, learning_rate=None): if isinstance(opt, six.string_types): if opt in six.iterkeys(_OPTIMIZER_CLS_NAMES): if not learning_rate: raise ValueError('learning_rate must be specified when opt is string.') return _OPTIMIZER_CLS_NAMES[opt](learning_rate=learning_rate) raise ValueError( 'Unsupported optimizer name: {}. Supported names are: {}'.format( opt, tuple(sorted(six.iterkeys(_OPTIMIZER_CLS_NAMES))))) if not isinstance(opt, optimizer_lib.Optimizer): raise ValueError( 'The given object is not an Optimizer instance. Given: {}'.format(opt)) return opt
true
true
f72c5d1dce32355c3989c67add71367d80276cc4
6,188
py
Python
code/common/preprocessing.py
monperrus/iFixR
5548f3ba91341dc9e73057269f8c01a0b1b6fc68
[ "MIT" ]
8
2019-07-23T15:03:50.000Z
2021-02-08T11:06:53.000Z
code/common/preprocessing.py
monperrus/iFixR
5548f3ba91341dc9e73057269f8c01a0b1b6fc68
[ "MIT" ]
null
null
null
code/common/preprocessing.py
monperrus/iFixR
5548f3ba91341dc9e73057269f8c01a0b1b6fc68
[ "MIT" ]
4
2019-09-19T08:23:46.000Z
2021-03-05T13:57:40.000Z
from nltk.tokenize import RegexpTokenizer # from stop_words import get_stop_words from nltk.stem.porter import PorterStemmer from string import punctuation import re from nltk.corpus import stopwords en_stop = stopwords.words('english') from nltk.corpus import wordnet import html from common.commons import * CODE_PATH = os.environ["CODE_PATH"] import spacy nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger', 'ner']) nlp.max_length =100000000 from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import sys def preprocessingCodeElementsList(res): printDetail = False if isinstance(res, list): merged = str() for r in res: if isinstance(r, list): merged = merged + ' ' + ' '.join(r) else: merged = merged +' ' + r else: merged=res res = html.unescape(merged) tokens = getTokens(res,printDetail) stripped = [] for t in tokens: splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t) for s in splits: stripped.append(s) punc = removeEndingPunct(stripped,printDetail) non_empty = [i for i in punc if i != ''] stripped = removeEndingPunct(non_empty,printDetail) camelCase = handleCamelCase(stripped,printDetail,True) underScore = handleUnderScore(camelCase,printDetail,True) lower = [i.lower() for i in underScore] stopped_tokens = [i for i in lower if not i in en_stop] stem2 = stem(stopped_tokens,printDetail) if printDetail: print('=====CLEANED=========') print(stem2) return stem2 def preprocessingNL(res): printDetail = False if isinstance(res, list): merged = str() for r in res: if isinstance(r, list): merged = merged + ' ' + ' '.join(r) else: merged = merged +' ' + r else: merged=res res = html.unescape(merged) html_decoded_string = res.replace("&amp;", "&").replace("&quot;", '"').replace("&apos;", "'").replace("&gt;", ">").replace( "&lt;", "<") html_decoded_string = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '',html_decoded_string) tokens = getTokens(html_decoded_string,printDetail) stripped = [] for t in tokens: splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t) for s in splits: stripped.append(s) punc = removeEndingPunct(stripped,printDetail) non_empty = [i for i in punc if i != ''] stripped = removeEndingPunct(non_empty,printDetail) camelCase = handleCamelCase(stripped,printDetail,True) underScore = handleUnderScore(camelCase,printDetail,True) lower = [i.lower() for i in underScore] stopped_tokens = [i for i in lower if not i in en_stop] nonDigit = [i for i in stopped_tokens if (not i.isdigit())] doc = nlp(' '.join(nonDigit)) newWord = [] for token in doc: if(token.text in nlp.vocab): newWord.append(token.text) stem2 = stem(newWord,printDetail) if printDetail: print('=====CLEANED=========') print(stem2) return stem2 def getTokens(re,printDetail=False): tokenizer = RegexpTokenizer(r'\S+') tokens = tokenizer.tokenize(re) if printDetail: print('=====TOKENS=========') print(tokens) return tokens def charLength(x, l=3): if x.isalpha() and len(x) >= l: return True else: return False def removeEndingPunct(re,printDetail): stripped = [i.strip(punctuation) for i in re] if printDetail: print('=====removeEndingPunct=========') print(stripped) return stripped def handleCamelCase(re,printDetail=False,keepOriginal = False): camelCased = list() for i in re: listOfCC = camel_case_split(i) camelCased.extend(listOfCC) if i not in listOfCC and keepOriginal: camelCased.append(i) if printDetail: print('=====CAMEL CASE=========') print(camelCased) return camelCased def handleUnderScore(re,printDetail=False,keepOriginal = False): underScored = list() for i in re: listOfCC = i.split('_') underScored.extend(listOfCC) if i not in listOfCC and keepOriginal: underScored.append(i) if printDetail: print('=====UNDER SCORE=========') print(underScored) return underScored def camel_case_split(identifier): matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier) res = [m.group(0) for m in matches] return res def stem(res,printDetail): p_stemmer = PorterStemmer() stemmed_tokens = [p_stemmer.stem(i.strip()) for i in res if i] if printDetail: print('=====STEMMED=========') print(stemmed_tokens) return stemmed_tokens def isEnglish(word_to_test): if not wordnet.synsets(word_to_test): #Not an English Word #TODO word_to_test #print word_to_test else: return word_to_test def dummy_fun(doc): return doc def calculateTfIdfCodeElementsList(aCorpus): global progress progress = 0 v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3) m = v.fit(aCorpus) return v def calculateTfIdfNLList(aCorpus): global progress progress = 0 v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3) m = v.fit(aCorpus) return v def getDTMNL(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]]) def getDTMCE(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]]) def getBRDTM(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]]) def getBRDTMCEs(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]])
26.672414
139
0.609082
from nltk.tokenize import RegexpTokenizer from nltk.stem.porter import PorterStemmer from string import punctuation import re from nltk.corpus import stopwords en_stop = stopwords.words('english') from nltk.corpus import wordnet import html from common.commons import * CODE_PATH = os.environ["CODE_PATH"] import spacy nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger', 'ner']) nlp.max_length =100000000 from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import sys def preprocessingCodeElementsList(res): printDetail = False if isinstance(res, list): merged = str() for r in res: if isinstance(r, list): merged = merged + ' ' + ' '.join(r) else: merged = merged +' ' + r else: merged=res res = html.unescape(merged) tokens = getTokens(res,printDetail) stripped = [] for t in tokens: splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t) for s in splits: stripped.append(s) punc = removeEndingPunct(stripped,printDetail) non_empty = [i for i in punc if i != ''] stripped = removeEndingPunct(non_empty,printDetail) camelCase = handleCamelCase(stripped,printDetail,True) underScore = handleUnderScore(camelCase,printDetail,True) lower = [i.lower() for i in underScore] stopped_tokens = [i for i in lower if not i in en_stop] stem2 = stem(stopped_tokens,printDetail) if printDetail: print('=====CLEANED=========') print(stem2) return stem2 def preprocessingNL(res): printDetail = False if isinstance(res, list): merged = str() for r in res: if isinstance(r, list): merged = merged + ' ' + ' '.join(r) else: merged = merged +' ' + r else: merged=res res = html.unescape(merged) html_decoded_string = res.replace("&amp;", "&").replace("&quot;", '"').replace("&apos;", "'").replace("&gt;", ">").replace( "&lt;", "<") html_decoded_string = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '',html_decoded_string) tokens = getTokens(html_decoded_string,printDetail) stripped = [] for t in tokens: splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t) for s in splits: stripped.append(s) punc = removeEndingPunct(stripped,printDetail) non_empty = [i for i in punc if i != ''] stripped = removeEndingPunct(non_empty,printDetail) camelCase = handleCamelCase(stripped,printDetail,True) underScore = handleUnderScore(camelCase,printDetail,True) lower = [i.lower() for i in underScore] stopped_tokens = [i for i in lower if not i in en_stop] nonDigit = [i for i in stopped_tokens if (not i.isdigit())] doc = nlp(' '.join(nonDigit)) newWord = [] for token in doc: if(token.text in nlp.vocab): newWord.append(token.text) stem2 = stem(newWord,printDetail) if printDetail: print('=====CLEANED=========') print(stem2) return stem2 def getTokens(re,printDetail=False): tokenizer = RegexpTokenizer(r'\S+') tokens = tokenizer.tokenize(re) if printDetail: print('=====TOKENS=========') print(tokens) return tokens def charLength(x, l=3): if x.isalpha() and len(x) >= l: return True else: return False def removeEndingPunct(re,printDetail): stripped = [i.strip(punctuation) for i in re] if printDetail: print('=====removeEndingPunct=========') print(stripped) return stripped def handleCamelCase(re,printDetail=False,keepOriginal = False): camelCased = list() for i in re: listOfCC = camel_case_split(i) camelCased.extend(listOfCC) if i not in listOfCC and keepOriginal: camelCased.append(i) if printDetail: print('=====CAMEL CASE=========') print(camelCased) return camelCased def handleUnderScore(re,printDetail=False,keepOriginal = False): underScored = list() for i in re: listOfCC = i.split('_') underScored.extend(listOfCC) if i not in listOfCC and keepOriginal: underScored.append(i) if printDetail: print('=====UNDER SCORE=========') print(underScored) return underScored def camel_case_split(identifier): matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier) res = [m.group(0) for m in matches] return res def stem(res,printDetail): p_stemmer = PorterStemmer() stemmed_tokens = [p_stemmer.stem(i.strip()) for i in res if i] if printDetail: print('=====STEMMED=========') print(stemmed_tokens) return stemmed_tokens def isEnglish(word_to_test): if not wordnet.synsets(word_to_test): #Not an English Word #TODO word_to_test #print word_to_test else: return word_to_test def dummy_fun(doc): return doc def calculateTfIdfCodeElementsList(aCorpus): global progress progress = 0 v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3) m = v.fit(aCorpus) return v def calculateTfIdfNLList(aCorpus): global progress progress = 0 v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3) m = v.fit(aCorpus) return v def getDTMNL(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]]) def getDTMCE(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]]) def getBRDTM(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]]) def getBRDTMCEs(x,v,corpus): ind =x.name v.tokenizer = dummy_fun return v.transform([corpus[ind]])
true
true
f72c5d5b573a0a6f9bb62598300340bf644adab6
4,237
py
Python
ControlFlowGenerator.py
mehrangoli/Control-Flow-Extractor
6993be4b8508821674958e72b0d74159bc9a16a3
[ "MIT" ]
1
2019-07-18T08:06:51.000Z
2019-07-18T08:06:51.000Z
ControlFlowGenerator.py
mehrangoli/Control-Flow-Extractor
6993be4b8508821674958e72b0d74159bc9a16a3
[ "MIT" ]
null
null
null
ControlFlowGenerator.py
mehrangoli/Control-Flow-Extractor
6993be4b8508821674958e72b0d74159bc9a16a3
[ "MIT" ]
null
null
null
#This is a parser to generate control flow of a SystemC design from its extracted run-time information by GDB and present it in XML or txt format. #Copyright (c) 2019 Group of Computer Architecture, university of Bremen. All Rights Reserved. #Filename: ControlFlowGenerator.py #Version 1 09-July-2019 # -- coding: utf-8 -- #!/usr/bin/env python import re import copy from Define import * class CF_generator: def __init__(self): self.sequence_dict = {} self.unic_seq_dic = {} try: self.gdb_log = open("gdblog_ctrl.txt",'r') except IOError: print info_user.FAIL + "Could not find \"gdblog_ctrl.txt\" file!" + info_user.ENDC def CF_extractor (self): index = 0 for line in self.gdb_log: if ('reakpoint' in line) and (('(this=' in line) or ('sc_main' in line)): split_line=line.split() mf_name = "" if ('Temporary' in line): mf_name = split_line[3] this = split_line[4] else: mf_name = split_line[2] this = split_line[3] if ('sc_main' in line): this = "NULL" mf_name = 'sc_main' elif ('(this=' in line): this = re.sub(r'\s', '', this).split('=') this = this[1].replace(")","") source_code=split_line[-1] for line in self.gdb_log: if ('===' in line): split_line_time = line.split() time = int(split_line_time[-1]) break t = (mf_name, this, source_code, time) self.sequence_dict[index] = list(t) index = index +1 self.gdb_log.close() def print_CF (self): result_file = open("CF.txt",'w') result_file.write( "\n") result_file.write( "{:<18} {:<15}".format('Sequence','Execution_flow_information')) result_file.write( "\n\n" ) for k in sorted(self.sequence_dict.keys()): result_file.write( "{:<12} {:<15}".format(k, self.sequence_dict[k])) result_file.write( "\n" ) result_file.close() def Uniq_CF_extractor (self): index = 0 for i in sorted(self.sequence_dict.keys()): #print seq_dic[i][1] temp1 = str(self.sequence_dict[i][0])+str(self.sequence_dict[i][1]) if (i+1) <= max(self.sequence_dict.keys()): temp2 = str(self.sequence_dict[i+1][0])+str(self.sequence_dict[i+1][1]) if (temp1 != temp2): self.unic_seq_dic[index] = self.sequence_dict[i] index = index +1 if (i+1) == max(self.sequence_dict.keys()): self.unic_seq_dic[index] = self.sequence_dict[i+1] index = index +1 def XML_generator (self): xml_result_file = open("XML_CF.xml",'w') string = "<ESL_RUN_TIME_TRACE>\n\t" xml_result_file.write(string ) tmp = [] for k in sorted(self.unic_seq_dic.keys()): if self.unic_seq_dic[k][0] != 'sc_main': tmp = re.sub(r'\s', '', self.unic_seq_dic[k][0]).split(':') module_name = tmp[0] func_name = tmp[2] else: module_name = self.unic_seq_dic[k][0] func_name = self.unic_seq_dic[k][0] tmp = re.sub(r'\s', '', self.unic_seq_dic[k][2]).split(':') source_name = tmp[0] line_number = tmp[1] string = '<SEQUENCE>\n\t\t<SEQUENCE_NUMBER> %d </SEQUENCE_NUMBER>\n\t\t<ROOT_MODULE> %s </ROOT_MODULE>\n\t\t<FUNCTION_NAME> %s </FUNCTION_NAME>\n\t\t<INSTANCE_ID> %s </INSTANCE_ID>\n\t\t\ <LINE_OF_CODE>\n\t\t\t<SOURCE_FILE> %s </SOURCE_FILE>\n\t\t\t<LINE_NUMBER> %s </LINE_NUMBER>\n\t\t</LINE_OF_CODE>\n\t\t\ <SIMULATION_TIME> %s </SIMULATION_TIME>\n\t</SEQUENCE>\n\t'%(k, module_name, func_name, self.unic_seq_dic[k][1], source_name, line_number, self.unic_seq_dic[k][3]) xml_result_file.write(string) xml_result_file.write ("\n") xml_result_file.write ("</ESL_RUN_TIME_TRACE>\n") CF_generator_instance = CF_generator() CF_generator_instance.CF_extractor() CF_generator_instance.Uniq_CF_extractor() input_arc = raw_input(info_user.OKBLUE +"Generating control flow in .txt format? (Y/N)\n"+ info_user.ENDC) if input_arc == 'Y' or input_arc == 'y': CF_generator_instance.print_CF() print info_user.OKGREEN +"Control flow in .txt format is generated!\n"+ info_user.ENDC input_arc = raw_input(info_user.OKBLUE +"Generating control flow in .XML format? (Y/N)\n"+ info_user.ENDC) if input_arc == 'Y' or input_arc == 'y': CF_generator_instance.XML_generator() print info_user.OKGREEN +"Control flow in .XML format is generated!\n"+ info_user.ENDC
36.525862
190
0.665093
import re import copy from Define import * class CF_generator: def __init__(self): self.sequence_dict = {} self.unic_seq_dic = {} try: self.gdb_log = open("gdblog_ctrl.txt",'r') except IOError: print info_user.FAIL + "Could not find \"gdblog_ctrl.txt\" file!" + info_user.ENDC def CF_extractor (self): index = 0 for line in self.gdb_log: if ('reakpoint' in line) and (('(this=' in line) or ('sc_main' in line)): split_line=line.split() mf_name = "" if ('Temporary' in line): mf_name = split_line[3] this = split_line[4] else: mf_name = split_line[2] this = split_line[3] if ('sc_main' in line): this = "NULL" mf_name = 'sc_main' elif ('(this=' in line): this = re.sub(r'\s', '', this).split('=') this = this[1].replace(")","") source_code=split_line[-1] for line in self.gdb_log: if ('===' in line): split_line_time = line.split() time = int(split_line_time[-1]) break t = (mf_name, this, source_code, time) self.sequence_dict[index] = list(t) index = index +1 self.gdb_log.close() def print_CF (self): result_file = open("CF.txt",'w') result_file.write( "\n") result_file.write( "{:<18} {:<15}".format('Sequence','Execution_flow_information')) result_file.write( "\n\n" ) for k in sorted(self.sequence_dict.keys()): result_file.write( "{:<12} {:<15}".format(k, self.sequence_dict[k])) result_file.write( "\n" ) result_file.close() def Uniq_CF_extractor (self): index = 0 for i in sorted(self.sequence_dict.keys()): temp1 = str(self.sequence_dict[i][0])+str(self.sequence_dict[i][1]) if (i+1) <= max(self.sequence_dict.keys()): temp2 = str(self.sequence_dict[i+1][0])+str(self.sequence_dict[i+1][1]) if (temp1 != temp2): self.unic_seq_dic[index] = self.sequence_dict[i] index = index +1 if (i+1) == max(self.sequence_dict.keys()): self.unic_seq_dic[index] = self.sequence_dict[i+1] index = index +1 def XML_generator (self): xml_result_file = open("XML_CF.xml",'w') string = "<ESL_RUN_TIME_TRACE>\n\t" xml_result_file.write(string ) tmp = [] for k in sorted(self.unic_seq_dic.keys()): if self.unic_seq_dic[k][0] != 'sc_main': tmp = re.sub(r'\s', '', self.unic_seq_dic[k][0]).split(':') module_name = tmp[0] func_name = tmp[2] else: module_name = self.unic_seq_dic[k][0] func_name = self.unic_seq_dic[k][0] tmp = re.sub(r'\s', '', self.unic_seq_dic[k][2]).split(':') source_name = tmp[0] line_number = tmp[1] string = '<SEQUENCE>\n\t\t<SEQUENCE_NUMBER> %d </SEQUENCE_NUMBER>\n\t\t<ROOT_MODULE> %s </ROOT_MODULE>\n\t\t<FUNCTION_NAME> %s </FUNCTION_NAME>\n\t\t<INSTANCE_ID> %s </INSTANCE_ID>\n\t\t\ <LINE_OF_CODE>\n\t\t\t<SOURCE_FILE> %s </SOURCE_FILE>\n\t\t\t<LINE_NUMBER> %s </LINE_NUMBER>\n\t\t</LINE_OF_CODE>\n\t\t\ <SIMULATION_TIME> %s </SIMULATION_TIME>\n\t</SEQUENCE>\n\t'%(k, module_name, func_name, self.unic_seq_dic[k][1], source_name, line_number, self.unic_seq_dic[k][3]) xml_result_file.write(string) xml_result_file.write ("\n") xml_result_file.write ("</ESL_RUN_TIME_TRACE>\n") CF_generator_instance = CF_generator() CF_generator_instance.CF_extractor() CF_generator_instance.Uniq_CF_extractor() input_arc = raw_input(info_user.OKBLUE +"Generating control flow in .txt format? (Y/N)\n"+ info_user.ENDC) if input_arc == 'Y' or input_arc == 'y': CF_generator_instance.print_CF() print info_user.OKGREEN +"Control flow in .txt format is generated!\n"+ info_user.ENDC input_arc = raw_input(info_user.OKBLUE +"Generating control flow in .XML format? (Y/N)\n"+ info_user.ENDC) if input_arc == 'Y' or input_arc == 'y': CF_generator_instance.XML_generator() print info_user.OKGREEN +"Control flow in .XML format is generated!\n"+ info_user.ENDC
false
true
f72c5e0a7a2455dfd966067814f820b39b4646a1
8,806
py
Python
src/main/resources/pytz/zoneinfo/America/Moncton.py
TheEin/swagger-maven-plugin
cf93dce2d5c8d3534f4cf8c612b11e2d2313871b
[ "Apache-2.0" ]
65
2015-11-14T13:46:01.000Z
2021-08-14T05:54:04.000Z
lib/pytz/zoneinfo/America/Moncton.py
tjsavage/polymer-dashboard
19bc467f1206613f8eec646b6f2bc43cc319ef75
[ "CNRI-Python", "Linux-OpenIB" ]
13
2016-03-31T20:00:17.000Z
2021-08-20T14:52:31.000Z
lib/pytz/zoneinfo/America/Moncton.py
tjsavage/polymer-dashboard
19bc467f1206613f8eec646b6f2bc43cc319ef75
[ "CNRI-Python", "Linux-OpenIB" ]
20
2015-03-18T08:41:37.000Z
2020-12-18T02:58:30.000Z
'''tzinfo timezone information for America/Moncton.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Moncton(DstTzInfo): '''America/Moncton timezone definition. See datetime.tzinfo for details''' zone = 'America/Moncton' _utc_transition_times = [ d(1,1,1,0,0,0), d(1902,6,15,5,0,0), d(1918,4,14,6,0,0), d(1918,10,31,5,0,0), d(1933,6,11,5,0,0), d(1933,9,10,4,0,0), d(1934,6,10,5,0,0), d(1934,9,9,4,0,0), d(1935,6,9,5,0,0), d(1935,9,8,4,0,0), d(1936,6,7,5,0,0), d(1936,9,6,4,0,0), d(1937,6,6,5,0,0), d(1937,9,5,4,0,0), d(1938,6,5,5,0,0), d(1938,9,4,4,0,0), d(1939,5,27,5,0,0), d(1939,9,23,4,0,0), d(1940,5,19,5,0,0), d(1940,9,21,4,0,0), d(1941,5,4,5,0,0), d(1941,9,27,4,0,0), d(1942,2,9,6,0,0), d(1945,8,14,23,0,0), d(1945,9,30,5,0,0), d(1946,4,28,6,0,0), d(1946,9,29,5,0,0), d(1947,4,27,6,0,0), d(1947,9,28,5,0,0), d(1948,4,25,6,0,0), d(1948,9,26,5,0,0), d(1949,4,24,6,0,0), d(1949,9,25,5,0,0), d(1950,4,30,6,0,0), d(1950,9,24,5,0,0), d(1951,4,29,6,0,0), d(1951,9,30,5,0,0), d(1952,4,27,6,0,0), d(1952,9,28,5,0,0), d(1953,4,26,6,0,0), d(1953,9,27,5,0,0), d(1954,4,25,6,0,0), d(1954,9,26,5,0,0), d(1955,4,24,6,0,0), d(1955,9,25,5,0,0), d(1956,4,29,6,0,0), d(1956,9,30,5,0,0), d(1957,4,28,6,0,0), d(1957,10,27,5,0,0), d(1958,4,27,6,0,0), d(1958,10,26,5,0,0), d(1959,4,26,6,0,0), d(1959,10,25,5,0,0), d(1960,4,24,6,0,0), d(1960,10,30,5,0,0), d(1961,4,30,6,0,0), d(1961,10,29,5,0,0), d(1962,4,29,6,0,0), d(1962,10,28,5,0,0), d(1963,4,28,6,0,0), d(1963,10,27,5,0,0), d(1964,4,26,6,0,0), d(1964,10,25,5,0,0), d(1965,4,25,6,0,0), d(1965,10,31,5,0,0), d(1966,4,24,6,0,0), d(1966,10,30,5,0,0), d(1967,4,30,6,0,0), d(1967,10,29,5,0,0), d(1968,4,28,6,0,0), d(1968,10,27,5,0,0), d(1969,4,27,6,0,0), d(1969,10,26,5,0,0), d(1970,4,26,6,0,0), d(1970,10,25,5,0,0), d(1971,4,25,6,0,0), d(1971,10,31,5,0,0), d(1972,4,30,6,0,0), d(1972,10,29,5,0,0), d(1974,4,28,6,0,0), d(1974,10,27,5,0,0), d(1975,4,27,6,0,0), d(1975,10,26,5,0,0), d(1976,4,25,6,0,0), d(1976,10,31,5,0,0), d(1977,4,24,6,0,0), d(1977,10,30,5,0,0), d(1978,4,30,6,0,0), d(1978,10,29,5,0,0), d(1979,4,29,6,0,0), d(1979,10,28,5,0,0), d(1980,4,27,6,0,0), d(1980,10,26,5,0,0), d(1981,4,26,6,0,0), d(1981,10,25,5,0,0), d(1982,4,25,6,0,0), d(1982,10,31,5,0,0), d(1983,4,24,6,0,0), d(1983,10,30,5,0,0), d(1984,4,29,6,0,0), d(1984,10,28,5,0,0), d(1985,4,28,6,0,0), d(1985,10,27,5,0,0), d(1986,4,27,6,0,0), d(1986,10,26,5,0,0), d(1987,4,5,6,0,0), d(1987,10,25,5,0,0), d(1988,4,3,6,0,0), d(1988,10,30,5,0,0), d(1989,4,2,6,0,0), d(1989,10,29,5,0,0), d(1990,4,1,6,0,0), d(1990,10,28,5,0,0), d(1991,4,7,6,0,0), d(1991,10,27,5,0,0), d(1992,4,5,6,0,0), d(1992,10,25,5,0,0), d(1993,4,4,4,1,0), d(1993,10,31,3,1,0), d(1994,4,3,4,1,0), d(1994,10,30,3,1,0), d(1995,4,2,4,1,0), d(1995,10,29,3,1,0), d(1996,4,7,4,1,0), d(1996,10,27,3,1,0), d(1997,4,6,4,1,0), d(1997,10,26,3,1,0), d(1998,4,5,4,1,0), d(1998,10,25,3,1,0), d(1999,4,4,4,1,0), d(1999,10,31,3,1,0), d(2000,4,2,4,1,0), d(2000,10,29,3,1,0), d(2001,4,1,4,1,0), d(2001,10,28,3,1,0), d(2002,4,7,4,1,0), d(2002,10,27,3,1,0), d(2003,4,6,4,1,0), d(2003,10,26,3,1,0), d(2004,4,4,4,1,0), d(2004,10,31,3,1,0), d(2005,4,3,4,1,0), d(2005,10,30,3,1,0), d(2006,4,2,4,1,0), d(2006,10,29,3,1,0), d(2007,3,11,6,0,0), d(2007,11,4,5,0,0), d(2008,3,9,6,0,0), d(2008,11,2,5,0,0), d(2009,3,8,6,0,0), d(2009,11,1,5,0,0), d(2010,3,14,6,0,0), d(2010,11,7,5,0,0), d(2011,3,13,6,0,0), d(2011,11,6,5,0,0), d(2012,3,11,6,0,0), d(2012,11,4,5,0,0), d(2013,3,10,6,0,0), d(2013,11,3,5,0,0), d(2014,3,9,6,0,0), d(2014,11,2,5,0,0), d(2015,3,8,6,0,0), d(2015,11,1,5,0,0), d(2016,3,13,6,0,0), d(2016,11,6,5,0,0), d(2017,3,12,6,0,0), d(2017,11,5,5,0,0), d(2018,3,11,6,0,0), d(2018,11,4,5,0,0), d(2019,3,10,6,0,0), d(2019,11,3,5,0,0), d(2020,3,8,6,0,0), d(2020,11,1,5,0,0), d(2021,3,14,6,0,0), d(2021,11,7,5,0,0), d(2022,3,13,6,0,0), d(2022,11,6,5,0,0), d(2023,3,12,6,0,0), d(2023,11,5,5,0,0), d(2024,3,10,6,0,0), d(2024,11,3,5,0,0), d(2025,3,9,6,0,0), d(2025,11,2,5,0,0), d(2026,3,8,6,0,0), d(2026,11,1,5,0,0), d(2027,3,14,6,0,0), d(2027,11,7,5,0,0), d(2028,3,12,6,0,0), d(2028,11,5,5,0,0), d(2029,3,11,6,0,0), d(2029,11,4,5,0,0), d(2030,3,10,6,0,0), d(2030,11,3,5,0,0), d(2031,3,9,6,0,0), d(2031,11,2,5,0,0), d(2032,3,14,6,0,0), d(2032,11,7,5,0,0), d(2033,3,13,6,0,0), d(2033,11,6,5,0,0), d(2034,3,12,6,0,0), d(2034,11,5,5,0,0), d(2035,3,11,6,0,0), d(2035,11,4,5,0,0), d(2036,3,9,6,0,0), d(2036,11,2,5,0,0), d(2037,3,8,6,0,0), d(2037,11,1,5,0,0), ] _transition_info = [ i(-18000,0,'EST'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'AWT'), i(-10800,3600,'APT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), ] Moncton = Moncton()
20.337182
78
0.563479
from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Moncton(DstTzInfo): zone = 'America/Moncton' _utc_transition_times = [ d(1,1,1,0,0,0), d(1902,6,15,5,0,0), d(1918,4,14,6,0,0), d(1918,10,31,5,0,0), d(1933,6,11,5,0,0), d(1933,9,10,4,0,0), d(1934,6,10,5,0,0), d(1934,9,9,4,0,0), d(1935,6,9,5,0,0), d(1935,9,8,4,0,0), d(1936,6,7,5,0,0), d(1936,9,6,4,0,0), d(1937,6,6,5,0,0), d(1937,9,5,4,0,0), d(1938,6,5,5,0,0), d(1938,9,4,4,0,0), d(1939,5,27,5,0,0), d(1939,9,23,4,0,0), d(1940,5,19,5,0,0), d(1940,9,21,4,0,0), d(1941,5,4,5,0,0), d(1941,9,27,4,0,0), d(1942,2,9,6,0,0), d(1945,8,14,23,0,0), d(1945,9,30,5,0,0), d(1946,4,28,6,0,0), d(1946,9,29,5,0,0), d(1947,4,27,6,0,0), d(1947,9,28,5,0,0), d(1948,4,25,6,0,0), d(1948,9,26,5,0,0), d(1949,4,24,6,0,0), d(1949,9,25,5,0,0), d(1950,4,30,6,0,0), d(1950,9,24,5,0,0), d(1951,4,29,6,0,0), d(1951,9,30,5,0,0), d(1952,4,27,6,0,0), d(1952,9,28,5,0,0), d(1953,4,26,6,0,0), d(1953,9,27,5,0,0), d(1954,4,25,6,0,0), d(1954,9,26,5,0,0), d(1955,4,24,6,0,0), d(1955,9,25,5,0,0), d(1956,4,29,6,0,0), d(1956,9,30,5,0,0), d(1957,4,28,6,0,0), d(1957,10,27,5,0,0), d(1958,4,27,6,0,0), d(1958,10,26,5,0,0), d(1959,4,26,6,0,0), d(1959,10,25,5,0,0), d(1960,4,24,6,0,0), d(1960,10,30,5,0,0), d(1961,4,30,6,0,0), d(1961,10,29,5,0,0), d(1962,4,29,6,0,0), d(1962,10,28,5,0,0), d(1963,4,28,6,0,0), d(1963,10,27,5,0,0), d(1964,4,26,6,0,0), d(1964,10,25,5,0,0), d(1965,4,25,6,0,0), d(1965,10,31,5,0,0), d(1966,4,24,6,0,0), d(1966,10,30,5,0,0), d(1967,4,30,6,0,0), d(1967,10,29,5,0,0), d(1968,4,28,6,0,0), d(1968,10,27,5,0,0), d(1969,4,27,6,0,0), d(1969,10,26,5,0,0), d(1970,4,26,6,0,0), d(1970,10,25,5,0,0), d(1971,4,25,6,0,0), d(1971,10,31,5,0,0), d(1972,4,30,6,0,0), d(1972,10,29,5,0,0), d(1974,4,28,6,0,0), d(1974,10,27,5,0,0), d(1975,4,27,6,0,0), d(1975,10,26,5,0,0), d(1976,4,25,6,0,0), d(1976,10,31,5,0,0), d(1977,4,24,6,0,0), d(1977,10,30,5,0,0), d(1978,4,30,6,0,0), d(1978,10,29,5,0,0), d(1979,4,29,6,0,0), d(1979,10,28,5,0,0), d(1980,4,27,6,0,0), d(1980,10,26,5,0,0), d(1981,4,26,6,0,0), d(1981,10,25,5,0,0), d(1982,4,25,6,0,0), d(1982,10,31,5,0,0), d(1983,4,24,6,0,0), d(1983,10,30,5,0,0), d(1984,4,29,6,0,0), d(1984,10,28,5,0,0), d(1985,4,28,6,0,0), d(1985,10,27,5,0,0), d(1986,4,27,6,0,0), d(1986,10,26,5,0,0), d(1987,4,5,6,0,0), d(1987,10,25,5,0,0), d(1988,4,3,6,0,0), d(1988,10,30,5,0,0), d(1989,4,2,6,0,0), d(1989,10,29,5,0,0), d(1990,4,1,6,0,0), d(1990,10,28,5,0,0), d(1991,4,7,6,0,0), d(1991,10,27,5,0,0), d(1992,4,5,6,0,0), d(1992,10,25,5,0,0), d(1993,4,4,4,1,0), d(1993,10,31,3,1,0), d(1994,4,3,4,1,0), d(1994,10,30,3,1,0), d(1995,4,2,4,1,0), d(1995,10,29,3,1,0), d(1996,4,7,4,1,0), d(1996,10,27,3,1,0), d(1997,4,6,4,1,0), d(1997,10,26,3,1,0), d(1998,4,5,4,1,0), d(1998,10,25,3,1,0), d(1999,4,4,4,1,0), d(1999,10,31,3,1,0), d(2000,4,2,4,1,0), d(2000,10,29,3,1,0), d(2001,4,1,4,1,0), d(2001,10,28,3,1,0), d(2002,4,7,4,1,0), d(2002,10,27,3,1,0), d(2003,4,6,4,1,0), d(2003,10,26,3,1,0), d(2004,4,4,4,1,0), d(2004,10,31,3,1,0), d(2005,4,3,4,1,0), d(2005,10,30,3,1,0), d(2006,4,2,4,1,0), d(2006,10,29,3,1,0), d(2007,3,11,6,0,0), d(2007,11,4,5,0,0), d(2008,3,9,6,0,0), d(2008,11,2,5,0,0), d(2009,3,8,6,0,0), d(2009,11,1,5,0,0), d(2010,3,14,6,0,0), d(2010,11,7,5,0,0), d(2011,3,13,6,0,0), d(2011,11,6,5,0,0), d(2012,3,11,6,0,0), d(2012,11,4,5,0,0), d(2013,3,10,6,0,0), d(2013,11,3,5,0,0), d(2014,3,9,6,0,0), d(2014,11,2,5,0,0), d(2015,3,8,6,0,0), d(2015,11,1,5,0,0), d(2016,3,13,6,0,0), d(2016,11,6,5,0,0), d(2017,3,12,6,0,0), d(2017,11,5,5,0,0), d(2018,3,11,6,0,0), d(2018,11,4,5,0,0), d(2019,3,10,6,0,0), d(2019,11,3,5,0,0), d(2020,3,8,6,0,0), d(2020,11,1,5,0,0), d(2021,3,14,6,0,0), d(2021,11,7,5,0,0), d(2022,3,13,6,0,0), d(2022,11,6,5,0,0), d(2023,3,12,6,0,0), d(2023,11,5,5,0,0), d(2024,3,10,6,0,0), d(2024,11,3,5,0,0), d(2025,3,9,6,0,0), d(2025,11,2,5,0,0), d(2026,3,8,6,0,0), d(2026,11,1,5,0,0), d(2027,3,14,6,0,0), d(2027,11,7,5,0,0), d(2028,3,12,6,0,0), d(2028,11,5,5,0,0), d(2029,3,11,6,0,0), d(2029,11,4,5,0,0), d(2030,3,10,6,0,0), d(2030,11,3,5,0,0), d(2031,3,9,6,0,0), d(2031,11,2,5,0,0), d(2032,3,14,6,0,0), d(2032,11,7,5,0,0), d(2033,3,13,6,0,0), d(2033,11,6,5,0,0), d(2034,3,12,6,0,0), d(2034,11,5,5,0,0), d(2035,3,11,6,0,0), d(2035,11,4,5,0,0), d(2036,3,9,6,0,0), d(2036,11,2,5,0,0), d(2037,3,8,6,0,0), d(2037,11,1,5,0,0), ] _transition_info = [ i(-18000,0,'EST'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'AWT'), i(-10800,3600,'APT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), i(-10800,3600,'ADT'), i(-14400,0,'AST'), ] Moncton = Moncton()
true
true
f72c5ecb4c2bda8417b9edf7a53fca157ea84580
397
py
Python
ReefberryPi/wsgi.py
reefberrypi/reefberrypi
f1e9977e8f56b402ef4d231ba8d4cdd0e469db42
[ "MIT" ]
null
null
null
ReefberryPi/wsgi.py
reefberrypi/reefberrypi
f1e9977e8f56b402ef4d231ba8d4cdd0e469db42
[ "MIT" ]
null
null
null
ReefberryPi/wsgi.py
reefberrypi/reefberrypi
f1e9977e8f56b402ef4d231ba8d4cdd0e469db42
[ "MIT" ]
null
null
null
""" WSGI config for ReefberryPi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ReefberryPi.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
26.466667
78
0.793451
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ReefberryPi.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
true
true
f72c5ef7f4210f6058725bdb8a177f76f278f6d9
3,669
py
Python
quetz/tests/test_workers.py
beenje/quetz
1c9e5827e81f7ea89e7a0efc4c855ef63577a028
[ "BSD-3-Clause" ]
null
null
null
quetz/tests/test_workers.py
beenje/quetz
1c9e5827e81f7ea89e7a0efc4c855ef63577a028
[ "BSD-3-Clause" ]
null
null
null
quetz/tests/test_workers.py
beenje/quetz
1c9e5827e81f7ea89e7a0efc4c855ef63577a028
[ "BSD-3-Clause" ]
null
null
null
import os import socket from contextlib import closing import pytest import requests from fastapi import BackgroundTasks from quetz.authorization import Rules from quetz.dao import Dao from quetz.db_models import User from quetz.tasks.workers import RQManager, SubprocessWorker, ThreadingWorker @pytest.fixture def sqlite_url(config_dir): # overriding sqlite_url to save to file so that # we can access the same db from a sub-process return f'sqlite:///{config_dir}/quetz.db' @pytest.fixture def http_session(): return requests.Session() @pytest.fixture def background_tasks(): bg_tasks = BackgroundTasks() return bg_tasks @pytest.fixture def api_key(): return "api-key" @pytest.fixture def browser_session(): return {} @pytest.fixture def auth(db, api_key, browser_session): return Rules(api_key, browser_session, db) @pytest.fixture def redis_ip(): return "127.0.0.1" @pytest.fixture def redis_port(): return 6379 @pytest.fixture def redis_db(): return 0 @pytest.fixture def threading_worker(background_tasks, dao, auth, http_session, config): worker = ThreadingWorker(background_tasks, dao, auth, http_session, config) return worker @pytest.fixture def subprocess_worker(api_key, browser_session, db, config): SubprocessWorker._executor = None worker = SubprocessWorker(api_key, browser_session, config) return worker @pytest.fixture def redis_worker(redis_ip, redis_port, redis_db, api_key, browser_session, db, config): worker = RQManager( redis_ip, redis_port, redis_db, api_key, browser_session, config, no_testing=False, ) return worker def check_socket(host, port): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.settimeout(2) if sock.connect_ex((host, port)) == 0: return True else: return False def check_redis(): return check_socket('127.0.0.1', 6379) @pytest.fixture( params=[ "threading_worker", "subprocess_worker", pytest.param( # type: ignore "redis_worker", marks=pytest.mark.skipif(not check_redis(), reason='no redis'), ), ] ) def any_worker(request): val = request.getfixturevalue(request.param) return val def basic_function(config_dir): os.chdir(config_dir) with open("test.txt", "w") as fid: fid.write("hello world!") def function_with_dao(dao: Dao): dao.create_user_with_role("my-user") @pytest.fixture def db_cleanup(config): # we can't use the db fixture for cleaning up because # it automatically rollsback all operations yield from quetz.database import get_session db = get_session(config.sqlalchemy_database_url) user = db.query(User).one_or_none() if user: db.delete(user) db.commit() @pytest.mark.asyncio async def test_threading_worker_execute(background_tasks, any_worker, db, config_dir): any_worker.execute(basic_function, config_dir=config_dir) await any_worker.wait() with open("test.txt") as fid: output = fid.read() assert output == "hello world!" @pytest.mark.asyncio async def test_threading_worker_execute_with_dao( background_tasks, any_worker, db, db_cleanup ): any_worker.execute(function_with_dao) await any_worker.wait() users = db.query(User).all() assert len(users) == 1 assert users[0].username == 'my-user' # we need to explicitly cleanup because sub-process did not use # our db fixture, this will be done at teardown in the db_cleanup fixture
21.086207
87
0.696648
import os import socket from contextlib import closing import pytest import requests from fastapi import BackgroundTasks from quetz.authorization import Rules from quetz.dao import Dao from quetz.db_models import User from quetz.tasks.workers import RQManager, SubprocessWorker, ThreadingWorker @pytest.fixture def sqlite_url(config_dir): return f'sqlite:///{config_dir}/quetz.db' @pytest.fixture def http_session(): return requests.Session() @pytest.fixture def background_tasks(): bg_tasks = BackgroundTasks() return bg_tasks @pytest.fixture def api_key(): return "api-key" @pytest.fixture def browser_session(): return {} @pytest.fixture def auth(db, api_key, browser_session): return Rules(api_key, browser_session, db) @pytest.fixture def redis_ip(): return "127.0.0.1" @pytest.fixture def redis_port(): return 6379 @pytest.fixture def redis_db(): return 0 @pytest.fixture def threading_worker(background_tasks, dao, auth, http_session, config): worker = ThreadingWorker(background_tasks, dao, auth, http_session, config) return worker @pytest.fixture def subprocess_worker(api_key, browser_session, db, config): SubprocessWorker._executor = None worker = SubprocessWorker(api_key, browser_session, config) return worker @pytest.fixture def redis_worker(redis_ip, redis_port, redis_db, api_key, browser_session, db, config): worker = RQManager( redis_ip, redis_port, redis_db, api_key, browser_session, config, no_testing=False, ) return worker def check_socket(host, port): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.settimeout(2) if sock.connect_ex((host, port)) == 0: return True else: return False def check_redis(): return check_socket('127.0.0.1', 6379) @pytest.fixture( params=[ "threading_worker", "subprocess_worker", pytest.param( "redis_worker", marks=pytest.mark.skipif(not check_redis(), reason='no redis'), ), ] ) def any_worker(request): val = request.getfixturevalue(request.param) return val def basic_function(config_dir): os.chdir(config_dir) with open("test.txt", "w") as fid: fid.write("hello world!") def function_with_dao(dao: Dao): dao.create_user_with_role("my-user") @pytest.fixture def db_cleanup(config): # it automatically rollsback all operations yield from quetz.database import get_session db = get_session(config.sqlalchemy_database_url) user = db.query(User).one_or_none() if user: db.delete(user) db.commit() @pytest.mark.asyncio async def test_threading_worker_execute(background_tasks, any_worker, db, config_dir): any_worker.execute(basic_function, config_dir=config_dir) await any_worker.wait() with open("test.txt") as fid: output = fid.read() assert output == "hello world!" @pytest.mark.asyncio async def test_threading_worker_execute_with_dao( background_tasks, any_worker, db, db_cleanup ): any_worker.execute(function_with_dao) await any_worker.wait() users = db.query(User).all() assert len(users) == 1 assert users[0].username == 'my-user' # we need to explicitly cleanup because sub-process did not use # our db fixture, this will be done at teardown in the db_cleanup fixture
true
true
f72c5f1f4d6cd6f6582fcd1e96aee59135e0c5f7
14,438
py
Python
grr/lib/lexer.py
nexus-lab/relf-server
d46774799c20376691c38f9293f454a3aff3ccb3
[ "Apache-2.0" ]
null
null
null
grr/lib/lexer.py
nexus-lab/relf-server
d46774799c20376691c38f9293f454a3aff3ccb3
[ "Apache-2.0" ]
null
null
null
grr/lib/lexer.py
nexus-lab/relf-server
d46774799c20376691c38f9293f454a3aff3ccb3
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """An LL(1) lexer. This lexer is very tolerant of errors and can resync.""" import logging import re from grr.lib import utils class Token(object): """A token action.""" state_regex = None def __init__(self, state_regex, regex, actions, next_state, flags=re.I): """Constructor. Args: state_regex: If this regular expression matches the current state this rule is considered. regex: A regular expression to try and match from the current point. actions: A command separated list of method names in the Lexer to call. next_state: The next state we transition to if this Token matches. flags: re flags. """ if state_regex: self.state_regex = re.compile(state_regex, re.DOTALL | re.M | re.S | re.U | flags) self.regex = re.compile(regex, re.DOTALL | re.M | re.S | re.U | flags) self.re_str = regex self.actions = [] if actions: self.actions = actions.split(",") self.next_state = next_state def Action(self, lexer): """Method is called when the token matches.""" class Error(Exception): """Module exception.""" class ParseError(Error): """A parse error occured.""" class Lexer(object): """A generic feed lexer.""" # A list of Token() instances. tokens = [] # Regex flags flags = 0 def __init__(self, data=""): # Set the lexer up to process a new data feed. self.Reset() # Populate internal token list with class tokens, if defined. self._tokens = self.tokens[:] # Populate the lexer with any data we got. self.buffer = utils.SmartStr(data) def Reset(self): """Reset the lexer to process a new data feed.""" # The first state self.state = "INITIAL" self.state_stack = [] # The buffer we are parsing now self.buffer = "" self.error = 0 self.verbose = 0 # The index into the buffer where we are currently pointing self.processed = 0 self.processed_buffer = "" def NextToken(self): """Fetch the next token by trying to match any of the regexes in order.""" # Nothing in the input stream - no token can match. if not self.buffer: return current_state = self.state for token in self._tokens: # Does the rule apply to us? if token.state_regex and not token.state_regex.match(current_state): continue if self.verbose: logging.debug("%s: Trying to match %r with %r", self.state, self.buffer[:10], token.re_str) # Try to match the rule m = token.regex.match(self.buffer) if not m: continue if self.verbose: logging.debug("%s matched %s", token.re_str, m.group(0)) # A token matched the empty string. We can not consume the token from the # input stream. if m.end() == 0: raise RuntimeError("Lexer bug! Token can not match the empty string.") # The match consumes the data off the buffer (the handler can put it back # if it likes) self.processed_buffer += self.buffer[:m.end()] self.buffer = self.buffer[m.end():] self.processed += m.end() next_state = token.next_state for action in token.actions: if self.verbose: logging.debug("Calling %s with %s", action, m.group(0)) # Is there a callback to handle this action? cb = getattr(self, action, self.Default) # Allow a callback to skip other callbacks. try: possible_next_state = cb(string=m.group(0), match=m) if possible_next_state == "CONTINUE": continue # Override the state from the Token elif possible_next_state: next_state = possible_next_state except ParseError as e: self.Error(e) # Update the next state if next_state: self.state = next_state return token # Check that we are making progress - if we are too full, we assume we are # stuck. self.Error("Lexer stuck at state %s" % (self.state)) self.processed_buffer += self.buffer[:1] self.buffer = self.buffer[1:] return "Error" def Feed(self, data): self.buffer += data def Empty(self): return not self.buffer def Default(self, **kwarg): logging.debug("Default handler: %s", kwarg) def Error(self, message=None, weight=1): logging.debug("Error(%s): %s", weight, message) # Keep a count of errors self.error += weight def PushState(self, **_): """Push the current state on the state stack.""" if self.verbose: logging.debug("Storing state %r", self.state) self.state_stack.append(self.state) def PopState(self, **_): """Pop the previous state from the stack.""" try: self.state = self.state_stack.pop() if self.verbose: logging.debug("Returned state to %s", self.state) return self.state except IndexError: self.Error("Tried to pop the state but failed - possible recursion error") def PushBack(self, string="", **_): """Push the match back on the stream.""" self.buffer = string + self.buffer self.processed_buffer = self.processed_buffer[:-len(string)] def Close(self): """A convenience function to force us to parse all the data.""" while self.NextToken(): if not self.buffer: return class SelfFeederMixIn(Lexer): """This mixin is used to make a lexer which feeds itself. Note that self.fd must be the fd we read from. """ def __init__(self, fd=""): self.fd = fd super(SelfFeederMixIn, self).__init__() def NextToken(self, end=True): # If we dont have enough data - feed ourselves: We assume # that we must have at least one sector in our buffer. if len(self.buffer) < 512: if self.Feed() == 0 and not self.buffer: return None return Lexer.next_token(self, end) def Feed(self, size=512): data = self.fd.read(size) Lexer.feed(self, data) return len(data) class Expression(object): """A class representing an expression.""" attribute = None args = None operator = None # The expected number of args number_of_args = 1 def __init__(self): self.args = [] def SetAttribute(self, attribute): self.attribute = attribute def SetOperator(self, operator): self.operator = operator def AddArg(self, arg): """Adds a new arg to this expression. Args: arg: The argument to add (string). Returns: True if this arg is the last arg, False otherwise. Raises: ParseError: If there are too many args. """ self.args.append(arg) if len(self.args) > self.number_of_args: raise ParseError("Too many args for this expression.") elif len(self.args) == self.number_of_args: return True return False def __str__(self): return "Expression: (%s) (%s) %s" % (self.attribute, self.operator, self.args) def PrintTree(self, depth=""): return "%s %s" % (depth, self) def Compile(self, filter_implemention): """Given a filter implementation, compile this expression.""" raise NotImplementedError( "%s does not implement Compile." % self.__class__.__name__) class BinaryExpression(Expression): """An expression which takes two other expressions.""" def __init__(self, operator="", part=None): self.operator = operator self.args = [] if part: self.args.append(part) super(BinaryExpression, self).__init__() def __str__(self): return "Binary Expression: %s %s" % (self.operator, [str(x) for x in self.args]) def AddOperands(self, lhs, rhs): if isinstance(lhs, Expression) and isinstance(rhs, Expression): self.args.insert(0, lhs) self.args.append(rhs) else: raise ParseError("Expected expression, got %s %s %s" % (lhs, self.operator, rhs)) def PrintTree(self, depth=""): result = "%s%s\n" % (depth, self.operator) for part in self.args: result += "%s-%s\n" % (depth, part.PrintTree(depth + " ")) return result def Compile(self, filter_implemention): """Compile the binary expression into a filter object.""" operator = self.operator.lower() if operator == "and" or operator == "&&": method = "AndFilter" elif operator == "or" or operator == "||": method = "OrFilter" else: raise ParseError("Invalid binary operator %s" % operator) args = [x.Compile(filter_implemention) for x in self.args] return filter_implemention.GetFilter(method)(*args) class IdentityExpression(Expression): """An Expression which always evaluates to True.""" def Compile(self, filter_implemention): return filter_implemention.IdentityFilter() class SearchParser(Lexer): """This parser can parse the mini query language and build an AST. Examples of valid syntax: filename contains "foo" and (size > 100k or date before "2011-10") date between 2011 and 2010 files older than 1 year """ expression_cls = Expression binary_expression_cls = BinaryExpression identity_expression_cls = IdentityExpression string = "" tokens = [ # Double quoted string Token("STRING", "\"", "PopState,StringFinish", None), Token("STRING", r"\\(.)", "StringEscape", None), Token("STRING", r"[^\\\"]+", "StringInsert", None), # Single quoted string Token("SQ_STRING", "'", "PopState,StringFinish", None), Token("SQ_STRING", r"\\(.)", "StringEscape", None), Token("SQ_STRING", r"[^\\']+", "StringInsert", None), # TODO(user): Implement a unary not operator. # The first thing we see in the initial state takes up to the ATTRIBUTE Token("INITIAL", r"(and|or|\&\&|\|\|)", "BinaryOperator", None), Token("INITIAL", r"[^\s\(\)]", "PushState,PushBack", "ATTRIBUTE"), Token("INITIAL", r"\(", "BracketOpen", None), Token("INITIAL", r"\)", "BracketClose", None), Token("ATTRIBUTE", r"[\w._0-9]+", "StoreAttribute", "OPERATOR"), Token("OPERATOR", r"[a-z0-9<>=\-\+\!\^\&%]+", "StoreOperator", "ARG_LIST"), Token("OPERATOR", "(!=|[<>=])", "StoreSpecialOperator", "ARG_LIST"), Token("ARG_LIST", r"[^\s'\"]+", "InsertArg", None), # Start a string. Token(".", "\"", "PushState,StringStart", "STRING"), Token(".", "'", "PushState,StringStart", "SQ_STRING"), # Skip whitespace. Token(".", r"\s+", None, None), ] def __init__(self, data): # Holds expression self.current_expression = self.expression_cls() self.filter_string = data # The token stack self.stack = [] Lexer.__init__(self, data) def BinaryOperator(self, string=None, **_): self.stack.append(self.binary_expression_cls(string)) def BracketOpen(self, **_): self.stack.append("(") def BracketClose(self, **_): self.stack.append(")") def StringStart(self, **_): self.string = "" def StringEscape(self, string, match, **_): """Escape backslashes found inside a string quote. Backslashes followed by anything other than ['"rnbt] will just be included in the string. Args: string: The string that matched. match: The match object (m.group(1) is the escaped code) """ if match.group(1) in "'\"rnbt": self.string += string.decode("string_escape") else: self.string += string def StringInsert(self, string="", **_): self.string += string def StringFinish(self, **_): if self.state == "ATTRIBUTE": return self.StoreAttribute(string=self.string) elif self.state == "ARG_LIST": return self.InsertArg(string=self.string) def StoreAttribute(self, string="", **_): if self.verbose: logging.debug("Storing attribute %r", string) # TODO(user): Update the expected number_of_args try: self.current_expression.SetAttribute(string) except AttributeError: raise ParseError("Invalid attribute '%s'" % string) return "OPERATOR" def StoreOperator(self, string="", **_): if self.verbose: logging.debug("Storing operator %r", string) self.current_expression.SetOperator(string) def InsertArg(self, string="", **_): """Insert an arg to the current expression.""" if self.verbose: logging.debug("Storing Argument %s", utils.SmartUnicode(string)) # This expression is complete if self.current_expression.AddArg(string): self.stack.append(self.current_expression) self.current_expression = self.expression_cls() return self.PopState() def _CombineBinaryExpressions(self, operator): for i in range(1, len(self.stack) - 1): item = self.stack[i] if (isinstance(item, BinaryExpression) and item.operator == operator and isinstance(self.stack[i - 1], Expression) and isinstance(self.stack[i + 1], Expression)): lhs = self.stack[i - 1] rhs = self.stack[i + 1] self.stack[i].AddOperands(lhs, rhs) self.stack[i - 1] = None self.stack[i + 1] = None self.stack = filter(None, self.stack) def _CombineParenthesis(self): for i in range(len(self.stack) - 2): if (self.stack[i] == "(" and self.stack[i + 2] == ")" and isinstance(self.stack[i + 1], Expression)): self.stack[i] = None self.stack[i + 2] = None self.stack = filter(None, self.stack) def Reduce(self): """Reduce the token stack into an AST.""" # Check for sanity if self.state != "INITIAL": self.Error("Premature end of expression") length = len(self.stack) while length > 1: # Precendence order self._CombineParenthesis() self._CombineBinaryExpressions("and") self._CombineBinaryExpressions("or") # No change if len(self.stack) == length: break length = len(self.stack) if length != 1: self.Error("Illegal query expression") return self.stack[0] def Error(self, message=None, weight=1): raise ParseError(u"%s in position %s: %s <----> %s )" % (utils.SmartUnicode(message), len(self.processed_buffer), self.processed_buffer, self.buffer)) def Parse(self): if not self.filter_string: return self.identity_expression_cls() self.Close() return self.Reduce()
28.991968
80
0.626333
import logging import re from grr.lib import utils class Token(object): state_regex = None def __init__(self, state_regex, regex, actions, next_state, flags=re.I): if state_regex: self.state_regex = re.compile(state_regex, re.DOTALL | re.M | re.S | re.U | flags) self.regex = re.compile(regex, re.DOTALL | re.M | re.S | re.U | flags) self.re_str = regex self.actions = [] if actions: self.actions = actions.split(",") self.next_state = next_state def Action(self, lexer): class Error(Exception): class ParseError(Error): class Lexer(object): tokens = [] flags = 0 def __init__(self, data=""): self.Reset() self._tokens = self.tokens[:] self.buffer = utils.SmartStr(data) def Reset(self): self.state = "INITIAL" self.state_stack = [] self.buffer = "" self.error = 0 self.verbose = 0 self.processed = 0 self.processed_buffer = "" def NextToken(self): if not self.buffer: return current_state = self.state for token in self._tokens: if token.state_regex and not token.state_regex.match(current_state): continue if self.verbose: logging.debug("%s: Trying to match %r with %r", self.state, self.buffer[:10], token.re_str) m = token.regex.match(self.buffer) if not m: continue if self.verbose: logging.debug("%s matched %s", token.re_str, m.group(0)) if m.end() == 0: raise RuntimeError("Lexer bug! Token can not match the empty string.") self.processed_buffer += self.buffer[:m.end()] self.buffer = self.buffer[m.end():] self.processed += m.end() next_state = token.next_state for action in token.actions: if self.verbose: logging.debug("Calling %s with %s", action, m.group(0)) cb = getattr(self, action, self.Default) try: possible_next_state = cb(string=m.group(0), match=m) if possible_next_state == "CONTINUE": continue elif possible_next_state: next_state = possible_next_state except ParseError as e: self.Error(e) if next_state: self.state = next_state return token self.Error("Lexer stuck at state %s" % (self.state)) self.processed_buffer += self.buffer[:1] self.buffer = self.buffer[1:] return "Error" def Feed(self, data): self.buffer += data def Empty(self): return not self.buffer def Default(self, **kwarg): logging.debug("Default handler: %s", kwarg) def Error(self, message=None, weight=1): logging.debug("Error(%s): %s", weight, message) self.error += weight def PushState(self, **_): if self.verbose: logging.debug("Storing state %r", self.state) self.state_stack.append(self.state) def PopState(self, **_): try: self.state = self.state_stack.pop() if self.verbose: logging.debug("Returned state to %s", self.state) return self.state except IndexError: self.Error("Tried to pop the state but failed - possible recursion error") def PushBack(self, string="", **_): self.buffer = string + self.buffer self.processed_buffer = self.processed_buffer[:-len(string)] def Close(self): while self.NextToken(): if not self.buffer: return class SelfFeederMixIn(Lexer): def __init__(self, fd=""): self.fd = fd super(SelfFeederMixIn, self).__init__() def NextToken(self, end=True): if len(self.buffer) < 512: if self.Feed() == 0 and not self.buffer: return None return Lexer.next_token(self, end) def Feed(self, size=512): data = self.fd.read(size) Lexer.feed(self, data) return len(data) class Expression(object): attribute = None args = None operator = None number_of_args = 1 def __init__(self): self.args = [] def SetAttribute(self, attribute): self.attribute = attribute def SetOperator(self, operator): self.operator = operator def AddArg(self, arg): self.args.append(arg) if len(self.args) > self.number_of_args: raise ParseError("Too many args for this expression.") elif len(self.args) == self.number_of_args: return True return False def __str__(self): return "Expression: (%s) (%s) %s" % (self.attribute, self.operator, self.args) def PrintTree(self, depth=""): return "%s %s" % (depth, self) def Compile(self, filter_implemention): raise NotImplementedError( "%s does not implement Compile." % self.__class__.__name__) class BinaryExpression(Expression): def __init__(self, operator="", part=None): self.operator = operator self.args = [] if part: self.args.append(part) super(BinaryExpression, self).__init__() def __str__(self): return "Binary Expression: %s %s" % (self.operator, [str(x) for x in self.args]) def AddOperands(self, lhs, rhs): if isinstance(lhs, Expression) and isinstance(rhs, Expression): self.args.insert(0, lhs) self.args.append(rhs) else: raise ParseError("Expected expression, got %s %s %s" % (lhs, self.operator, rhs)) def PrintTree(self, depth=""): result = "%s%s\n" % (depth, self.operator) for part in self.args: result += "%s-%s\n" % (depth, part.PrintTree(depth + " ")) return result def Compile(self, filter_implemention): operator = self.operator.lower() if operator == "and" or operator == "&&": method = "AndFilter" elif operator == "or" or operator == "||": method = "OrFilter" else: raise ParseError("Invalid binary operator %s" % operator) args = [x.Compile(filter_implemention) for x in self.args] return filter_implemention.GetFilter(method)(*args) class IdentityExpression(Expression): def Compile(self, filter_implemention): return filter_implemention.IdentityFilter() class SearchParser(Lexer): expression_cls = Expression binary_expression_cls = BinaryExpression identity_expression_cls = IdentityExpression string = "" tokens = [ Token("STRING", "\"", "PopState,StringFinish", None), Token("STRING", r"\\(.)", "StringEscape", None), Token("STRING", r"[^\\\"]+", "StringInsert", None), Token("SQ_STRING", "'", "PopState,StringFinish", None), Token("SQ_STRING", r"\\(.)", "StringEscape", None), Token("SQ_STRING", r"[^\\']+", "StringInsert", None), Token("INITIAL", r"(and|or|\&\&|\|\|)", "BinaryOperator", None), Token("INITIAL", r"[^\s\(\)]", "PushState,PushBack", "ATTRIBUTE"), Token("INITIAL", r"\(", "BracketOpen", None), Token("INITIAL", r"\)", "BracketClose", None), Token("ATTRIBUTE", r"[\w._0-9]+", "StoreAttribute", "OPERATOR"), Token("OPERATOR", r"[a-z0-9<>=\-\+\!\^\&%]+", "StoreOperator", "ARG_LIST"), Token("OPERATOR", "(!=|[<>=])", "StoreSpecialOperator", "ARG_LIST"), Token("ARG_LIST", r"[^\s'\"]+", "InsertArg", None), # Start a string. Token(".", "\"", "PushState,StringStart", "STRING"), Token(".", "'", "PushState,StringStart", "SQ_STRING"), Token(".", r"\s+", None, None), ] def __init__(self, data): self.current_expression = self.expression_cls() self.filter_string = data self.stack = [] Lexer.__init__(self, data) def BinaryOperator(self, string=None, **_): self.stack.append(self.binary_expression_cls(string)) def BracketOpen(self, **_): self.stack.append("(") def BracketClose(self, **_): self.stack.append(")") def StringStart(self, **_): self.string = "" def StringEscape(self, string, match, **_): if match.group(1) in "'\"rnbt": self.string += string.decode("string_escape") else: self.string += string def StringInsert(self, string="", **_): self.string += string def StringFinish(self, **_): if self.state == "ATTRIBUTE": return self.StoreAttribute(string=self.string) elif self.state == "ARG_LIST": return self.InsertArg(string=self.string) def StoreAttribute(self, string="", **_): if self.verbose: logging.debug("Storing attribute %r", string) # TODO(user): Update the expected number_of_args try: self.current_expression.SetAttribute(string) except AttributeError: raise ParseError("Invalid attribute '%s'" % string) return "OPERATOR" def StoreOperator(self, string="", **_): if self.verbose: logging.debug("Storing operator %r", string) self.current_expression.SetOperator(string) def InsertArg(self, string="", **_): if self.verbose: logging.debug("Storing Argument %s", utils.SmartUnicode(string)) # This expression is complete if self.current_expression.AddArg(string): self.stack.append(self.current_expression) self.current_expression = self.expression_cls() return self.PopState() def _CombineBinaryExpressions(self, operator): for i in range(1, len(self.stack) - 1): item = self.stack[i] if (isinstance(item, BinaryExpression) and item.operator == operator and isinstance(self.stack[i - 1], Expression) and isinstance(self.stack[i + 1], Expression)): lhs = self.stack[i - 1] rhs = self.stack[i + 1] self.stack[i].AddOperands(lhs, rhs) self.stack[i - 1] = None self.stack[i + 1] = None self.stack = filter(None, self.stack) def _CombineParenthesis(self): for i in range(len(self.stack) - 2): if (self.stack[i] == "(" and self.stack[i + 2] == ")" and isinstance(self.stack[i + 1], Expression)): self.stack[i] = None self.stack[i + 2] = None self.stack = filter(None, self.stack) def Reduce(self): # Check for sanity if self.state != "INITIAL": self.Error("Premature end of expression") length = len(self.stack) while length > 1: # Precendence order self._CombineParenthesis() self._CombineBinaryExpressions("and") self._CombineBinaryExpressions("or") # No change if len(self.stack) == length: break length = len(self.stack) if length != 1: self.Error("Illegal query expression") return self.stack[0] def Error(self, message=None, weight=1): raise ParseError(u"%s in position %s: %s <----> %s )" % (utils.SmartUnicode(message), len(self.processed_buffer), self.processed_buffer, self.buffer)) def Parse(self): if not self.filter_string: return self.identity_expression_cls() self.Close() return self.Reduce()
true
true
f72c5f21b10b223a9ba7876395cff13950f436cd
5,375
py
Python
hw2skeleton/k_means.py
egilbertson-ucsf/algHW2
eec0f4e42e27d4c7633cc907d6f523285fadd79c
[ "Apache-2.0" ]
1
2022-02-07T21:00:46.000Z
2022-02-07T21:00:46.000Z
hw2skeleton/k_means.py
egilbertson-ucsf/algHW2
eec0f4e42e27d4c7633cc907d6f523285fadd79c
[ "Apache-2.0" ]
null
null
null
hw2skeleton/k_means.py
egilbertson-ucsf/algHW2
eec0f4e42e27d4c7633cc907d6f523285fadd79c
[ "Apache-2.0" ]
null
null
null
from hw2skeleton import cluster as cl from hw2skeleton import io import sklearn.metrics as sk import os import pandas as pd import numpy as np import math aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split() aa_df = pd.DataFrame(0, index=list(aa3), columns=['Count']) def calc_avg_site_length(sites): ''' calculate the average size of an active site for use in generating random sites ''' ss = [] for site in sites: ss.append(len(site.residues)) return [sum(ss) / len(sites), max(ss), min(ss)] def generate_random_site(sites): ''' generate a random site by filling in a 1x20 vector repr of amino acids with counts ''' lens = calc_avg_site_length(sites) num_res = np.random.randint(lens[2],lens[1]) site = aa_df.copy() for pos in range(num_res): aa = np.random.randint(0,19) site.iloc[aa] += 1 return site def generate_k_random_centroids(k, sites): ''' generate k random sites using above function ''' centroids = {} for i in range(k): centroids[i] = generate_random_site(sites) return centroids def assign_single_site_to_cluster(site, centroids): ''' check which cluster centroid is closest to the given site and assign the site to that cluster ''' loc = site.counts dists = {} for c in centroids.keys(): dist = cl.compute_similarity(loc, centroids[c]) dists[dist] = c closest = dists[min(dists.keys())] return closest def assign_all_sites_to_cluster(sites, centroids, clusters): ''' loop through all sites and assign them to the appropriate clusters ''' for site in sites: close = assign_single_site_to_cluster(site, centroids) if close not in clusters: clusters[close] = [site] else: clusters[close].append(site) for cent in centroids: if cent not in clusters: clusters[cent] = [] return clusters def compute_cluster_center(cluster_list, sites_dict): ''' compute the center of a cluster by taking the average of the vector representations of all sites in the cluster ''' sites = aa_df.copy() for j in cluster_list: if isinstance(j, str): sites += sites_dict[j].counts else: sites += j.counts return sites / len(sites) def get_new_centroids(clusters, sites_dict=None): ''' use the compute_cluster_center function to get the new centroids after updating assignments ''' centroids = {} for cluster in clusters.keys(): centroids[cluster] = compute_cluster_center(clusters[cluster], sites_dict) return centroids def check_change_in_centroids(old_centroids, new_centroids): ''' check how far the centroids have moved ''' diff = 0 for c in old_centroids.keys(): diff += cl.compute_similarity(old_centroids[c], new_centroids[c]) return diff def one_full_k_means(sites, k): ''' using all above functions, one full iteration of k means''' centroids = generate_k_random_centroids(k, sites) clusters = {} clusters = assign_all_sites_to_cluster(sites, centroids, clusters) new_centroids = get_new_centroids(clusters) old_diff = check_change_in_centroids(centroids, new_centroids) new_diff = 0 while old_diff - new_diff > 0.00001: old_diff = check_change_in_centroids(centroids, new_centroids) centroids = new_centroids.copy() clusters = {} clusters = assign_all_sites_to_cluster(sites, centroids, clusters) new_centroids = get_new_centroids(clusters) new_diff = check_change_in_centroids(centroids, new_centroids) return clusters, centroids def compute_similarity_matrix(sites): ''' copy of computer similarity matrix from utils ''' simMat = [] names = [] for i in range(len(sites)): names.append(sites[i].name) row = [] for j in range(len(sites)): row.append(cl.compute_similarity(sites[i].counts,sites[j].counts)) simMat.append(row) simMat = pd.DataFrame(simMat, columns = names, index = names) return simMat def make_cluster_assign_df(clusters, simMat): ''' make a nice df repr of the cluster assignments''' assgn = pd.DataFrame(index = simMat.index, columns = ['Cluster Assignment']) for cluster in clusters.keys(): for site in clusters[cluster]: assgn.loc[site.name] = cluster return assgn def avg_sl(sites, k, simMat): ''' average silhouette_score for i random starts of k means for k clusters''' scores = [] c_list = [] for i in range(1): clusters, centroids = one_full_k_means(sites, k) assgn = make_cluster_assign_df(clusters, simMat) c_list.append(clusters) scores.append(sk.silhouette_score(simMat, assgn['Cluster Assignment'], metric='precomputed')) return scores, clusters def k_means(sites=None): ''' run k means ''' sites = io.read_active_sites('data') simMat = compute_similarity_matrix(sites) points = [[],[]] clusters = [] for i in range(2,5): points[0].append(i) temp = avg_sl(sites, i , simMat) points[1].append(temp[0]) clusters.append(temp[1]) return clusters[points[1].index(max(points[1]))], max(points[1])
31.25
101
0.661767
from hw2skeleton import cluster as cl from hw2skeleton import io import sklearn.metrics as sk import os import pandas as pd import numpy as np import math aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split() aa_df = pd.DataFrame(0, index=list(aa3), columns=['Count']) def calc_avg_site_length(sites): ss = [] for site in sites: ss.append(len(site.residues)) return [sum(ss) / len(sites), max(ss), min(ss)] def generate_random_site(sites): lens = calc_avg_site_length(sites) num_res = np.random.randint(lens[2],lens[1]) site = aa_df.copy() for pos in range(num_res): aa = np.random.randint(0,19) site.iloc[aa] += 1 return site def generate_k_random_centroids(k, sites): centroids = {} for i in range(k): centroids[i] = generate_random_site(sites) return centroids def assign_single_site_to_cluster(site, centroids): loc = site.counts dists = {} for c in centroids.keys(): dist = cl.compute_similarity(loc, centroids[c]) dists[dist] = c closest = dists[min(dists.keys())] return closest def assign_all_sites_to_cluster(sites, centroids, clusters): for site in sites: close = assign_single_site_to_cluster(site, centroids) if close not in clusters: clusters[close] = [site] else: clusters[close].append(site) for cent in centroids: if cent not in clusters: clusters[cent] = [] return clusters def compute_cluster_center(cluster_list, sites_dict): sites = aa_df.copy() for j in cluster_list: if isinstance(j, str): sites += sites_dict[j].counts else: sites += j.counts return sites / len(sites) def get_new_centroids(clusters, sites_dict=None): centroids = {} for cluster in clusters.keys(): centroids[cluster] = compute_cluster_center(clusters[cluster], sites_dict) return centroids def check_change_in_centroids(old_centroids, new_centroids): diff = 0 for c in old_centroids.keys(): diff += cl.compute_similarity(old_centroids[c], new_centroids[c]) return diff def one_full_k_means(sites, k): centroids = generate_k_random_centroids(k, sites) clusters = {} clusters = assign_all_sites_to_cluster(sites, centroids, clusters) new_centroids = get_new_centroids(clusters) old_diff = check_change_in_centroids(centroids, new_centroids) new_diff = 0 while old_diff - new_diff > 0.00001: old_diff = check_change_in_centroids(centroids, new_centroids) centroids = new_centroids.copy() clusters = {} clusters = assign_all_sites_to_cluster(sites, centroids, clusters) new_centroids = get_new_centroids(clusters) new_diff = check_change_in_centroids(centroids, new_centroids) return clusters, centroids def compute_similarity_matrix(sites): simMat = [] names = [] for i in range(len(sites)): names.append(sites[i].name) row = [] for j in range(len(sites)): row.append(cl.compute_similarity(sites[i].counts,sites[j].counts)) simMat.append(row) simMat = pd.DataFrame(simMat, columns = names, index = names) return simMat def make_cluster_assign_df(clusters, simMat): assgn = pd.DataFrame(index = simMat.index, columns = ['Cluster Assignment']) for cluster in clusters.keys(): for site in clusters[cluster]: assgn.loc[site.name] = cluster return assgn def avg_sl(sites, k, simMat): scores = [] c_list = [] for i in range(1): clusters, centroids = one_full_k_means(sites, k) assgn = make_cluster_assign_df(clusters, simMat) c_list.append(clusters) scores.append(sk.silhouette_score(simMat, assgn['Cluster Assignment'], metric='precomputed')) return scores, clusters def k_means(sites=None): sites = io.read_active_sites('data') simMat = compute_similarity_matrix(sites) points = [[],[]] clusters = [] for i in range(2,5): points[0].append(i) temp = avg_sl(sites, i , simMat) points[1].append(temp[0]) clusters.append(temp[1]) return clusters[points[1].index(max(points[1]))], max(points[1])
true
true
f72c5fd356bc70a6fedc8a393b6f0f7e3a5126db
3,817
py
Python
zester/client.py
Rahul09123/zester
e878ba5ce66156a642bc7513a69dc4175f9393be
[ "ISC" ]
10
2015-10-17T16:12:30.000Z
2021-12-09T04:08:47.000Z
zester/client.py
Rahul09123/zester
e878ba5ce66156a642bc7513a69dc4175f9393be
[ "ISC" ]
null
null
null
zester/client.py
Rahul09123/zester
e878ba5ce66156a642bc7513a69dc4175f9393be
[ "ISC" ]
2
2020-05-05T04:04:28.000Z
2020-09-30T14:19:16.000Z
from collections import namedtuple import inspect import os from ghost import Ghost class Client(object): def __init__(self, url=None): if url: self.url = url assert self.url, "All clients must have a URL attribute" self._attributes = self._collect_attributes() self._class_model = self._setup_class_model() self._ghost = Ghost() def process(self): self._load_ghost() attribute_results = self._process_attributes() self._object_results = self._make_objects(attribute_results) return self._object_results def _setup_class_model(self): class_name = self.__class__.__name__ return namedtuple(class_name + "Response", self._attributes.keys()) def _process_attributes(self): results = [] for attribute_name, attribute in self._attributes.iteritems(): result, resources = self._ghost.evaluate(attribute.query) # If a node was selected, return it's data if isinstance(result, dict): if 'data' in result: result = result['data'] elif 'selector' in result: raise TypeError("The attribute {} returned a selector" " instead of a node.".format(attribute_name)) results.append(result) return results def _make_objects(self, attribute_results): raise NotImplementedError() def _collect_attributes(self): attrs = [(attr_name, attr) for (attr_name, attr) in inspect.getmembers(self) if isinstance(attr, Attribute)] return dict(attrs) def _load_ghost(self): page, extra_resources = self._ghost.open(self.url) # For local testing, page is None if page: # TODO should error better assert page.http_status < 400 # Load jquery jquery_path = os.path.join(os.path.abspath(os.curdir), 'zester', 'fixtures', 'jquery.min.js') jquery_text = open(jquery_path, 'r').read() result, resources = self._ghost.evaluate(jquery_text) class MultipleClient(Client): def _process_attributes(self): results = super(MultipleClient, self)._process_attributes() if not results: return results zipped_results = zip(*results) return zipped_results def _make_objects(self, attribute_results): object_results = [] attribute_names = self._attributes.keys() for attribute_result in attribute_results: result_dict = dict(zip(attribute_names, attribute_result)) object_results.append(self._class_model(**result_dict)) return object_results class SingleClient(Client): def _process_attributes(self): result = super(SingleClient, self)._process_attributes() number_of_attributes = len(self._attributes) if len(result) > number_of_attributes: # If we found more attributes than we were looking for result = result[:number_of_attributes] return result def _make_objects(self, attribute_result): attribute_names = self._attributes.keys() result_dict = dict(zip(attribute_names, attribute_result)) object_result = self._class_model(**result_dict) return object_result class Attribute(object): def __init__(self, selector, modifier=None): self.selector = selector self.modifier = modifier @property def query(self): if self.modifier: # Escaping braces in here base = "$.map({selector}, function(el){{ return {modifier}}});" return base.format(selector=self.selector, modifier=self.modifier) else: return self.selector
34.387387
78
0.637674
from collections import namedtuple import inspect import os from ghost import Ghost class Client(object): def __init__(self, url=None): if url: self.url = url assert self.url, "All clients must have a URL attribute" self._attributes = self._collect_attributes() self._class_model = self._setup_class_model() self._ghost = Ghost() def process(self): self._load_ghost() attribute_results = self._process_attributes() self._object_results = self._make_objects(attribute_results) return self._object_results def _setup_class_model(self): class_name = self.__class__.__name__ return namedtuple(class_name + "Response", self._attributes.keys()) def _process_attributes(self): results = [] for attribute_name, attribute in self._attributes.iteritems(): result, resources = self._ghost.evaluate(attribute.query) if isinstance(result, dict): if 'data' in result: result = result['data'] elif 'selector' in result: raise TypeError("The attribute {} returned a selector" " instead of a node.".format(attribute_name)) results.append(result) return results def _make_objects(self, attribute_results): raise NotImplementedError() def _collect_attributes(self): attrs = [(attr_name, attr) for (attr_name, attr) in inspect.getmembers(self) if isinstance(attr, Attribute)] return dict(attrs) def _load_ghost(self): page, extra_resources = self._ghost.open(self.url) # For local testing, page is None if page: # TODO should error better assert page.http_status < 400 # Load jquery jquery_path = os.path.join(os.path.abspath(os.curdir), 'zester', 'fixtures', 'jquery.min.js') jquery_text = open(jquery_path, 'r').read() result, resources = self._ghost.evaluate(jquery_text) class MultipleClient(Client): def _process_attributes(self): results = super(MultipleClient, self)._process_attributes() if not results: return results zipped_results = zip(*results) return zipped_results def _make_objects(self, attribute_results): object_results = [] attribute_names = self._attributes.keys() for attribute_result in attribute_results: result_dict = dict(zip(attribute_names, attribute_result)) object_results.append(self._class_model(**result_dict)) return object_results class SingleClient(Client): def _process_attributes(self): result = super(SingleClient, self)._process_attributes() number_of_attributes = len(self._attributes) if len(result) > number_of_attributes: # If we found more attributes than we were looking for result = result[:number_of_attributes] return result def _make_objects(self, attribute_result): attribute_names = self._attributes.keys() result_dict = dict(zip(attribute_names, attribute_result)) object_result = self._class_model(**result_dict) return object_result class Attribute(object): def __init__(self, selector, modifier=None): self.selector = selector self.modifier = modifier @property def query(self): if self.modifier: # Escaping braces in here base = "$.map({selector}, function(el){{ return {modifier}}});" return base.format(selector=self.selector, modifier=self.modifier) else: return self.selector
true
true
f72c603dfc8ecbd5f63c67e5d3ff1d9b9f2bae6b
662
py
Python
rotateMatrix90/rotMat90.py
lowylow/InterviewQuestions
e267a601ff336b0a2a581db4ae985283a29fed51
[ "MIT" ]
null
null
null
rotateMatrix90/rotMat90.py
lowylow/InterviewQuestions
e267a601ff336b0a2a581db4ae985283a29fed51
[ "MIT" ]
null
null
null
rotateMatrix90/rotMat90.py
lowylow/InterviewQuestions
e267a601ff336b0a2a581db4ae985283a29fed51
[ "MIT" ]
null
null
null
def rotate90acw(matrix): outMatrix = [] for x in range(len(matrix)): outArray = [] for y in range(len(matrix)): outArray.append(matrix[len(matrix)-1-y][len(matrix)-1-x]) outMatrix.append(outArray[::-1]) return outMatrix def rotate90cw(matrix): outMatrix = [] for x in range(len(matrix)): outArray = [] for y in range(len(matrix)): outArray.append(matrix[y][x]) outMatrix.append(outArray[::-1]) return outMatrix Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(rotate90cw(Matrix))
23.642857
70
0.5
def rotate90acw(matrix): outMatrix = [] for x in range(len(matrix)): outArray = [] for y in range(len(matrix)): outArray.append(matrix[len(matrix)-1-y][len(matrix)-1-x]) outMatrix.append(outArray[::-1]) return outMatrix def rotate90cw(matrix): outMatrix = [] for x in range(len(matrix)): outArray = [] for y in range(len(matrix)): outArray.append(matrix[y][x]) outMatrix.append(outArray[::-1]) return outMatrix Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(rotate90cw(Matrix))
true
true
f72c60682595bfbd3fa6b5191c70b2cc02dd5f4c
36,930
py
Python
tests/hwsim/test_owe.py
cschuber/hostap
b26f5c0fe35cd0472ea43f533b981ac2d91cdf1f
[ "Unlicense" ]
21
2018-11-25T17:42:48.000Z
2021-12-17T11:04:56.000Z
tests/hwsim/test_owe.py
cschuber/hostap
b26f5c0fe35cd0472ea43f533b981ac2d91cdf1f
[ "Unlicense" ]
3
2017-08-11T16:48:19.000Z
2020-03-10T21:18:17.000Z
tests/hwsim/test_owe.py
cschuber/hostap
b26f5c0fe35cd0472ea43f533b981ac2d91cdf1f
[ "Unlicense" ]
18
2015-03-11T07:09:31.000Z
2022-03-25T08:29:18.000Z
# Test cases for Opportunistic Wireless Encryption (OWE) # Copyright (c) 2017, Jouni Malinen <j@w1.fi> # # This software may be distributed under the terms of the BSD license. # See README for more details. import binascii import logging logger = logging.getLogger() import time import os import struct import hostapd from wpasupplicant import WpaSupplicant import hwsim_utils from tshark import run_tshark from utils import HwsimSkip, fail_test, alloc_fail, wait_fail_trigger from test_ap_acs import wait_acs def test_owe(dev, apdev): """Opportunistic Wireless Encryption""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() conf = hapd.request("GET_CONFIG") if "key_mgmt=OWE" not in conf.splitlines(): logger.info("GET_CONFIG:\n" + conf) raise Exception("GET_CONFIG did not report correct key_mgmt") dev[0].scan_for_bss(bssid, freq="2412") bss = dev[0].get_bss(bssid) if "[WPA2-OWE-CCMP]" not in bss['flags']: raise Exception("OWE AKM not recognized: " + bss['flags']) id = dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") hapd.wait_sta() pmk_h = hapd.request("GET_PMK " + dev[0].own_addr()) pmk_w = dev[0].get_pmk(id) if pmk_h != pmk_w: raise Exception("Fetched PMK does not match: hostapd %s, wpa_supplicant %s" % (pmk_h, pmk_w)) hwsim_utils.test_connectivity(dev[0], hapd) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_groups(dev, apdev): """Opportunistic Wireless Encryption - DH groups""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") for group in [19, 20, 21]: dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group)) hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) dev[0].request("REMOVE_NETWORK all") dev[0].wait_disconnected() dev[0].dump_monitor() hapd.dump_monitor() def test_owe_pmksa_caching(dev, apdev): """Opportunistic Wireless Encryption and PMKSA caching""" try: run_owe_pmksa_caching(dev, apdev) finally: dev[0].set("reassoc_same_bss_optim", "0") def test_owe_pmksa_caching_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption and PMKSA caching using cfg80211 connect command""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") try: run_owe_pmksa_caching([wpas], apdev) finally: wpas.set("reassoc_same_bss_optim", "0") def run_owe_pmksa_caching(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].set("reassoc_same_bss_optim", "1") dev[0].scan_for_bss(bssid, freq="2412") id = dev[0].connect("owe", key_mgmt="OWE") hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) pmksa = dev[0].get_pmksa(bssid) dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].dump_monitor() dev[0].select_network(id, 2412) dev[0].wait_connected() hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) pmksa2 = dev[0].get_pmksa(bssid) dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].dump_monitor() if "OK" not in hapd.request("PMKSA_FLUSH"): raise Exception("PMKSA_FLUSH failed") dev[0].select_network(id, 2412) dev[0].wait_connected() hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) pmksa3 = dev[0].get_pmksa(bssid) if pmksa is None or pmksa2 is None or pmksa3 is None: raise Exception("PMKSA entry missing") if pmksa['pmkid'] != pmksa2['pmkid']: raise Exception("Unexpected PMKID change when using PMKSA caching") if pmksa['pmkid'] == pmksa3['pmkid']: raise Exception("PMKID did not change after PMKSA cache flush") dev[0].request("REASSOCIATE") dev[0].wait_connected() pmksa4 = dev[0].get_pmksa(bssid) if pmksa3['pmkid'] != pmksa4['pmkid']: raise Exception("Unexpected PMKID change when using PMKSA caching [2]") def test_owe_and_psk(dev, apdev): """Opportunistic Wireless Encryption and WPA2-PSK enabled""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe+psk", "wpa": "2", "wpa_key_mgmt": "OWE WPA-PSK", "rsn_pairwise": "CCMP", "wpa_passphrase": "12345678"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe+psk", psk="12345678") hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) dev[1].scan_for_bss(bssid, freq="2412") dev[1].connect("owe+psk", key_mgmt="OWE") hapd.wait_sta() hwsim_utils.test_connectivity(dev[1], hapd) def test_owe_transition_mode(dev, apdev): """Opportunistic Wireless Encryption transition mode""" run_owe_transition_mode(dev, apdev) def test_owe_transition_mode_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption transition mode using cfg80211 connect command""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_transition_mode([wpas], apdev) def test_owe_transition_mode_mismatch1(dev, apdev): """Opportunistic Wireless Encryption transition mode (mismatch 1)""" run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55") def test_owe_transition_mode_mismatch2(dev, apdev): """Opportunistic Wireless Encryption transition mode (mismatch 2)""" run_owe_transition_mode(dev, apdev, adv_bssid1="02:11:22:33:44:66") def test_owe_transition_mode_mismatch3(dev, apdev): """Opportunistic Wireless Encryption transition mode (mismatch 3)""" run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55", adv_bssid1="02:11:22:33:44:66") def run_owe_transition_mode(dev, apdev, adv_bssid0=None, adv_bssid1=None): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() adv_bssid = adv_bssid0 if adv_bssid0 else apdev[1]['bssid'] params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_bssid": adv_bssid, "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() adv_bssid = adv_bssid1 if adv_bssid1 else apdev[0]['bssid'] params = {"ssid": "owe-test", "owe_transition_bssid": adv_bssid, "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") bss = dev[0].get_bss(bssid) if "[WPA2-OWE-CCMP]" not in bss['flags']: raise Exception("OWE AKM not recognized: " + bss['flags']) if "[OWE-TRANS]" not in bss['flags']: raise Exception("OWE transition not recognized: " + bss['flags']) bss = dev[0].get_bss(bssid2) if "[OWE-TRANS-OPEN]" not in bss['flags']: raise Exception("OWE transition (open) not recognized: " + bss['flags']) id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) logger.info("Move to OWE only mode (disable transition mode)") dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].dump_monitor() hapd2.disable() hapd.disable() dev[0].flush_scan_cache() hapd.set("owe_transition_bssid", "00:00:00:00:00:00") hapd.set("ignore_broadcast_ssid", '0') hapd.set("ssid", 'owe-test') hapd.enable() dev[0].scan_for_bss(bssid, freq="2412") dev[0].select_network(id, 2412) dev[0].wait_connected() hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) def test_owe_transition_mode_ifname(dev, apdev): """Opportunistic Wireless Encryption transition mode (ifname)""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_ifname": apdev[1]['ifname'], "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() params = {"ssid": "owe-test", "owe_transition_ifname": apdev[0]['ifname']} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_transition_mode_ifname_acs(dev, apdev): """Opportunistic Wireless Encryption transition mode (ifname, ACS)""" run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=False) def test_owe_transition_mode_ifname_acs2(dev, apdev): """Opportunistic Wireless Encryption transition mode (ifname, ACS)""" run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=True) def run_owe_transition_mode_ifname_acs(dev, apdev, wait_first): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "channel": "0", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_ifname": apdev[1]['ifname'], "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params, wait_enabled=False) bssid = hapd.own_addr() if wait_first: wait_acs(hapd) params = {"ssid": "owe-test", "channel": "0", "owe_transition_ifname": apdev[0]['ifname']} hapd2 = hostapd.add_ap(apdev[1], params, wait_enabled=False) bssid2 = hapd2.own_addr() wait_acs(hapd2) if not wait_first: state = hapd.get_status_field("state") if state == "ACS-STARTED": time.sleep(5) state = hapd.get_status_field("state") if state != "ENABLED": raise Exception("AP1 startup did not succeed") freq = hapd.get_status_field("freq") freq2 = hapd2.get_status_field("freq") dev[0].scan_for_bss(bssid, freq=freq) dev[0].scan_for_bss(bssid2, freq=freq2) id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="%s %s" % (freq, freq2)) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_transition_mode_open_only_ap(dev, apdev): """Opportunistic Wireless Encryption transition mode connect to open-only AP""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-test-open"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") bss = dev[0].get_bss(bssid) id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") hwsim_utils.test_connectivity(dev[0], hapd) val = dev[0].get_status_field("key_mgmt") if val != "NONE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_only_sta(dev, apdev): """Opportunistic Wireless Encryption transition mode disabled on STA""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-test-open"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2", scan_freq="2412", owe_only="1", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10) if not ev: raise Exception("Unknown result for the connection attempt") if "CTRL-EVENT-CONNECTED" in ev: raise Exception("Unexpected connection to open network") dev[0].request("DISCONNECT") dev[0].dump_monitor() params = {"ssid": "owe-test-open", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd2 = hostapd.add_ap(apdev[1], params) dev[0].request("RECONNECT") dev[0].wait_connected() def test_owe_transition_mode_open_multiple_scans(dev, apdev): """Opportunistic Wireless Encryption transition mode and need for multiple scans""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-test", "owe_transition_bssid": apdev[0]['bssid'], "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid2, freq="2412") dev[0].dump_monitor() id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=1) params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_bssid": apdev[1]['bssid'], "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].wait_connected() val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_transition_mode_multi_bss(dev, apdev): """Opportunistic Wireless Encryption transition mode (multi BSS)""" try: run_owe_transition_mode_multi_bss(dev, apdev) finally: dev[0].request("SCAN_INTERVAL 5") def run_owe_transition_mode_multi_bss(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") ifname1 = apdev[0]['ifname'] ifname2 = apdev[0]['ifname'] + '-2' hapd1 = hostapd.add_bss(apdev[0], ifname1, 'owe-bss-1.conf') hapd2 = hostapd.add_bss(apdev[0], ifname2, 'owe-bss-2.conf') hapd2.bssidx = 1 bssid = hapd1.own_addr() bssid2 = hapd2.own_addr() # Beaconing with the OWE Transition Mode element can start only once both # BSSs are enabled, so the very first Beacon frame may go out without this # element. Wait a bit to avoid getting incomplete scan results. time.sleep(0.1) dev[0].request("SCAN_INTERVAL 1") dev[0].scan_for_bss(bssid2, freq="2412") dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("transition-mode-open", key_mgmt="OWE") val = dev[0].get_status_field("bssid") if val != bssid2: raise Exception("Unexpected bssid: " + val) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) hwsim_utils.test_connectivity(dev[0], hapd2) def test_owe_transition_mode_rsne_mismatch(dev, apdev): """Opportunistic Wireless Encryption transition mode and RSNE mismatch""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "rsne_override_eapol": "30140100000fac040100000fac040100000fac020c00", "owe_transition_bssid": apdev[1]['bssid'], "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() params = {"ssid": "owe-test", "owe_transition_bssid": apdev[0]['bssid'], "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=5) if ev is None: raise Exception("OWE PMKSA not created") ev = dev[0].wait_event(["WPA: IE in 3/4 msg does not match with IE in Beacon/ProbeResp"], timeout=5) if ev is None: raise Exception("RSNE mismatch not reported") ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "CTRL-EVENT-DISCONNECTED"], timeout=5) dev[0].request("REMOVE_NETWORK all") if ev is None: raise Exception("No disconnection seen") if "CTRL-EVENT-DISCONNECTED" not in ev: raise Exception("Unexpected connection") if "reason=17 locally_generated=1" not in ev: raise Exception("Unexpected disconnection reason: " + ev) def test_owe_unsupported_group(dev, apdev): """Opportunistic Wireless Encryption and unsupported group""" try: run_owe_unsupported_group(dev, apdev) finally: dev[0].request("VENDOR_ELEM_REMOVE 13 *") def test_owe_unsupported_group_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption and unsupported group using cfg80211 connect command""" try: wpas = None wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_unsupported_group([wpas], apdev) finally: if wpas: wpas.request("VENDOR_ELEM_REMOVE 13 *") def run_owe_unsupported_group(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") # Override OWE Dh Parameters element with a payload that uses invalid group # 0 (and actual group 19 data) to make the AP reject this with the specific # status code 77. dev[0].request("VENDOR_ELEM_ADD 13 ff23200000783590fb7440e03d5b3b33911f86affdcc6b4411b707846ac4ff08ddc8831ccd") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason: " + ev) def test_owe_limited_group_set(dev, apdev): """Opportunistic Wireless Encryption and limited group set""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "20 21"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", owe_group="19", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason: " + ev) dev[0].dump_monitor() for group in [20, 21]: dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group)) dev[0].request("REMOVE_NETWORK all") dev[0].wait_disconnected() dev[0].dump_monitor() def test_owe_limited_group_set_pmf(dev, apdev, params): """Opportunistic Wireless Encryption and limited group set (PMF)""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") pcapng = os.path.join(params['logdir'], "hwsim0.pcapng") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "21"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason: " + ev) dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected (2)") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason (2): " + ev) dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="21", ieee80211w="2", scan_freq="2412") dev[0].request("REMOVE_NETWORK all") dev[0].wait_disconnected() dev[0].dump_monitor() out = run_tshark(pcapng, "wlan.fc.type_subtype == 1", display=['wlan_mgt.fixed.status_code']) status = out.splitlines() logger.info("Association Response frame status codes: " + str(status)) if len(status) != 3: raise Exception("Unexpected number of Association Response frames") if (int(status[0], base=0) != 77 or int(status[1], base=0) != 77 or int(status[2], base=0) != 0): raise Exception("Unexpected Association Response frame status code") def test_owe_group_negotiation(dev, apdev): """Opportunistic Wireless Encryption and group negotiation""" run_owe_group_negotiation(dev[0], apdev) def test_owe_group_negotiation_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption and group negotiation (connect command)""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_group_negotiation(wpas, apdev) def run_owe_group_negotiation(dev, apdev): if "OWE" not in dev.get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "21"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev.scan_for_bss(bssid, freq="2412") dev.connect("owe", key_mgmt="OWE") def test_owe_assoc_reject(dev, apdev): """Opportunistic Wireless Encryption association rejection handling""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "require_ht": "1", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "19"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() # First, reject two associations with HT-required (i.e., not OWE related) dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", disable_ht="1", scan_freq="2412", wait_connect=False) for i in range(0, 2): ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) if ev is None: raise Exception("Association rejection not reported") # Then, verify that STA tries OWE with the default group (19) on the next # attempt instead of having moved to testing another group. hapd.set("require_ht", "0") for i in range(0, 2): ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT", "CTRL-EVENT-CONNECTED"], timeout=10) if ev is None: raise Exception("Association result not reported") if "CTRL-EVENT-CONNECTED" in ev: break if "status_code=77" in ev: raise Exception("Unexpected unsupport group rejection") if "CTRL-EVENT-CONNECTED" not in ev: raise Exception("Did not connect successfully") def test_owe_local_errors(dev, apdev): """Opportunistic Wireless Encryption - local errors on supplicant""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") tests = [(1, "crypto_ecdh_init;owe_build_assoc_req"), (1, "crypto_ecdh_get_pubkey;owe_build_assoc_req"), (1, "wpabuf_alloc;owe_build_assoc_req")] for count, func in tests: with alloc_fail(dev[0], count, func): dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2", scan_freq="2412", wait_connect=False) wait_fail_trigger(dev[0], "GET_ALLOC_FAIL") dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() tests = [(1, "crypto_ecdh_set_peerkey;owe_process_assoc_resp"), (1, "crypto_ecdh_get_pubkey;owe_process_assoc_resp"), (1, "wpabuf_alloc;=owe_process_assoc_resp")] for count, func in tests: with alloc_fail(dev[0], count, func): dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2", scan_freq="2412", wait_connect=False) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() tests = [(1, "hmac_sha256;owe_process_assoc_resp", 19), (1, "hmac_sha256_kdf;owe_process_assoc_resp", 19), (1, "hmac_sha384;owe_process_assoc_resp", 20), (1, "hmac_sha384_kdf;owe_process_assoc_resp", 20), (1, "hmac_sha512;owe_process_assoc_resp", 21), (1, "hmac_sha512_kdf;owe_process_assoc_resp", 21)] for count, func, group in tests: with fail_test(dev[0], count, func): dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group), ieee80211w="2", scan_freq="2412", wait_connect=False) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="18", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=5) if ev is None: raise Exception("No authentication attempt") time.sleep(0.5) dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() def hapd_auth(hapd): for i in range(0, 10): req = hapd.mgmt_rx() if req is None: raise Exception("MGMT RX wait timed out") if req['subtype'] == 11: break req = None if not req: raise Exception("Authentication frame not received") resp = {} resp['fc'] = req['fc'] resp['da'] = req['sa'] resp['sa'] = req['da'] resp['bssid'] = req['bssid'] resp['payload'] = struct.pack('<HHH', 0, 2, 0) hapd.mgmt_tx(resp) def hapd_assoc(hapd, extra): for i in range(0, 10): req = hapd.mgmt_rx() if req is None: raise Exception("MGMT RX wait timed out") if req['subtype'] == 0: break req = None if not req: raise Exception("Association Request frame not received") resp = {} resp['fc'] = 0x0010 resp['da'] = req['sa'] resp['sa'] = req['da'] resp['bssid'] = req['bssid'] payload = struct.pack('<HHH', 0x0411, 0, 0xc001) payload += binascii.unhexlify("010882848b960c121824") resp['payload'] = payload + extra hapd.mgmt_tx(resp) def test_owe_invalid_assoc_resp(dev, apdev): """Opportunistic Wireless Encryption - invalid Association Response frame""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") hapd.set("ext_mgmt_frame_handling", "1") # OWE: No Diffie-Hellman Parameter element found in Association Response frame tests = [b''] # No room for group --> no DH Params tests += [binascii.unhexlify('ff0120')] # OWE: Unexpected Diffie-Hellman group in response: 18 tests += [binascii.unhexlify('ff03201200')] # OWE: Invalid peer DH public key tests += [binascii.unhexlify('ff23201300' + 31*'00' + '01')] # OWE: Invalid peer DH public key tests += [binascii.unhexlify('ff24201300' + 33*'ee')] for extra in tests: dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412", wait_connect=False) hapd_auth(hapd) hapd_assoc(hapd, extra) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() # OWE: Empty public key (this ends up getting padded to a valid point) dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412", wait_connect=False) hapd_auth(hapd) hapd_assoc(hapd, binascii.unhexlify('ff03201300')) ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED", "PMKSA-CACHE-ADDED"], timeout=5) if ev is None: raise Exception("No result reported for empty public key") dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() def start_owe(dev, apdev, workaround=0): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "owe_ptk_workaround": str(workaround), "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) dev[0].scan_for_bss(hapd.own_addr(), freq="2412") return hapd def owe_check_ok(dev, hapd, owe_group, owe_ptk_workaround): dev.connect("owe", key_mgmt="OWE", ieee80211w="2", owe_group=owe_group, owe_ptk_workaround=owe_ptk_workaround, scan_freq="2412") hapd.wait_sta() dev.request("REMOVE_NETWORK all") dev.wait_disconnected() dev.dump_monitor() def test_owe_ptk_workaround_ap(dev, apdev): """Opportunistic Wireless Encryption - AP using PTK workaround""" hapd = start_owe(dev, apdev, workaround=1) for group, workaround in [(19, 0), (20, 0), (21, 0), (19, 1), (20, 1), (21, 1)]: owe_check_ok(dev[0], hapd, str(group), str(workaround)) def test_owe_ptk_hash(dev, apdev): """Opportunistic Wireless Encryption - PTK derivation hash alg""" hapd = start_owe(dev, apdev) for group, workaround in [(19, 0), (20, 0), (21, 0), (19, 1)]: owe_check_ok(dev[0], hapd, str(group), str(workaround)) for group in [20, 21]: dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", owe_group=str(group), owe_ptk_workaround="1", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=10) if ev is None: raise Exception("Could not complete OWE association") ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "CTRL-EVENT-DISCONNECTED"], timeout=5) if ev is None: raise Exception("Unknown connection result") if "CTRL-EVENT-CONNECTED" in ev: raise Exception("Unexpected connection") dev[0].request("REMOVE_NETWORK all") ev = dev[0].wait_event(["PMKSA-CACHE-REMOVED"], timeout=5) if ev is None: raise Exception("No PMKSA cache removal event seen") dev[0].dump_monitor() def test_owe_transition_mode_disable(dev, apdev): """Opportunistic Wireless Encryption transition mode disable""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "transition_disable": '0x08', "owe_transition_bssid": apdev[1]['bssid'], "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() params = {"ssid": "owe-test", "owe_transition_bssid": apdev[0]['bssid'], "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=1) if ev is None: raise Exception("Transition disable not indicated") if ev.split(' ')[1] != "08": raise Exception("Unexpected transition disable bitmap: " + ev) val = dev[0].get_network(id, "owe_only") if val != "1": raise Exception("Unexpected owe_only value: " + val) dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].request("RECONNECT") dev[0].wait_connected() def test_owe_sa_query(dev, apdev): """Opportunistic Wireless Encryption - SA Query""" if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412") hapd.wait_sta() hapd.set("ext_mgmt_frame_handling", "1") dev[0].request("DISCONNECT") dev[0].wait_disconnected(timeout=10) hapd.set("ext_mgmt_frame_handling", "0") dev[0].request("PMKSA_FLUSH") dev[0].request("REASSOCIATE") dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
38.710692
115
0.616951
import binascii import logging logger = logging.getLogger() import time import os import struct import hostapd from wpasupplicant import WpaSupplicant import hwsim_utils from tshark import run_tshark from utils import HwsimSkip, fail_test, alloc_fail, wait_fail_trigger from test_ap_acs import wait_acs def test_owe(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() conf = hapd.request("GET_CONFIG") if "key_mgmt=OWE" not in conf.splitlines(): logger.info("GET_CONFIG:\n" + conf) raise Exception("GET_CONFIG did not report correct key_mgmt") dev[0].scan_for_bss(bssid, freq="2412") bss = dev[0].get_bss(bssid) if "[WPA2-OWE-CCMP]" not in bss['flags']: raise Exception("OWE AKM not recognized: " + bss['flags']) id = dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") hapd.wait_sta() pmk_h = hapd.request("GET_PMK " + dev[0].own_addr()) pmk_w = dev[0].get_pmk(id) if pmk_h != pmk_w: raise Exception("Fetched PMK does not match: hostapd %s, wpa_supplicant %s" % (pmk_h, pmk_w)) hwsim_utils.test_connectivity(dev[0], hapd) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_groups(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") for group in [19, 20, 21]: dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group)) hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) dev[0].request("REMOVE_NETWORK all") dev[0].wait_disconnected() dev[0].dump_monitor() hapd.dump_monitor() def test_owe_pmksa_caching(dev, apdev): try: run_owe_pmksa_caching(dev, apdev) finally: dev[0].set("reassoc_same_bss_optim", "0") def test_owe_pmksa_caching_connect_cmd(dev, apdev): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") try: run_owe_pmksa_caching([wpas], apdev) finally: wpas.set("reassoc_same_bss_optim", "0") def run_owe_pmksa_caching(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].set("reassoc_same_bss_optim", "1") dev[0].scan_for_bss(bssid, freq="2412") id = dev[0].connect("owe", key_mgmt="OWE") hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) pmksa = dev[0].get_pmksa(bssid) dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].dump_monitor() dev[0].select_network(id, 2412) dev[0].wait_connected() hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) pmksa2 = dev[0].get_pmksa(bssid) dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].dump_monitor() if "OK" not in hapd.request("PMKSA_FLUSH"): raise Exception("PMKSA_FLUSH failed") dev[0].select_network(id, 2412) dev[0].wait_connected() hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) pmksa3 = dev[0].get_pmksa(bssid) if pmksa is None or pmksa2 is None or pmksa3 is None: raise Exception("PMKSA entry missing") if pmksa['pmkid'] != pmksa2['pmkid']: raise Exception("Unexpected PMKID change when using PMKSA caching") if pmksa['pmkid'] == pmksa3['pmkid']: raise Exception("PMKID did not change after PMKSA cache flush") dev[0].request("REASSOCIATE") dev[0].wait_connected() pmksa4 = dev[0].get_pmksa(bssid) if pmksa3['pmkid'] != pmksa4['pmkid']: raise Exception("Unexpected PMKID change when using PMKSA caching [2]") def test_owe_and_psk(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe+psk", "wpa": "2", "wpa_key_mgmt": "OWE WPA-PSK", "rsn_pairwise": "CCMP", "wpa_passphrase": "12345678"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe+psk", psk="12345678") hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) dev[1].scan_for_bss(bssid, freq="2412") dev[1].connect("owe+psk", key_mgmt="OWE") hapd.wait_sta() hwsim_utils.test_connectivity(dev[1], hapd) def test_owe_transition_mode(dev, apdev): run_owe_transition_mode(dev, apdev) def test_owe_transition_mode_connect_cmd(dev, apdev): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_transition_mode([wpas], apdev) def test_owe_transition_mode_mismatch1(dev, apdev): run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55") def test_owe_transition_mode_mismatch2(dev, apdev): run_owe_transition_mode(dev, apdev, adv_bssid1="02:11:22:33:44:66") def test_owe_transition_mode_mismatch3(dev, apdev): run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55", adv_bssid1="02:11:22:33:44:66") def run_owe_transition_mode(dev, apdev, adv_bssid0=None, adv_bssid1=None): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() adv_bssid = adv_bssid0 if adv_bssid0 else apdev[1]['bssid'] params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_bssid": adv_bssid, "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() adv_bssid = adv_bssid1 if adv_bssid1 else apdev[0]['bssid'] params = {"ssid": "owe-test", "owe_transition_bssid": adv_bssid, "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") bss = dev[0].get_bss(bssid) if "[WPA2-OWE-CCMP]" not in bss['flags']: raise Exception("OWE AKM not recognized: " + bss['flags']) if "[OWE-TRANS]" not in bss['flags']: raise Exception("OWE transition not recognized: " + bss['flags']) bss = dev[0].get_bss(bssid2) if "[OWE-TRANS-OPEN]" not in bss['flags']: raise Exception("OWE transition (open) not recognized: " + bss['flags']) id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) logger.info("Move to OWE only mode (disable transition mode)") dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].dump_monitor() hapd2.disable() hapd.disable() dev[0].flush_scan_cache() hapd.set("owe_transition_bssid", "00:00:00:00:00:00") hapd.set("ignore_broadcast_ssid", '0') hapd.set("ssid", 'owe-test') hapd.enable() dev[0].scan_for_bss(bssid, freq="2412") dev[0].select_network(id, 2412) dev[0].wait_connected() hapd.wait_sta() hwsim_utils.test_connectivity(dev[0], hapd) def test_owe_transition_mode_ifname(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_ifname": apdev[1]['ifname'], "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() params = {"ssid": "owe-test", "owe_transition_ifname": apdev[0]['ifname']} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_transition_mode_ifname_acs(dev, apdev): run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=False) def test_owe_transition_mode_ifname_acs2(dev, apdev): run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=True) def run_owe_transition_mode_ifname_acs(dev, apdev, wait_first): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "channel": "0", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_ifname": apdev[1]['ifname'], "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params, wait_enabled=False) bssid = hapd.own_addr() if wait_first: wait_acs(hapd) params = {"ssid": "owe-test", "channel": "0", "owe_transition_ifname": apdev[0]['ifname']} hapd2 = hostapd.add_ap(apdev[1], params, wait_enabled=False) bssid2 = hapd2.own_addr() wait_acs(hapd2) if not wait_first: state = hapd.get_status_field("state") if state == "ACS-STARTED": time.sleep(5) state = hapd.get_status_field("state") if state != "ENABLED": raise Exception("AP1 startup did not succeed") freq = hapd.get_status_field("freq") freq2 = hapd2.get_status_field("freq") dev[0].scan_for_bss(bssid, freq=freq) dev[0].scan_for_bss(bssid2, freq=freq2) id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="%s %s" % (freq, freq2)) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_transition_mode_open_only_ap(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-test-open"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") bss = dev[0].get_bss(bssid) id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") hwsim_utils.test_connectivity(dev[0], hapd) val = dev[0].get_status_field("key_mgmt") if val != "NONE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_only_sta(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-test-open"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2", scan_freq="2412", owe_only="1", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10) if not ev: raise Exception("Unknown result for the connection attempt") if "CTRL-EVENT-CONNECTED" in ev: raise Exception("Unexpected connection to open network") dev[0].request("DISCONNECT") dev[0].dump_monitor() params = {"ssid": "owe-test-open", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd2 = hostapd.add_ap(apdev[1], params) dev[0].request("RECONNECT") dev[0].wait_connected() def test_owe_transition_mode_open_multiple_scans(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-test", "owe_transition_bssid": apdev[0]['bssid'], "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid2, freq="2412") dev[0].dump_monitor() id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=1) params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "owe_transition_bssid": apdev[1]['bssid'], "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].wait_connected() val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) def test_owe_transition_mode_multi_bss(dev, apdev): try: run_owe_transition_mode_multi_bss(dev, apdev) finally: dev[0].request("SCAN_INTERVAL 5") def run_owe_transition_mode_multi_bss(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") ifname1 = apdev[0]['ifname'] ifname2 = apdev[0]['ifname'] + '-2' hapd1 = hostapd.add_bss(apdev[0], ifname1, 'owe-bss-1.conf') hapd2 = hostapd.add_bss(apdev[0], ifname2, 'owe-bss-2.conf') hapd2.bssidx = 1 bssid = hapd1.own_addr() bssid2 = hapd2.own_addr() time.sleep(0.1) dev[0].request("SCAN_INTERVAL 1") dev[0].scan_for_bss(bssid2, freq="2412") dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("transition-mode-open", key_mgmt="OWE") val = dev[0].get_status_field("bssid") if val != bssid2: raise Exception("Unexpected bssid: " + val) val = dev[0].get_status_field("key_mgmt") if val != "OWE": raise Exception("Unexpected key_mgmt: " + val) hwsim_utils.test_connectivity(dev[0], hapd2) def test_owe_transition_mode_rsne_mismatch(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "rsne_override_eapol": "30140100000fac040100000fac040100000fac020c00", "owe_transition_bssid": apdev[1]['bssid'], "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() params = {"ssid": "owe-test", "owe_transition_bssid": apdev[0]['bssid'], "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=5) if ev is None: raise Exception("OWE PMKSA not created") ev = dev[0].wait_event(["WPA: IE in 3/4 msg does not match with IE in Beacon/ProbeResp"], timeout=5) if ev is None: raise Exception("RSNE mismatch not reported") ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "CTRL-EVENT-DISCONNECTED"], timeout=5) dev[0].request("REMOVE_NETWORK all") if ev is None: raise Exception("No disconnection seen") if "CTRL-EVENT-DISCONNECTED" not in ev: raise Exception("Unexpected connection") if "reason=17 locally_generated=1" not in ev: raise Exception("Unexpected disconnection reason: " + ev) def test_owe_unsupported_group(dev, apdev): try: run_owe_unsupported_group(dev, apdev) finally: dev[0].request("VENDOR_ELEM_REMOVE 13 *") def test_owe_unsupported_group_connect_cmd(dev, apdev): try: wpas = None wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_unsupported_group([wpas], apdev) finally: if wpas: wpas.request("VENDOR_ELEM_REMOVE 13 *") def run_owe_unsupported_group(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].request("VENDOR_ELEM_ADD 13 ff23200000783590fb7440e03d5b3b33911f86affdcc6b4411b707846ac4ff08ddc8831ccd") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason: " + ev) def test_owe_limited_group_set(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "20 21"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", owe_group="19", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason: " + ev) dev[0].dump_monitor() for group in [20, 21]: dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group)) dev[0].request("REMOVE_NETWORK all") dev[0].wait_disconnected() dev[0].dump_monitor() def test_owe_limited_group_set_pmf(dev, apdev, params): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") pcapng = os.path.join(params['logdir'], "hwsim0.pcapng") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "21"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason: " + ev) dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) dev[0].request("DISCONNECT") if ev is None: raise Exception("Association not rejected (2)") if "status_code=77" not in ev: raise Exception("Unexpected rejection reason (2): " + ev) dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="21", ieee80211w="2", scan_freq="2412") dev[0].request("REMOVE_NETWORK all") dev[0].wait_disconnected() dev[0].dump_monitor() out = run_tshark(pcapng, "wlan.fc.type_subtype == 1", display=['wlan_mgt.fixed.status_code']) status = out.splitlines() logger.info("Association Response frame status codes: " + str(status)) if len(status) != 3: raise Exception("Unexpected number of Association Response frames") if (int(status[0], base=0) != 77 or int(status[1], base=0) != 77 or int(status[2], base=0) != 0): raise Exception("Unexpected Association Response frame status code") def test_owe_group_negotiation(dev, apdev): run_owe_group_negotiation(dev[0], apdev) def test_owe_group_negotiation_connect_cmd(dev, apdev): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_group_negotiation(wpas, apdev) def run_owe_group_negotiation(dev, apdev): if "OWE" not in dev.get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "21"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev.scan_for_bss(bssid, freq="2412") dev.connect("owe", key_mgmt="OWE") def test_owe_assoc_reject(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "require_ht": "1", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "owe_groups": "19"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", disable_ht="1", scan_freq="2412", wait_connect=False) for i in range(0, 2): ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10) if ev is None: raise Exception("Association rejection not reported") hapd.set("require_ht", "0") for i in range(0, 2): ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT", "CTRL-EVENT-CONNECTED"], timeout=10) if ev is None: raise Exception("Association result not reported") if "CTRL-EVENT-CONNECTED" in ev: break if "status_code=77" in ev: raise Exception("Unexpected unsupport group rejection") if "CTRL-EVENT-CONNECTED" not in ev: raise Exception("Did not connect successfully") def test_owe_local_errors(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") tests = [(1, "crypto_ecdh_init;owe_build_assoc_req"), (1, "crypto_ecdh_get_pubkey;owe_build_assoc_req"), (1, "wpabuf_alloc;owe_build_assoc_req")] for count, func in tests: with alloc_fail(dev[0], count, func): dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2", scan_freq="2412", wait_connect=False) wait_fail_trigger(dev[0], "GET_ALLOC_FAIL") dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() tests = [(1, "crypto_ecdh_set_peerkey;owe_process_assoc_resp"), (1, "crypto_ecdh_get_pubkey;owe_process_assoc_resp"), (1, "wpabuf_alloc;=owe_process_assoc_resp")] for count, func in tests: with alloc_fail(dev[0], count, func): dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2", scan_freq="2412", wait_connect=False) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() tests = [(1, "hmac_sha256;owe_process_assoc_resp", 19), (1, "hmac_sha256_kdf;owe_process_assoc_resp", 19), (1, "hmac_sha384;owe_process_assoc_resp", 20), (1, "hmac_sha384_kdf;owe_process_assoc_resp", 20), (1, "hmac_sha512;owe_process_assoc_resp", 21), (1, "hmac_sha512_kdf;owe_process_assoc_resp", 21)] for count, func, group in tests: with fail_test(dev[0], count, func): dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group), ieee80211w="2", scan_freq="2412", wait_connect=False) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="18", ieee80211w="2", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=5) if ev is None: raise Exception("No authentication attempt") time.sleep(0.5) dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() def hapd_auth(hapd): for i in range(0, 10): req = hapd.mgmt_rx() if req is None: raise Exception("MGMT RX wait timed out") if req['subtype'] == 11: break req = None if not req: raise Exception("Authentication frame not received") resp = {} resp['fc'] = req['fc'] resp['da'] = req['sa'] resp['sa'] = req['da'] resp['bssid'] = req['bssid'] resp['payload'] = struct.pack('<HHH', 0, 2, 0) hapd.mgmt_tx(resp) def hapd_assoc(hapd, extra): for i in range(0, 10): req = hapd.mgmt_rx() if req is None: raise Exception("MGMT RX wait timed out") if req['subtype'] == 0: break req = None if not req: raise Exception("Association Request frame not received") resp = {} resp['fc'] = 0x0010 resp['da'] = req['sa'] resp['sa'] = req['da'] resp['bssid'] = req['bssid'] payload = struct.pack('<HHH', 0x0411, 0, 0xc001) payload += binascii.unhexlify("010882848b960c121824") resp['payload'] = payload + extra hapd.mgmt_tx(resp) def test_owe_invalid_assoc_resp(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") hapd.set("ext_mgmt_frame_handling", "1") tests = [b''] tests += [binascii.unhexlify('ff0120')] tests += [binascii.unhexlify('ff03201200')] tests += [binascii.unhexlify('ff23201300' + 31*'00' + '01')] tests += [binascii.unhexlify('ff24201300' + 33*'ee')] for extra in tests: dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412", wait_connect=False) hapd_auth(hapd) hapd_assoc(hapd, extra) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412", wait_connect=False) hapd_auth(hapd) hapd_assoc(hapd, binascii.unhexlify('ff03201300')) ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED", "PMKSA-CACHE-ADDED"], timeout=5) if ev is None: raise Exception("No result reported for empty public key") dev[0].request("REMOVE_NETWORK all") dev[0].dump_monitor() def start_owe(dev, apdev, workaround=0): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "owe_ptk_workaround": str(workaround), "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) dev[0].scan_for_bss(hapd.own_addr(), freq="2412") return hapd def owe_check_ok(dev, hapd, owe_group, owe_ptk_workaround): dev.connect("owe", key_mgmt="OWE", ieee80211w="2", owe_group=owe_group, owe_ptk_workaround=owe_ptk_workaround, scan_freq="2412") hapd.wait_sta() dev.request("REMOVE_NETWORK all") dev.wait_disconnected() dev.dump_monitor() def test_owe_ptk_workaround_ap(dev, apdev): hapd = start_owe(dev, apdev, workaround=1) for group, workaround in [(19, 0), (20, 0), (21, 0), (19, 1), (20, 1), (21, 1)]: owe_check_ok(dev[0], hapd, str(group), str(workaround)) def test_owe_ptk_hash(dev, apdev): hapd = start_owe(dev, apdev) for group, workaround in [(19, 0), (20, 0), (21, 0), (19, 1)]: owe_check_ok(dev[0], hapd, str(group), str(workaround)) for group in [20, 21]: dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", owe_group=str(group), owe_ptk_workaround="1", scan_freq="2412", wait_connect=False) ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=10) if ev is None: raise Exception("Could not complete OWE association") ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED", "CTRL-EVENT-DISCONNECTED"], timeout=5) if ev is None: raise Exception("Unknown connection result") if "CTRL-EVENT-CONNECTED" in ev: raise Exception("Unexpected connection") dev[0].request("REMOVE_NETWORK all") ev = dev[0].wait_event(["PMKSA-CACHE-REMOVED"], timeout=5) if ev is None: raise Exception("No PMKSA cache removal event seen") dev[0].dump_monitor() def test_owe_transition_mode_disable(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") dev[0].flush_scan_cache() params = {"ssid": "owe-random", "wpa": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP", "ieee80211w": "2", "transition_disable": '0x08', "owe_transition_bssid": apdev[1]['bssid'], "owe_transition_ssid": '"owe-test"', "ignore_broadcast_ssid": "1"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() params = {"ssid": "owe-test", "owe_transition_bssid": apdev[0]['bssid'], "owe_transition_ssid": '"owe-random"'} hapd2 = hostapd.add_ap(apdev[1], params) bssid2 = hapd2.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].scan_for_bss(bssid2, freq="2412") id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2", scan_freq="2412") ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=1) if ev is None: raise Exception("Transition disable not indicated") if ev.split(' ')[1] != "08": raise Exception("Unexpected transition disable bitmap: " + ev) val = dev[0].get_network(id, "owe_only") if val != "1": raise Exception("Unexpected owe_only value: " + val) dev[0].request("DISCONNECT") dev[0].wait_disconnected() dev[0].request("RECONNECT") dev[0].wait_connected() def test_owe_sa_query(dev, apdev): if "OWE" not in dev[0].get_capability("key_mgmt"): raise HwsimSkip("OWE not supported") params = {"ssid": "owe", "wpa": "2", "ieee80211w": "2", "wpa_key_mgmt": "OWE", "rsn_pairwise": "CCMP"} hapd = hostapd.add_ap(apdev[0], params) bssid = hapd.own_addr() dev[0].scan_for_bss(bssid, freq="2412") dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2", scan_freq="2412") hapd.wait_sta() hapd.set("ext_mgmt_frame_handling", "1") dev[0].request("DISCONNECT") dev[0].wait_disconnected(timeout=10) hapd.set("ext_mgmt_frame_handling", "0") dev[0].request("PMKSA_FLUSH") dev[0].request("REASSOCIATE") dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
true
true
f72c6125a11e0ae38fd3d3c079c6d6047cfb6b22
2,373
py
Python
backend/alembic/env.py
jflad17/pilot_logbook
f75c9866d073c33d001ae2d0eb0994496eb49045
[ "MIT" ]
1
2022-03-25T23:41:37.000Z
2022-03-25T23:41:37.000Z
backend/alembic/env.py
jflad17/pilot_logbook
f75c9866d073c33d001ae2d0eb0994496eb49045
[ "MIT" ]
null
null
null
backend/alembic/env.py
jflad17/pilot_logbook
f75c9866d073c33d001ae2d0eb0994496eb49045
[ "MIT" ]
null
null
null
from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from models import * from db.base import Base from core.config import settings from alembic import context from models import * # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata target_metadata = Base.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URI) url = config.get_main_option("sqlalchemy.url") def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, version_table="AlembicVersion", compare_type=True, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, version_table="AlembicVersion", compare_type=True, ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
27.275862
74
0.714286
from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from models import * from db.base import Base from core.config import settings from alembic import context from models import * config = context.config fileConfig(config.config_file_name) # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata target_metadata = Base.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URI) url = config.get_main_option("sqlalchemy.url") def run_migrations_offline(): context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, version_table="AlembicVersion", compare_type=True, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, version_table="AlembicVersion", compare_type=True, ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
true
true
f72c61450c801c44dc77e1b98289e540685b544a
1,343
py
Python
bootleg/embeddings/word_embeddings/base_word_emb.py
mleszczy/bootleg
162d74001cdfbbe146753393641d549e0328acb1
[ "Apache-2.0" ]
1
2021-01-11T18:40:09.000Z
2021-01-11T18:40:09.000Z
bootleg/embeddings/word_embeddings/base_word_emb.py
mleszczy/bootleg
162d74001cdfbbe146753393641d549e0328acb1
[ "Apache-2.0" ]
null
null
null
bootleg/embeddings/word_embeddings/base_word_emb.py
mleszczy/bootleg
162d74001cdfbbe146753393641d549e0328acb1
[ "Apache-2.0" ]
null
null
null
"""Base word embedding""" import torch import torch.nn as nn import os from bootleg.utils import logging_utils class BaseWordEmbedding(nn.Module): """ Base word embedding class. We split the word embedding from the sentence encoder, similar to BERT. Attributes: pad_id: id of the pad word index """ def __init__(self, args, main_args, word_symbols): super(BaseWordEmbedding, self).__init__() self.logger = logging_utils.get_logger(main_args) self._key = "word" self.pad_id = word_symbols.pad_id def freeze_params(self): for name, param in self.named_parameters(): param.requires_grad = False self.logger.debug(f'Freezing {name}') return # This mask is for downstream pytorch multiheadattention # This assumes that TRUE means MASK (aka IGNORE). For the sentence embedding, the mask therefore is if an index is equal to the pad id # Note: This mask cannot be used for a BERT model as they use the reverse mask. def get_downstream_mask(self, word_indices): return word_indices == self.pad_id def forward(self, word_indices): raise ValueError("Not implemented.") def get_dim(self): raise ValueError("Not implemented.") def get_key(self): raise ValueError("Not implemented.")
32.756098
138
0.684289
import torch import torch.nn as nn import os from bootleg.utils import logging_utils class BaseWordEmbedding(nn.Module): def __init__(self, args, main_args, word_symbols): super(BaseWordEmbedding, self).__init__() self.logger = logging_utils.get_logger(main_args) self._key = "word" self.pad_id = word_symbols.pad_id def freeze_params(self): for name, param in self.named_parameters(): param.requires_grad = False self.logger.debug(f'Freezing {name}') return def get_downstream_mask(self, word_indices): return word_indices == self.pad_id def forward(self, word_indices): raise ValueError("Not implemented.") def get_dim(self): raise ValueError("Not implemented.") def get_key(self): raise ValueError("Not implemented.")
true
true
f72c63c7014f8654c874d4b6bc686d7d1259981c
1,815
py
Python
exampleapp/view1/views.py
thomasjiangcy/django-rest-mock
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
[ "MIT" ]
9
2018-03-05T12:45:07.000Z
2021-11-15T15:22:18.000Z
exampleapp/view1/views.py
thomasjiangcy/django-rest-mock
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
[ "MIT" ]
null
null
null
exampleapp/view1/views.py
thomasjiangcy/django-rest-mock
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
[ "MIT" ]
null
null
null
from rest_framework import generics, views from rest_framework.response import Response class SomeView(views.APIView): """ URL: /api/someview """ def get(self, request, *args, **kwargs): """ ``` { "success": "Hello, world!" } ``` """ pass class ResourceListView(generics.ListCreateAPIView): """ URL: /api/resource/__key """ def post(self, request, *args, **kwargs): """ ``` { "__options": { "excludeKey": true } } ``` """ pass class ResourceView(generics.RetrieveUpdateDestroyAPIView): """ URL: /api/resource/__key """ def get(self, request, *args, **kwargs): """ ``` { "__key": "<id:int>", "__key_position": "url", "__mockcount": 5, "__options": { "modifiers": ["patch", "put", "delete"], "excludeKey": false }, "id": "<int>", "name": "<name>", "complexStructure": [ { "link": "<int::10>", "url": "<uri>", "related_user": { "id": "<int:1:5>", "hash": "<sha256>" } } ] } ``` """ return Response({'success': 'Successful request and response!'}, status=200) def patch(self, request, *args, **kwargs): """Some docstring""" pass def put(self, request, *args, **kwargs): """some docstring""" pass def delete(self, request, *args, **kwargs): """Some docstring""" pass
21.86747
84
0.406061
from rest_framework import generics, views from rest_framework.response import Response class SomeView(views.APIView): def get(self, request, *args, **kwargs): pass class ResourceListView(generics.ListCreateAPIView): def post(self, request, *args, **kwargs): pass class ResourceView(generics.RetrieveUpdateDestroyAPIView): def get(self, request, *args, **kwargs): return Response({'success': 'Successful request and response!'}, status=200) def patch(self, request, *args, **kwargs): pass def put(self, request, *args, **kwargs): pass def delete(self, request, *args, **kwargs): pass
true
true
f72c64df1da4e00b9d299b8a5608883b2530e2c8
7,812
py
Python
scons/scons-local-4.1.0/SCons/Tool/mingw.py
vishalbelsare/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
[ "BSD-2-Clause" ]
null
null
null
scons/scons-local-4.1.0/SCons/Tool/mingw.py
vishalbelsare/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
[ "BSD-2-Clause" ]
null
null
null
scons/scons-local-4.1.0/SCons/Tool/mingw.py
vishalbelsare/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
[ "BSD-2-Clause" ]
null
null
null
# MIT License # # Copyright The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """SCons.Tool.gcc Tool-specific initialization for MinGW (http://www.mingw.org/) There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ import os import os.path import glob import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Tool import SCons.Util mingw_paths = [ r'c:\MinGW\bin', r'C:\cygwin64\bin', r'C:\msys64', r'C:\msys64\mingw64\bin', r'C:\cygwin\bin', r'C:\msys', r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin' ] def shlib_generator(target, source, env, for_signature): cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.append('-Wl,--out-implib,' + implib.get_string(for_signature)) def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') insert_def = env.subst("$WINDOWS_INSERT_DEF") if insert_def not in ['', '0', 0] and def_target: \ cmd.append('-Wl,--output-def,' + def_target.get_string(for_signature)) return [cmd] def shlib_emitter(target, source, env): dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError( "A shared library should have exactly one target with the suffix: %s Target(s) are:%s" % \ (env.subst("$SHLIBSUFFIX"), ",".join([str(t) for t in target]))) if not no_import_lib and \ not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'): # Create list of target libraries as strings targetStrings = env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) # Append a def file target if there isn't already a def file target # or a def file source or the user has explicitly asked for the target # to be emitted. def_source = env.FindIxes(source, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') skip_def_insert = env.subst("$WINDOWS_INSERT_DEF") in ['', '0', 0] if not def_source and not def_target and not skip_def_insert: # Create list of target libraries and def files as strings targetStrings = env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) return (target, source) shlib_action = SCons.Action.Action(shlib_generator, '$SHLINKCOMSTR', generator=1) ldmodule_action = SCons.Action.Action(shlib_generator, '$LDMODULECOMSTR', generator=1) res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, suffix='.o', source_scanner=SCons.Tool.SourceFileScanner) SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan) # This is what we search for to find mingw: # key_program = 'mingw32-gcc' key_program = 'mingw32-make' def find_version_specific_mingw_paths(): r""" One example of default mingw install paths is: C:\mingw-w64\x86_64-6.3.0-posix-seh-rt_v5-rev2\mingw64\bin Use glob'ing to find such and add to mingw_paths """ new_paths = glob.glob(r"C:\mingw-w64\*\mingw64\bin") return new_paths def generate(env): global mingw_paths # Check for reasoanble mingw default paths mingw_paths += find_version_specific_mingw_paths() mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths) if mingw: mingw_bin_dir = os.path.dirname(mingw) # Adjust path if we found it in a chocolatey install if mingw_bin_dir == r'C:\ProgramData\chocolatey\bin': mingw_bin_dir = r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin' env.AppendENVPath('PATH', mingw_bin_dir) # Most of mingw is the same as gcc and friends... gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'gfortran', 'm4'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) # ... but a few things differ: env['CC'] = 'gcc' # make sure the msvc tool doesnt break us, it added a /flag if 'CCFLAGS' in env: # make sure its a CLVar to handle list or str cases if type(env['CCFLAGS']) is not SCons.Util.CLVar: env['CCFLAGS'] = SCons.Util.CLVar(env['CCFLAGS']) env['CCFLAGS'] = SCons.Util.CLVar(str(env['CCFLAGS']).replace('/nologo', '')) env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['CXX'] = 'g++' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = shlib_action env['SHLINKCOMSTR'] = shlib_generator env['LDMODULECOM'] = ldmodule_action env.Append(SHLIBEMITTER=[shlib_emitter]) env.Append(LDMODULEEMITTER=[shlib_emitter]) env['AS'] = 'as' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}' env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = 'windres' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['RCINCPREFIX'] = '--include-dir ' env['RCINCSUFFIX'] = '' env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET' env['BUILDERS']['RES'] = res_builder # Some setting from the platform also have to be overridden: env['OBJSUFFIX'] = '.o' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' env['PROGSUFFIX'] = '.exe' # Handle new versioned shared library logic env['_SHLIBSUFFIX'] = '$SHLIBSUFFIX' env["SHLIBPREFIX"] = "" def exists(env): mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths) if mingw: mingw_bin_dir = os.path.dirname(mingw) env.AppendENVPath('PATH', mingw_bin_dir) return mingw # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
36.166667
110
0.670123
import os import os.path import glob import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Tool import SCons.Util mingw_paths = [ r'c:\MinGW\bin', r'C:\cygwin64\bin', r'C:\msys64', r'C:\msys64\mingw64\bin', r'C:\cygwin\bin', r'C:\msys', r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin' ] def shlib_generator(target, source, env, for_signature): cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.append('-Wl,--out-implib,' + implib.get_string(for_signature)) def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') insert_def = env.subst("$WINDOWS_INSERT_DEF") if insert_def not in ['', '0', 0] and def_target: \ cmd.append('-Wl,--output-def,' + def_target.get_string(for_signature)) return [cmd] def shlib_emitter(target, source, env): dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError( "A shared library should have exactly one target with the suffix: %s Target(s) are:%s" % \ (env.subst("$SHLIBSUFFIX"), ",".join([str(t) for t in target]))) if not no_import_lib and \ not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'): targetStrings = env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX') target.append(env.fs.File(targetStrings)) # or a def file source or the user has explicitly asked for the target # to be emitted. def_source = env.FindIxes(source, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') skip_def_insert = env.subst("$WINDOWS_INSERT_DEF") in ['', '0', 0] if not def_source and not def_target and not skip_def_insert: # Create list of target libraries and def files as strings targetStrings = env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) return (target, source) shlib_action = SCons.Action.Action(shlib_generator, '$SHLINKCOMSTR', generator=1) ldmodule_action = SCons.Action.Action(shlib_generator, '$LDMODULECOMSTR', generator=1) res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, suffix='.o', source_scanner=SCons.Tool.SourceFileScanner) SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan) # This is what we search for to find mingw: # key_program = 'mingw32-gcc' key_program = 'mingw32-make' def find_version_specific_mingw_paths(): new_paths = glob.glob(r"C:\mingw-w64\*\mingw64\bin") return new_paths def generate(env): global mingw_paths # Check for reasoanble mingw default paths mingw_paths += find_version_specific_mingw_paths() mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths) if mingw: mingw_bin_dir = os.path.dirname(mingw) # Adjust path if we found it in a chocolatey install if mingw_bin_dir == r'C:\ProgramData\chocolatey\bin': mingw_bin_dir = r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin' env.AppendENVPath('PATH', mingw_bin_dir) # Most of mingw is the same as gcc and friends... gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'gfortran', 'm4'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) # ... but a few things differ: env['CC'] = 'gcc' # make sure the msvc tool doesnt break us, it added a /flag if 'CCFLAGS' in env: # make sure its a CLVar to handle list or str cases if type(env['CCFLAGS']) is not SCons.Util.CLVar: env['CCFLAGS'] = SCons.Util.CLVar(env['CCFLAGS']) env['CCFLAGS'] = SCons.Util.CLVar(str(env['CCFLAGS']).replace('/nologo', '')) env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['CXX'] = 'g++' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = shlib_action env['SHLINKCOMSTR'] = shlib_generator env['LDMODULECOM'] = ldmodule_action env.Append(SHLIBEMITTER=[shlib_emitter]) env.Append(LDMODULEEMITTER=[shlib_emitter]) env['AS'] = 'as' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}' env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = 'windres' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['RCINCPREFIX'] = '--include-dir ' env['RCINCSUFFIX'] = '' env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET' env['BUILDERS']['RES'] = res_builder # Some setting from the platform also have to be overridden: env['OBJSUFFIX'] = '.o' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' env['PROGSUFFIX'] = '.exe' # Handle new versioned shared library logic env['_SHLIBSUFFIX'] = '$SHLIBSUFFIX' env["SHLIBPREFIX"] = "" def exists(env): mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths) if mingw: mingw_bin_dir = os.path.dirname(mingw) env.AppendENVPath('PATH', mingw_bin_dir) return mingw # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
true
true
f72c66e743146c7a5b70a5440e9ab5459f10245b
6,426
py
Python
Lib/site-packages/pyparsing/actions.py
edupyter/EDUPYTER38
396183cea72987506f1ef647c0272a2577c56218
[ "bzip2-1.0.6" ]
1
2020-10-05T05:38:26.000Z
2020-10-05T05:38:26.000Z
Lib/site-packages/pyparsing/actions.py
edupyter/EDUPYTER38
396183cea72987506f1ef647c0272a2577c56218
[ "bzip2-1.0.6" ]
null
null
null
Lib/site-packages/pyparsing/actions.py
edupyter/EDUPYTER38
396183cea72987506f1ef647c0272a2577c56218
[ "bzip2-1.0.6" ]
null
null
null
# actions.py from .exceptions import ParseException from .util import col class OnlyOnce: """ Wrapper for parse actions, to ensure they are only called once. """ def __init__(self, method_call): from .core import _trim_arity self.callable = _trim_arity(method_call) self.called = False def __call__(self, s, l, t): if not self.called: results = self.callable(s, l, t) self.called = True return results raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset") def reset(self): """ Allow the associated parse action to be called once more. """ self.called = False def match_only_at_col(n): """ Helper method for defining parse actions that require matching at a specific column in the input text. """ def verify_col(strg, locn, toks): if col(locn, strg) != n: raise ParseException(strg, locn, "matched token not at column {}".format(n)) return verify_col def replace_with(repl_str): """ Helper method for common parse actions that simply return a literal value. Especially useful when used with :class:`transform_string<ParserElement.transform_string>` (). Example:: num = Word(nums).set_parse_action(lambda toks: int(toks[0])) na = one_of("N/A NA").set_parse_action(replace_with(math.nan)) term = na | num term[1, ...].parse_string("324 234 N/A 234") # -> [324, 234, nan, 234] """ return lambda s, l, t: [repl_str] def remove_quotes(s, l, t): """ Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use remove_quotes to strip quotation marks from parsed results quoted_string.set_parse_action(remove_quotes) quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] """ return t[0][1:-1] def with_attribute(*args, **attr_dict): """ Helper to create a validating parse action to be used with start tags created with :class:`make_xml_tags` or :class:`make_html_tags`. Use ``with_attribute`` to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as ``<TD>`` or ``<DIV>``. Call ``with_attribute`` with a series of attribute names and values. Specify the list of filter attributes names and values as: - keyword arguments, as in ``(align="right")``, or - as an explicit dict with ``**`` operator, when an attribute name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}`` - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))`` For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case. If just testing for ``class`` (with or without a namespace), use :class:`with_class`. To verify that the attribute exists, but without specifying a value, pass ``with_attribute.ANY_VALUE`` as the value. Example:: html = ''' <div> Some text <div type="grid">1 4 0 1 0</div> <div type="graph">1,3 2,3 1,1</div> <div>this has no type</div> </div> ''' div,div_end = make_html_tags("div") # only match div tag having a type attribute with value "grid" div_grid = div().set_parse_action(with_attribute(type="grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.search_string(html): print(grid_header.body) # construct a match with any div tag having a type attribute, regardless of the value div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.search_string(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 """ if args: attrs = args[:] else: attrs = attr_dict.items() attrs = [(k, v) for k, v in attrs] def pa(s, l, tokens): for attrName, attrValue in attrs: if attrName not in tokens: raise ParseException(s, l, "no matching attribute " + attrName) if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue: raise ParseException( s, l, "attribute {!r} has value {!r}, must be {!r}".format( attrName, tokens[attrName], attrValue ), ) return pa with_attribute.ANY_VALUE = object() def with_class(classname, namespace=""): """ Simplified version of :class:`with_attribute` when matching on a div class - made difficult because ``class`` is a reserved word in Python. Example:: html = ''' <div> Some text <div class="grid">1 4 0 1 0</div> <div class="graph">1,3 2,3 1,1</div> <div>this &lt;div&gt; has no class</div> </div> ''' div,div_end = make_html_tags("div") div_grid = div().set_parse_action(with_class("grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.search_string(html): print(grid_header.body) div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.search_string(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 """ classattr = "{}:class".format(namespace) if namespace else "class" return with_attribute(**{classattr: classname}) # pre-PEP8 compatibility symbols replaceWith = replace_with removeQuotes = remove_quotes withAttribute = with_attribute withClass = with_class matchOnlyAtCol = match_only_at_col
30.894231
122
0.613601
from .exceptions import ParseException from .util import col class OnlyOnce: def __init__(self, method_call): from .core import _trim_arity self.callable = _trim_arity(method_call) self.called = False def __call__(self, s, l, t): if not self.called: results = self.callable(s, l, t) self.called = True return results raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset") def reset(self): self.called = False def match_only_at_col(n): def verify_col(strg, locn, toks): if col(locn, strg) != n: raise ParseException(strg, locn, "matched token not at column {}".format(n)) return verify_col def replace_with(repl_str): return lambda s, l, t: [repl_str] def remove_quotes(s, l, t): return t[0][1:-1] def with_attribute(*args, **attr_dict): if args: attrs = args[:] else: attrs = attr_dict.items() attrs = [(k, v) for k, v in attrs] def pa(s, l, tokens): for attrName, attrValue in attrs: if attrName not in tokens: raise ParseException(s, l, "no matching attribute " + attrName) if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue: raise ParseException( s, l, "attribute {!r} has value {!r}, must be {!r}".format( attrName, tokens[attrName], attrValue ), ) return pa with_attribute.ANY_VALUE = object() def with_class(classname, namespace=""): classattr = "{}:class".format(namespace) if namespace else "class" return with_attribute(**{classattr: classname}) replaceWith = replace_with removeQuotes = remove_quotes withAttribute = with_attribute withClass = with_class matchOnlyAtCol = match_only_at_col
true
true
f72c67eadf3af59757f3c3b77056d4d8ab1bc14b
2,242
py
Python
py/game_logic/GameList.py
rSimulate/Cosmosium
f2489862b9b747458a6be9b884c9de75bd6eb3d2
[ "CC-BY-4.0" ]
18
2015-01-02T05:22:43.000Z
2021-11-12T12:11:12.000Z
py/game_logic/GameList.py
rSimulate/Cosmosium
f2489862b9b747458a6be9b884c9de75bd6eb3d2
[ "CC-BY-4.0" ]
3
2015-07-14T19:11:54.000Z
2018-09-17T19:09:52.000Z
py/game_logic/GameList.py
rSimulate/Cosmosium
f2489862b9b747458a6be9b884c9de75bd6eb3d2
[ "CC-BY-4.0" ]
4
2016-02-24T05:19:07.000Z
2022-02-15T17:36:37.000Z
import pickle from py.game_logic.Game import Game GAMES_FILE = 'db/GAMELIST.pickle' class GameList(object): def __init__(self): self.games = [Game()] def __len__(self): return len(self.games) def addGame(self): self.games.append(Game()) # this turned out to be more trouble than it was worth: # def pickle(self): # ''' # Removes down non-pickleable attributes and saves what it can to file. # This should be an uncommon operation, used only to preserve game-states for next time the # server comes back up. # ''' # with open(GAMES_FILE, 'wb') as f: # pickle.dump(self, f,-1) # print str(len(self))+' games-in-progress pickled.' def unpickle(self): try: with open(GAMES_FILE, 'rb') as f: self = pickle.load(f) except (EOFError, IOError): print 'No pickled games-in-progress found. Starting from scratch.' def joinGame(self,userObj): # connects given user object to best game # if user already in a game, returns that one # else finds open slot game = self._inGame(userObj) if game: userObj.game = game return game else: game = self.__findOpenSlot(userObj) game.addPlayer(userObj) return game def _inGame(self,user): # returns game obj if user is in a game, else returns None for game in self.games: if game.inGame(user.name): return game else: return None def __findOpenSlot(self,user): # returns the best game for a new user to join # NOTE: just uses 1 game for now... selectedGame = self.games[0] return selectedGame # DEPRECIATED def findOpenSlot(self,user): # returns the best open slot for a new user to join a game # adds the player to the game, and returns that game object # NOTE: just uses 1 game for now... selectedGame = self.games[0] selectedGame.addPlayer(user) return selectedGame
32.492754
99
0.566012
import pickle from py.game_logic.Game import Game GAMES_FILE = 'db/GAMELIST.pickle' class GameList(object): def __init__(self): self.games = [Game()] def __len__(self): return len(self.games) def addGame(self): self.games.append(Game()) # Removes down non-pickleable attributes and saves what it can to file. # This should be an uncommon operation, used only to preserve game-states for next time the # server comes back up. # ''' def unpickle(self): try: with open(GAMES_FILE, 'rb') as f: self = pickle.load(f) except (EOFError, IOError): print 'No pickled games-in-progress found. Starting from scratch.' def joinGame(self,userObj): game = self._inGame(userObj) if game: userObj.game = game return game else: game = self.__findOpenSlot(userObj) game.addPlayer(userObj) return game def _inGame(self,user): for game in self.games: if game.inGame(user.name): return game else: return None def __findOpenSlot(self,user): selectedGame = self.games[0] return selectedGame def findOpenSlot(self,user): selectedGame = self.games[0] selectedGame.addPlayer(user) return selectedGame
false
true
f72c68b5184364eaf2b32e9631fcdb1b88247b70
702
py
Python
setup.py
luk036/ellpy
07fe4377a18ae9b38be9ad34eceb701f26873607
[ "MIT" ]
7
2019-01-01T00:30:03.000Z
2021-07-11T12:54:46.000Z
setup.py
luk036/ellpy
07fe4377a18ae9b38be9ad34eceb701f26873607
[ "MIT" ]
1
2018-06-03T09:01:26.000Z
2018-06-03T09:01:26.000Z
setup.py
luk036/ellpy
07fe4377a18ae9b38be9ad34eceb701f26873607
[ "MIT" ]
1
2018-06-03T08:59:05.000Z
2018-06-03T08:59:05.000Z
""" Setup file for ellpy. Use setup.cfg to configure your project. This file was generated with PyScaffold 4.0.2. PyScaffold helps you to put up the scaffold of your new Python project. Learn more under: https://pyscaffold.org/ """ from setuptools import setup if __name__ == "__main__": try: setup(use_scm_version={"version_scheme": "no-guess-dev"}) except: # noqa print( "\n\nAn error occurred while building the project, " "please ensure you have the most updated version of setuptools, " "setuptools_scm and wheel with:\n" " pip install -U setuptools setuptools_scm wheel\n\n" ) raise
31.909091
77
0.638177
from setuptools import setup if __name__ == "__main__": try: setup(use_scm_version={"version_scheme": "no-guess-dev"}) except: print( "\n\nAn error occurred while building the project, " "please ensure you have the most updated version of setuptools, " "setuptools_scm and wheel with:\n" " pip install -U setuptools setuptools_scm wheel\n\n" ) raise
true
true
f72c692cf8cf1539d1b99caf1dd1a442c8da420c
7,899
py
Python
lib/modeling/keypoint_rcnn_heads.py
skokec/detectron-villard
9e420bf3fb75a8f06f6e3fd970fc2600d8969d10
[ "Apache-2.0" ]
287
2018-12-23T08:31:09.000Z
2022-02-27T14:52:21.000Z
lib/modeling/keypoint_rcnn_heads.py
absorbguo/Detectron
2f8161edc3092b0382cab535c977a180a8b3cc4d
[ "Apache-2.0" ]
54
2018-12-26T13:04:32.000Z
2020-04-24T04:09:30.000Z
lib/modeling/keypoint_rcnn_heads.py
absorbguo/Detectron
2f8161edc3092b0382cab535c977a180a8b3cc4d
[ "Apache-2.0" ]
96
2018-12-24T05:12:36.000Z
2021-04-23T15:51:21.000Z
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## """Various network "heads" for predicting keypoints in Mask R-CNN. The design is as follows: ... -> RoI ----\ -> RoIFeatureXform -> keypoint head -> keypoint output -> loss ... -> Feature / Map The keypoint head produces a feature representation of the RoI for the purpose of keypoint prediction. The keypoint output module converts the feature representation into keypoint heatmaps. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from core.config import cfg from utils.c2 import const_fill from utils.c2 import gauss_fill import modeling.ResNet as ResNet import utils.blob as blob_utils # ---------------------------------------------------------------------------- # # Keypoint R-CNN outputs and losses # ---------------------------------------------------------------------------- # def add_keypoint_outputs(model, blob_in, dim): """Add Mask R-CNN keypoint specific outputs: keypoint heatmaps.""" # NxKxHxW upsample_heatmap = (cfg.KRCNN.UP_SCALE > 1) if cfg.KRCNN.USE_DECONV: # Apply ConvTranspose to the feature representation; results in 2x # upsampling blob_in = model.ConvTranspose( blob_in, 'kps_deconv', dim, cfg.KRCNN.DECONV_DIM, kernel=cfg.KRCNN.DECONV_KERNEL, pad=int(cfg.KRCNN.DECONV_KERNEL / 2 - 1), stride=2, weight_init=gauss_fill(0.01), bias_init=const_fill(0.0) ) model.Relu('kps_deconv', 'kps_deconv') dim = cfg.KRCNN.DECONV_DIM if upsample_heatmap: blob_name = 'kps_score_lowres' else: blob_name = 'kps_score' if cfg.KRCNN.USE_DECONV_OUTPUT: # Use ConvTranspose to predict heatmaps; results in 2x upsampling blob_out = model.ConvTranspose( blob_in, blob_name, dim, cfg.KRCNN.NUM_KEYPOINTS, kernel=cfg.KRCNN.DECONV_KERNEL, pad=int(cfg.KRCNN.DECONV_KERNEL / 2 - 1), stride=2, weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.001}), bias_init=const_fill(0.0) ) else: # Use Conv to predict heatmaps; does no upsampling blob_out = model.Conv( blob_in, blob_name, dim, cfg.KRCNN.NUM_KEYPOINTS, kernel=1, pad=0, stride=1, weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.001}), bias_init=const_fill(0.0) ) if upsample_heatmap: # Increase heatmap output size via bilinear upsampling blob_out = model.BilinearInterpolation( blob_out, 'kps_score', cfg.KRCNN.NUM_KEYPOINTS, cfg.KRCNN.NUM_KEYPOINTS, cfg.KRCNN.UP_SCALE ) return blob_out def add_keypoint_losses(model): """Add Mask R-CNN keypoint specific losses.""" # Reshape input from (N, K, H, W) to (NK, HW) model.net.Reshape( ['kps_score'], ['kps_score_reshaped', '_kps_score_old_shape'], shape=(-1, cfg.KRCNN.HEATMAP_SIZE * cfg.KRCNN.HEATMAP_SIZE) ) # Softmax across **space** (woahh....space!) # Note: this is not what is commonly called "spatial softmax" # (i.e., softmax applied along the channel dimension at each spatial # location); This is softmax applied over a set of spatial locations (i.e., # each spatial location is a "class"). kps_prob, loss_kps = model.net.SoftmaxWithLoss( ['kps_score_reshaped', 'keypoint_locations_int32', 'keypoint_weights'], ['kps_prob', 'loss_kps'], scale=cfg.KRCNN.LOSS_WEIGHT / cfg.NUM_GPUS, spatial=0 ) if not cfg.KRCNN.NORMALIZE_BY_VISIBLE_KEYPOINTS: # Discussion: the softmax loss above will average the loss by the sum of # keypoint_weights, i.e. the total number of visible keypoints. Since # the number of visible keypoints can vary significantly between # minibatches, this has the effect of up-weighting the importance of # minibatches with few visible keypoints. (Imagine the extreme case of # only one visible keypoint versus N: in the case of N, each one # contributes 1/N to the gradient compared to the single keypoint # determining the gradient direction). Instead, we can normalize the # loss by the total number of keypoints, if it were the case that all # keypoints were visible in a full minibatch. (Returning to the example, # this means that the one visible keypoint contributes as much as each # of the N keypoints.) model.StopGradient( 'keypoint_loss_normalizer', 'keypoint_loss_normalizer' ) loss_kps = model.net.Mul( ['loss_kps', 'keypoint_loss_normalizer'], 'loss_kps_normalized' ) loss_gradients = blob_utils.get_loss_gradients(model, [loss_kps]) model.AddLosses(loss_kps) return loss_gradients # ---------------------------------------------------------------------------- # # Keypoint heads # ---------------------------------------------------------------------------- # def add_ResNet_roi_conv5_head_for_keypoints( model, blob_in, dim_in, spatial_scale ): """Add a ResNet "conv5" / "stage5" head for Mask R-CNN keypoint prediction. """ model.RoIFeatureTransform( blob_in, '_[pose]_pool5', blob_rois='keypoint_rois', method=cfg.KRCNN.ROI_XFORM_METHOD, resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION, sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO, spatial_scale=spatial_scale ) # Using the prefix '_[pose]_' to 'res5' enables initializing the head's # parameters using pretrained 'res5' parameters if given (see # utils.net.initialize_gpu_0_from_weights_file) s, dim_in = ResNet.add_stage( model, '_[pose]_res5', '_[pose]_pool5', 3, dim_in, 2048, 512, cfg.KRCNN.DILATION, stride_init=int(cfg.KRCNN.ROI_XFORM_RESOLUTION / 7) ) return s, 2048 def add_roi_pose_head_v1convX(model, blob_in, dim_in, spatial_scale): """Add a Mask R-CNN keypoint head. v1convX design: X * (conv).""" hidden_dim = cfg.KRCNN.CONV_HEAD_DIM kernel_size = cfg.KRCNN.CONV_HEAD_KERNEL pad_size = kernel_size // 2 current = model.RoIFeatureTransform( blob_in, '_[pose]_roi_feat', blob_rois='keypoint_rois', method=cfg.KRCNN.ROI_XFORM_METHOD, resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION, sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO, spatial_scale=spatial_scale ) for i in range(cfg.KRCNN.NUM_STACKED_CONVS): current = model.Conv( current, 'conv_fcn' + str(i + 1), dim_in, hidden_dim, kernel_size, stride=1, pad=pad_size, weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.01}), bias_init=('ConstantFill', {'value': 0.}) ) current = model.Relu(current, current) dim_in = hidden_dim return current, hidden_dim
36.233945
80
0.617547
model, blob_in, dim_in, spatial_scale ): model.RoIFeatureTransform( blob_in, '_[pose]_pool5', blob_rois='keypoint_rois', method=cfg.KRCNN.ROI_XFORM_METHOD, resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION, sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO, spatial_scale=spatial_scale ) # parameters using pretrained 'res5' parameters if given (see # utils.net.initialize_gpu_0_from_weights_file) s, dim_in = ResNet.add_stage( model, '_[pose]_res5', '_[pose]_pool5', 3, dim_in, 2048, 512, cfg.KRCNN.DILATION, stride_init=int(cfg.KRCNN.ROI_XFORM_RESOLUTION / 7) ) return s, 2048 def add_roi_pose_head_v1convX(model, blob_in, dim_in, spatial_scale): hidden_dim = cfg.KRCNN.CONV_HEAD_DIM kernel_size = cfg.KRCNN.CONV_HEAD_KERNEL pad_size = kernel_size // 2 current = model.RoIFeatureTransform( blob_in, '_[pose]_roi_feat', blob_rois='keypoint_rois', method=cfg.KRCNN.ROI_XFORM_METHOD, resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION, sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO, spatial_scale=spatial_scale ) for i in range(cfg.KRCNN.NUM_STACKED_CONVS): current = model.Conv( current, 'conv_fcn' + str(i + 1), dim_in, hidden_dim, kernel_size, stride=1, pad=pad_size, weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.01}), bias_init=('ConstantFill', {'value': 0.}) ) current = model.Relu(current, current) dim_in = hidden_dim return current, hidden_dim
true
true
f72c69bd895eea56254b314d4418757ffc5e1cbe
1,266
py
Python
Scripts/Legacy/line1prep.py
rhong3/CPTAC-UCEC
ec83fbee234b5ad3df6524cdd960b5f0f3da9ea9
[ "MIT" ]
4
2019-01-04T21:11:03.000Z
2020-12-11T16:56:15.000Z
Scripts/Legacy/line1prep.py
rhong3/CPTAC-UCEC
ec83fbee234b5ad3df6524cdd960b5f0f3da9ea9
[ "MIT" ]
null
null
null
Scripts/Legacy/line1prep.py
rhong3/CPTAC-UCEC
ec83fbee234b5ad3df6524cdd960b5f0f3da9ea9
[ "MIT" ]
null
null
null
import pandas as pd labels = pd.read_csv('../Fusion_dummy_His_MUT_joined.csv', header=0) # line = pd.read_csv('../../Line1.csv', header=0) line = pd.read_csv('../EC_cyclin_expression.csv', header=0) # line['name'] = line['Proteomics_Participant_ID'] # line = line.drop(['Proteomics_Participant_ID', 'Histologic_type', 'Genomics_subtype', 'TP53_TP53'], axis=1) # labels = labels.join(line.set_index('name'), on='name') # labels['LINE1_ORF1p'] = (labels['LINE1_ORF1p'].dropna() > 0).astype(int) # labels['RAD50-S635'] = (labels['RAD50-S635'].dropna() > 0).astype(int) # labels['NBN-S343'] = (labels['NBN-S343'].dropna() > 0).astype(int) # labels['ATR-T1989'] = (labels['ATR-T1989'].dropna() > 0).astype(int) # labels['ATM-S1981'] = (labels['ATM-S1981'].dropna() > 0).astype(int) line['name'] = line['Sample_ID'].str.slice(start=0, stop=9) line = line.drop(['Sample_ID', 'Genomic_subtype'], axis=1) labels = labels.join(line.set_index('name'), on='name') labels['CCND1'] = (labels['CCND1'].dropna() > 0).astype(int) labels['CCNE1'] = (labels['CCNE1'].dropna() > 0).astype(int) labels['CCNA2'] = (labels['CCNA2'].dropna() > 0).astype(int) labels['CCNB1'] = (labels['CCNB1'].dropna() > 0).astype(int) labels.to_csv('../Fusion_dummy_His_MUT_joined.csv', index=False)
48.692308
109
0.671406
import pandas as pd labels = pd.read_csv('../Fusion_dummy_His_MUT_joined.csv', header=0) line = pd.read_csv('../EC_cyclin_expression.csv', header=0) line['name'] = line['Sample_ID'].str.slice(start=0, stop=9) line = line.drop(['Sample_ID', 'Genomic_subtype'], axis=1) labels = labels.join(line.set_index('name'), on='name') labels['CCND1'] = (labels['CCND1'].dropna() > 0).astype(int) labels['CCNE1'] = (labels['CCNE1'].dropna() > 0).astype(int) labels['CCNA2'] = (labels['CCNA2'].dropna() > 0).astype(int) labels['CCNB1'] = (labels['CCNB1'].dropna() > 0).astype(int) labels.to_csv('../Fusion_dummy_His_MUT_joined.csv', index=False)
true
true
f72c6a4e0c25397651cfa6ffd566d94b400550f8
87,446
py
Python
Lib/zipfile.py
fochoao/CPython
c92e0770af558fe3e440e44d3605c3acaf3c5b68
[ "TCL", "0BSD" ]
null
null
null
Lib/zipfile.py
fochoao/CPython
c92e0770af558fe3e440e44d3605c3acaf3c5b68
[ "TCL", "0BSD" ]
null
null
null
Lib/zipfile.py
fochoao/CPython
c92e0770af558fe3e440e44d3605c3acaf3c5b68
[ "TCL", "0BSD" ]
null
null
null
""" Read and write ZIP files. XXX references to utf-8 need further investigation. """ import binascii import importlib.util import io import itertools import os import posixpath import shutil import stat import struct import sys import threading import time import contextlib try: import zlib # We may need its compression method crc32 = zlib.crc32 except ImportError: zlib = None crc32 = binascii.crc32 try: import bz2 # We may need its compression method except ImportError: bz2 = None try: import lzma # We may need its compression method except ImportError: lzma = None __all__ = ["BadZipFile", "BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA", "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile", "Path"] class BadZipFile(Exception): pass class LargeZipFile(Exception): """ Raised when writing a zipfile, the zipfile requires ZIP64 extensions and those extensions are disabled. """ error = BadZipfile = BadZipFile # Pre-3.2 compatibility names ZIP64_LIMIT = (1 << 31) - 1 ZIP_FILECOUNT_LIMIT = (1 << 16) - 1 ZIP_MAX_COMMENT = (1 << 16) - 1 # constants for Zip file compression methods ZIP_STORED = 0 ZIP_DEFLATED = 8 ZIP_BZIP2 = 12 ZIP_LZMA = 14 # Other ZIP compression methods not supported DEFAULT_VERSION = 20 ZIP64_VERSION = 45 BZIP2_VERSION = 46 LZMA_VERSION = 63 # we recognize (but not necessarily support) all features up to that version MAX_EXTRACT_VERSION = 63 # Below are some formats and associated data for reading/writing headers using # the struct module. The names and structures of headers/records are those used # in the PKWARE description of the ZIP file format: # http://www.pkware.com/documents/casestudies/APPNOTE.TXT # (URL valid as of January 2008) # The "end of central directory" structure, magic number, size, and indices # (section V.I in the format document) structEndArchive = b"<4s4H2LH" stringEndArchive = b"PK\005\006" sizeEndCentDir = struct.calcsize(structEndArchive) _ECD_SIGNATURE = 0 _ECD_DISK_NUMBER = 1 _ECD_DISK_START = 2 _ECD_ENTRIES_THIS_DISK = 3 _ECD_ENTRIES_TOTAL = 4 _ECD_SIZE = 5 _ECD_OFFSET = 6 _ECD_COMMENT_SIZE = 7 # These last two indices are not part of the structure as defined in the # spec, but they are used internally by this module as a convenience _ECD_COMMENT = 8 _ECD_LOCATION = 9 # The "central directory" structure, magic number, size, and indices # of entries in the structure (section V.F in the format document) structCentralDir = "<4s4B4HL2L5H2L" stringCentralDir = b"PK\001\002" sizeCentralDir = struct.calcsize(structCentralDir) # indexes of entries in the central directory structure _CD_SIGNATURE = 0 _CD_CREATE_VERSION = 1 _CD_CREATE_SYSTEM = 2 _CD_EXTRACT_VERSION = 3 _CD_EXTRACT_SYSTEM = 4 _CD_FLAG_BITS = 5 _CD_COMPRESS_TYPE = 6 _CD_TIME = 7 _CD_DATE = 8 _CD_CRC = 9 _CD_COMPRESSED_SIZE = 10 _CD_UNCOMPRESSED_SIZE = 11 _CD_FILENAME_LENGTH = 12 _CD_EXTRA_FIELD_LENGTH = 13 _CD_COMMENT_LENGTH = 14 _CD_DISK_NUMBER_START = 15 _CD_INTERNAL_FILE_ATTRIBUTES = 16 _CD_EXTERNAL_FILE_ATTRIBUTES = 17 _CD_LOCAL_HEADER_OFFSET = 18 # The "local file header" structure, magic number, size, and indices # (section V.A in the format document) structFileHeader = "<4s2B4HL2L2H" stringFileHeader = b"PK\003\004" sizeFileHeader = struct.calcsize(structFileHeader) _FH_SIGNATURE = 0 _FH_EXTRACT_VERSION = 1 _FH_EXTRACT_SYSTEM = 2 _FH_GENERAL_PURPOSE_FLAG_BITS = 3 _FH_COMPRESSION_METHOD = 4 _FH_LAST_MOD_TIME = 5 _FH_LAST_MOD_DATE = 6 _FH_CRC = 7 _FH_COMPRESSED_SIZE = 8 _FH_UNCOMPRESSED_SIZE = 9 _FH_FILENAME_LENGTH = 10 _FH_EXTRA_FIELD_LENGTH = 11 # The "Zip64 end of central directory locator" structure, magic number, and size structEndArchive64Locator = "<4sLQL" stringEndArchive64Locator = b"PK\x06\x07" sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator) # The "Zip64 end of central directory" record, magic number, size, and indices # (section V.G in the format document) structEndArchive64 = "<4sQ2H2L4Q" stringEndArchive64 = b"PK\x06\x06" sizeEndCentDir64 = struct.calcsize(structEndArchive64) _CD64_SIGNATURE = 0 _CD64_DIRECTORY_RECSIZE = 1 _CD64_CREATE_VERSION = 2 _CD64_EXTRACT_VERSION = 3 _CD64_DISK_NUMBER = 4 _CD64_DISK_NUMBER_START = 5 _CD64_NUMBER_ENTRIES_THIS_DISK = 6 _CD64_NUMBER_ENTRIES_TOTAL = 7 _CD64_DIRECTORY_SIZE = 8 _CD64_OFFSET_START_CENTDIR = 9 _DD_SIGNATURE = 0x08074b50 _EXTRA_FIELD_STRUCT = struct.Struct('<HH') def _strip_extra(extra, xids): # Remove Extra Fields with specified IDs. unpack = _EXTRA_FIELD_STRUCT.unpack modified = False buffer = [] start = i = 0 while i + 4 <= len(extra): xid, xlen = unpack(extra[i : i + 4]) j = i + 4 + xlen if xid in xids: if i != start: buffer.append(extra[start : i]) start = j modified = True i = j if not modified: return extra return b''.join(buffer) def _check_zipfile(fp): try: if _EndRecData(fp): return True # file has correct magic number except OSError: pass return False def is_zipfile(filename): """Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too. """ result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) except OSError: pass return result def _EndRecData64(fpin, offset, endrec): """ Read the ZIP64 end-of-archive records and use that to update endrec """ try: fpin.seek(offset - sizeEndCentDir64Locator, 2) except OSError: # If the seek fails, the file is not large enough to contain a ZIP64 # end-of-archive record, so just return the end record we were given. return endrec data = fpin.read(sizeEndCentDir64Locator) if len(data) != sizeEndCentDir64Locator: return endrec sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data) if sig != stringEndArchive64Locator: return endrec if diskno != 0 or disks > 1: raise BadZipFile("zipfiles that span multiple disks are not supported") # Assume no 'zip64 extensible data' fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2) data = fpin.read(sizeEndCentDir64) if len(data) != sizeEndCentDir64: return endrec sig, sz, create_version, read_version, disk_num, disk_dir, \ dircount, dircount2, dirsize, diroffset = \ struct.unpack(structEndArchive64, data) if sig != stringEndArchive64: return endrec # Update the original endrec using data from the ZIP64 record endrec[_ECD_SIGNATURE] = sig endrec[_ECD_DISK_NUMBER] = disk_num endrec[_ECD_DISK_START] = disk_dir endrec[_ECD_ENTRIES_THIS_DISK] = dircount endrec[_ECD_ENTRIES_TOTAL] = dircount2 endrec[_ECD_SIZE] = dirsize endrec[_ECD_OFFSET] = diroffset return endrec def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except OSError: return None data = fpin.read() if (len(data) == sizeEndCentDir and data[0:4] == stringEndArchive and data[-2:] == b"\000\000"): # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append(b"") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] if len(recData) != sizeEndCentDir: # Zip file is corrupted. return None endrec = list(struct.unpack(structEndArchive, recData)) commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize] endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return None class ZipInfo (object): """Class with attributes describing each file in the ZIP archive.""" __slots__ = ( 'orig_filename', 'filename', 'date_time', 'compress_type', '_compresslevel', 'comment', 'extra', 'create_system', 'create_version', 'extract_version', 'reserved', 'flag_bits', 'volume', 'internal_attr', 'external_attr', 'header_offset', 'CRC', 'compress_size', 'file_size', '_raw_time', ) def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the # ZIP format specification. if os.sep != "/" and os.sep in filename: filename = filename.replace(os.sep, "/") self.filename = filename # Normalized file name self.date_time = date_time # year, month, day, hour, min, sec if date_time[0] < 1980: raise ValueError('ZIP does not support timestamps before 1980') # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self._compresslevel = None # Level for the compressor self.comment = b"" # Comment for each file self.extra = b"" # ZIP extra data if sys.platform == 'win32': self.create_system = 0 # System which created ZIP archive else: # Assume everything else is unix-y self.create_system = 3 # System which created ZIP archive self.create_version = DEFAULT_VERSION # Version which created ZIP archive self.extract_version = DEFAULT_VERSION # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes self.compress_size = 0 # Size of the compressed file self.file_size = 0 # Size of the uncompressed file # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # CRC CRC-32 of the uncompressed file def __repr__(self): result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)] if self.compress_type != ZIP_STORED: result.append(' compress_type=%s' % compressor_names.get(self.compress_type, self.compress_type)) hi = self.external_attr >> 16 lo = self.external_attr & 0xFFFF if hi: result.append(' filemode=%r' % stat.filemode(hi)) if lo: result.append(' external_attr=%#x' % lo) isdir = self.is_dir() if not isdir or self.file_size: result.append(' file_size=%r' % self.file_size) if ((not isdir or self.compress_size) and (self.compress_type != ZIP_STORED or self.file_size != self.compress_size)): result.append(' compress_size=%r' % self.compress_size) result.append('>') return ''.join(result) def FileHeader(self, zip64=None): """Return the per-file header as a bytes object.""" dt = self.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) if self.flag_bits & 0x08: # Set these to zero because we write them after the file data CRC = compress_size = file_size = 0 else: CRC = self.CRC compress_size = self.compress_size file_size = self.file_size extra = self.extra min_version = 0 if zip64 is None: zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT if zip64: fmt = '<HHQQ' extra = extra + struct.pack(fmt, 1, struct.calcsize(fmt)-4, file_size, compress_size) if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT: if not zip64: raise LargeZipFile("Filesize would require ZIP64 extensions") # File is larger than what fits into a 4 byte integer, # fall back to the ZIP64 extension file_size = 0xffffffff compress_size = 0xffffffff min_version = ZIP64_VERSION if self.compress_type == ZIP_BZIP2: min_version = max(BZIP2_VERSION, min_version) elif self.compress_type == ZIP_LZMA: min_version = max(LZMA_VERSION, min_version) self.extract_version = max(min_version, self.extract_version) self.create_version = max(min_version, self.create_version) filename, flag_bits = self._encodeFilenameFlags() header = struct.pack(structFileHeader, stringFileHeader, self.extract_version, self.reserved, flag_bits, self.compress_type, dostime, dosdate, CRC, compress_size, file_size, len(filename), len(extra)) return header + filename + extra def _encodeFilenameFlags(self): try: return self.filename.encode('ascii'), self.flag_bits except UnicodeEncodeError: return self.filename.encode('utf-8'), self.flag_bits | 0x800 def _decodeExtra(self): # Try to decode the extra field. extra = self.extra unpack = struct.unpack while len(extra) >= 4: tp, ln = unpack('<HH', extra[:4]) if ln+4 > len(extra): raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln)) if tp == 0x0001: data = extra[4:ln+4] # ZIP64 extension (large files and/or large archives) try: if self.file_size in (0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF): field = "File size" self.file_size, = unpack('<Q', data[:8]) data = data[8:] if self.compress_size == 0xFFFF_FFFF: field = "Compress size" self.compress_size, = unpack('<Q', data[:8]) data = data[8:] if self.header_offset == 0xFFFF_FFFF: field = "Header offset" self.header_offset, = unpack('<Q', data[:8]) except struct.error: raise BadZipFile(f"Corrupt zip64 extra field. " f"{field} not found.") from None extra = extra[ln+4:] @classmethod def from_file(cls, filename, arcname=None, *, strict_timestamps=True): """Construct an appropriate ZipInfo for a file on the filesystem. filename should be the path to a file or directory on the filesystem. arcname is the name which it will have within the archive (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). """ if isinstance(filename, os.PathLike): filename = os.fspath(filename) st = os.stat(filename) isdir = stat.S_ISDIR(st.st_mode) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] if not strict_timestamps and date_time[0] < 1980: date_time = (1980, 1, 1, 0, 0, 0) elif not strict_timestamps and date_time[0] > 2107: date_time = (2107, 12, 31, 23, 59, 59) # Create ZipInfo instance to store file information if arcname is None: arcname = filename arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] if isdir: arcname += '/' zinfo = cls(arcname, date_time) zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes if isdir: zinfo.file_size = 0 zinfo.external_attr |= 0x10 # MS-DOS directory flag else: zinfo.file_size = st.st_size return zinfo def is_dir(self): """Return True if this archive member is a directory.""" return self.filename[-1] == '/' # ZIP encryption uses the CRC32 one-byte primitive for scrambling some # internal keys. We noticed that a direct implementation is faster than # relying on binascii.crc32(). _crctable = None def _gen_crc(crc): for j in range(8): if crc & 1: crc = (crc >> 1) ^ 0xEDB88320 else: crc >>= 1 return crc # ZIP supports a password-based form of encryption. Even though known # plaintext attacks have been found against it, it is still useful # to be able to get data out of such a file. # # Usage: # zd = _ZipDecrypter(mypwd) # plain_bytes = zd(cypher_bytes) def _ZipDecrypter(pwd): key0 = 305419896 key1 = 591751049 key2 = 878082192 global _crctable if _crctable is None: _crctable = list(map(_gen_crc, range(256))) crctable = _crctable def crc32(ch, crc): """Compute the CRC32 primitive on one byte.""" return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF] def update_keys(c): nonlocal key0, key1, key2 key0 = crc32(c, key0) key1 = (key1 + (key0 & 0xFF)) & 0xFFFFFFFF key1 = (key1 * 134775813 + 1) & 0xFFFFFFFF key2 = crc32(key1 >> 24, key2) for p in pwd: update_keys(p) def decrypter(data): """Decrypt a bytes object.""" result = bytearray() append = result.append for c in data: k = key2 | 2 c ^= ((k * (k^1)) >> 8) & 0xFF update_keys(c) append(c) return bytes(result) return decrypter class LZMACompressor: def __init__(self): self._comp = None def _init(self): props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1}) self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[ lzma._decode_filter_properties(lzma.FILTER_LZMA1, props) ]) return struct.pack('<BBH', 9, 4, len(props)) + props def compress(self, data): if self._comp is None: return self._init() + self._comp.compress(data) return self._comp.compress(data) def flush(self): if self._comp is None: return self._init() + self._comp.flush() return self._comp.flush() class LZMADecompressor: def __init__(self): self._decomp = None self._unconsumed = b'' self.eof = False def decompress(self, data): if self._decomp is None: self._unconsumed += data if len(self._unconsumed) <= 4: return b'' psize, = struct.unpack('<H', self._unconsumed[2:4]) if len(self._unconsumed) <= 4 + psize: return b'' self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[ lzma._decode_filter_properties(lzma.FILTER_LZMA1, self._unconsumed[4:4 + psize]) ]) data = self._unconsumed[4 + psize:] del self._unconsumed result = self._decomp.decompress(data) self.eof = self._decomp.eof return result compressor_names = { 0: 'store', 1: 'shrink', 2: 'reduce', 3: 'reduce', 4: 'reduce', 5: 'reduce', 6: 'implode', 7: 'tokenize', 8: 'deflate', 9: 'deflate64', 10: 'implode', 12: 'bzip2', 14: 'lzma', 18: 'terse', 19: 'lz77', 97: 'wavpack', 98: 'ppmd', } def _check_compression(compression): if compression == ZIP_STORED: pass elif compression == ZIP_DEFLATED: if not zlib: raise RuntimeError( "Compression requires the (missing) zlib module") elif compression == ZIP_BZIP2: if not bz2: raise RuntimeError( "Compression requires the (missing) bz2 module") elif compression == ZIP_LZMA: if not lzma: raise RuntimeError( "Compression requires the (missing) lzma module") else: raise NotImplementedError("That compression method is not supported") def _get_compressor(compress_type, compresslevel=None): if compress_type == ZIP_DEFLATED: if compresslevel is not None: return zlib.compressobj(compresslevel, zlib.DEFLATED, -15) return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) elif compress_type == ZIP_BZIP2: if compresslevel is not None: return bz2.BZ2Compressor(compresslevel) return bz2.BZ2Compressor() # compresslevel is ignored for ZIP_LZMA elif compress_type == ZIP_LZMA: return LZMACompressor() else: return None def _get_decompressor(compress_type): _check_compression(compress_type) if compress_type == ZIP_STORED: return None elif compress_type == ZIP_DEFLATED: return zlib.decompressobj(-15) elif compress_type == ZIP_BZIP2: return bz2.BZ2Decompressor() elif compress_type == ZIP_LZMA: return LZMADecompressor() else: descr = compressor_names.get(compress_type) if descr: raise NotImplementedError("compression type %d (%s)" % (compress_type, descr)) else: raise NotImplementedError("compression type %d" % (compress_type,)) class _SharedFile: def __init__(self, file, pos, close, lock, writing): self._file = file self._pos = pos self._close = close self._lock = lock self._writing = writing self.seekable = file.seekable self.tell = file.tell def seek(self, offset, whence=0): with self._lock: if self._writing(): raise ValueError("Can't reposition in the ZIP file while " "there is an open writing handle on it. " "Close the writing handle before trying to read.") self._file.seek(offset, whence) self._pos = self._file.tell() return self._pos def read(self, n=-1): with self._lock: if self._writing(): raise ValueError("Can't read from the ZIP file while there " "is an open writing handle on it. " "Close the writing handle before trying to read.") self._file.seek(self._pos) data = self._file.read(n) self._pos = self._file.tell() return data def close(self): if self._file is not None: fileobj = self._file self._file = None self._close(fileobj) # Provide the tell method for unseekable stream class _Tellable: def __init__(self, fp): self.fp = fp self.offset = 0 def write(self, data): n = self.fp.write(data) self.offset += n return n def tell(self): return self.offset def flush(self): self.fp.flush() def close(self): self.fp.close() class ZipExtFile(io.BufferedIOBase): """File-like object for reading an archive member. Is returned by ZipFile.open(). """ # Max size supported by decompressor. MAX_N = 1 << 31 - 1 # Read from compressed files in 4k blocks. MIN_READ_SIZE = 4096 # Chunk size to read during seek MAX_SEEK_READ = 1 << 24 def __init__(self, fileobj, mode, zipinfo, pwd=None, close_fileobj=False): self._fileobj = fileobj self._pwd = pwd self._close_fileobj = close_fileobj self._compress_type = zipinfo.compress_type self._compress_left = zipinfo.compress_size self._left = zipinfo.file_size self._decompressor = _get_decompressor(self._compress_type) self._eof = False self._readbuffer = b'' self._offset = 0 self.newlines = None self.mode = mode self.name = zipinfo.filename if hasattr(zipinfo, 'CRC'): self._expected_crc = zipinfo.CRC self._running_crc = crc32(b'') else: self._expected_crc = None self._seekable = False try: if fileobj.seekable(): self._orig_compress_start = fileobj.tell() self._orig_compress_size = zipinfo.compress_size self._orig_file_size = zipinfo.file_size self._orig_start_crc = self._running_crc self._seekable = True except AttributeError: pass self._decrypter = None if pwd: if zipinfo.flag_bits & 0x8: # compare against the file type from extended local headers check_byte = (zipinfo._raw_time >> 8) & 0xff else: # compare against the CRC otherwise check_byte = (zipinfo.CRC >> 24) & 0xff h = self._init_decrypter() if h != check_byte: raise RuntimeError("Bad password for file %r" % zipinfo.orig_filename) def _init_decrypter(self): self._decrypter = _ZipDecrypter(self._pwd) # The first 12 bytes in the cypher stream is an encryption header # used to strengthen the algorithm. The first 11 bytes are # completely random, while the 12th contains the MSB of the CRC, # or the MSB of the file time depending on the header type # and is used to check the correctness of the password. header = self._fileobj.read(12) self._compress_left -= 12 return self._decrypter(header)[11] def __repr__(self): result = ['<%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)] if not self.closed: result.append(' name=%r mode=%r' % (self.name, self.mode)) if self._compress_type != ZIP_STORED: result.append(' compress_type=%s' % compressor_names.get(self._compress_type, self._compress_type)) else: result.append(' [closed]') result.append('>') return ''.join(result) def readline(self, limit=-1): """Read and return a line from the stream. If limit is specified, at most limit bytes will be read. """ if limit < 0: # Shortcut common case - newline found in buffer. i = self._readbuffer.find(b'\n', self._offset) + 1 if i > 0: line = self._readbuffer[self._offset: i] self._offset = i return line return io.BufferedIOBase.readline(self, limit) def peek(self, n=1): """Returns buffered bytes without advancing the position.""" if n > len(self._readbuffer) - self._offset: chunk = self.read(n) if len(chunk) > self._offset: self._readbuffer = chunk + self._readbuffer[self._offset:] self._offset = 0 else: self._offset -= len(chunk) # Return up to 512 bytes to reduce allocation overhead for tight loops. return self._readbuffer[self._offset: self._offset + 512] def readable(self): if self.closed: raise ValueError("I/O operation on closed file.") return True def read(self, n=-1): """Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. """ if self.closed: raise ValueError("read from closed file.") if n is None or n < 0: buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while not self._eof: buf += self._read1(self.MAX_N) return buf end = n + self._offset if end < len(self._readbuffer): buf = self._readbuffer[self._offset:end] self._offset = end return buf n = end - len(self._readbuffer) buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while n > 0 and not self._eof: data = self._read1(n) if n < len(data): self._readbuffer = data self._offset = n buf += data[:n] break buf += data n -= len(data) return buf def _update_crc(self, newdata): # Update the CRC using the given data. if self._expected_crc is None: # No need to compute the CRC if we don't have a reference value return self._running_crc = crc32(newdata, self._running_crc) # Check the CRC if we're at the end of the file if self._eof and self._running_crc != self._expected_crc: raise BadZipFile("Bad CRC-32 for file %r" % self.name) def read1(self, n): """Read up to n bytes with at most one read() system call.""" if n is None or n < 0: buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while not self._eof: data = self._read1(self.MAX_N) if data: buf += data break return buf end = n + self._offset if end < len(self._readbuffer): buf = self._readbuffer[self._offset:end] self._offset = end return buf n = end - len(self._readbuffer) buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 if n > 0: while not self._eof: data = self._read1(n) if n < len(data): self._readbuffer = data self._offset = n buf += data[:n] break if data: buf += data break return buf def _read1(self, n): # Read up to n compressed bytes with at most one read() system call, # decrypt and decompress them. if self._eof or n <= 0: return b'' # Read from file. if self._compress_type == ZIP_DEFLATED: ## Handle unconsumed data. data = self._decompressor.unconsumed_tail if n > len(data): data += self._read2(n - len(data)) else: data = self._read2(n) if self._compress_type == ZIP_STORED: self._eof = self._compress_left <= 0 elif self._compress_type == ZIP_DEFLATED: n = max(n, self.MIN_READ_SIZE) data = self._decompressor.decompress(data, n) self._eof = (self._decompressor.eof or self._compress_left <= 0 and not self._decompressor.unconsumed_tail) if self._eof: data += self._decompressor.flush() else: data = self._decompressor.decompress(data) self._eof = self._decompressor.eof or self._compress_left <= 0 data = data[:self._left] self._left -= len(data) if self._left <= 0: self._eof = True self._update_crc(data) return data def _read2(self, n): if self._compress_left <= 0: return b'' n = max(n, self.MIN_READ_SIZE) n = min(n, self._compress_left) data = self._fileobj.read(n) self._compress_left -= len(data) if not data: raise EOFError if self._decrypter is not None: data = self._decrypter(data) return data def close(self): try: if self._close_fileobj: self._fileobj.close() finally: super().close() def seekable(self): if self.closed: raise ValueError("I/O operation on closed file.") return self._seekable def seek(self, offset, whence=0): if self.closed: raise ValueError("seek on closed file.") if not self._seekable: raise io.UnsupportedOperation("underlying stream is not seekable") curr_pos = self.tell() if whence == 0: # Seek from start of file new_pos = offset elif whence == 1: # Seek from current position new_pos = curr_pos + offset elif whence == 2: # Seek from EOF new_pos = self._orig_file_size + offset else: raise ValueError("whence must be os.SEEK_SET (0), " "os.SEEK_CUR (1), or os.SEEK_END (2)") if new_pos > self._orig_file_size: new_pos = self._orig_file_size if new_pos < 0: new_pos = 0 read_offset = new_pos - curr_pos buff_offset = read_offset + self._offset if buff_offset >= 0 and buff_offset < len(self._readbuffer): # Just move the _offset index if the new position is in the _readbuffer self._offset = buff_offset read_offset = 0 elif read_offset < 0: # Position is before the current position. Reset the ZipExtFile self._fileobj.seek(self._orig_compress_start) self._running_crc = self._orig_start_crc self._compress_left = self._orig_compress_size self._left = self._orig_file_size self._readbuffer = b'' self._offset = 0 self._decompressor = _get_decompressor(self._compress_type) self._eof = False read_offset = new_pos if self._decrypter is not None: self._init_decrypter() while read_offset > 0: read_len = min(self.MAX_SEEK_READ, read_offset) self.read(read_len) read_offset -= read_len return self.tell() def tell(self): if self.closed: raise ValueError("tell on closed file.") if not self._seekable: raise io.UnsupportedOperation("underlying stream is not seekable") filepos = self._orig_file_size - self._left - len(self._readbuffer) + self._offset return filepos class _ZipWriteFile(io.BufferedIOBase): def __init__(self, zf, zinfo, zip64): self._zinfo = zinfo self._zip64 = zip64 self._zipfile = zf self._compressor = _get_compressor(zinfo.compress_type, zinfo._compresslevel) self._file_size = 0 self._compress_size = 0 self._crc = 0 @property def _fileobj(self): return self._zipfile.fp def writable(self): return True def write(self, data): if self.closed: raise ValueError('I/O operation on closed file.') # Accept any data that supports the buffer protocol if isinstance(data, (bytes, bytearray)): nbytes = len(data) else: data = memoryview(data) nbytes = data.nbytes self._file_size += nbytes self._crc = crc32(data, self._crc) if self._compressor: data = self._compressor.compress(data) self._compress_size += len(data) self._fileobj.write(data) return nbytes def close(self): if self.closed: return try: super().close() # Flush any data from the compressor, and update header info if self._compressor: buf = self._compressor.flush() self._compress_size += len(buf) self._fileobj.write(buf) self._zinfo.compress_size = self._compress_size else: self._zinfo.compress_size = self._file_size self._zinfo.CRC = self._crc self._zinfo.file_size = self._file_size # Write updated header info if self._zinfo.flag_bits & 0x08: # Write CRC and file sizes after the file data fmt = '<LLQQ' if self._zip64 else '<LLLL' self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC, self._zinfo.compress_size, self._zinfo.file_size)) self._zipfile.start_dir = self._fileobj.tell() else: if not self._zip64: if self._file_size > ZIP64_LIMIT: raise RuntimeError( 'File size unexpectedly exceeded ZIP64 limit') if self._compress_size > ZIP64_LIMIT: raise RuntimeError( 'Compressed size unexpectedly exceeded ZIP64 limit') # Seek backwards and write file header (which will now include # correct CRC and file sizes) # Preserve current position in file self._zipfile.start_dir = self._fileobj.tell() self._fileobj.seek(self._zinfo.header_offset) self._fileobj.write(self._zinfo.FileHeader(self._zip64)) self._fileobj.seek(self._zipfile.start_dir) # Successfully written: Add file to our caches self._zipfile.filelist.append(self._zinfo) self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo finally: self._zipfile._writing = False class ZipFile: """ Class with methods to open, read, write, close, list zip files. z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True, compresslevel=None) file: Either the path to the file, or a file-like object. If it is a path, the file will be opened and closed by ZipFile. mode: The mode can be either read 'r', write 'w', exclusive create 'x', or append 'a'. compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib), ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma). allowZip64: if True ZipFile will create files with ZIP64 extensions when needed, otherwise it will raise an exception when this would be necessary. compresslevel: None (default for the given compression type) or an integer specifying the level to pass to the compressor. When using ZIP_STORED or ZIP_LZMA this keyword has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted. When using ZIP_BZIP2 integers 1 through 9 are accepted. """ fp = None # Set here since __del__ checks it _windows_illegal_name_trans_table = None def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True): """Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'.""" if mode not in ('r', 'w', 'x', 'a'): raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'") _check_compression(compression) self._allowZip64 = allowZip64 self._didModify = False self.debug = 0 # Level of printing: 0 through 3 self.NameToInfo = {} # Find file info given name self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.compresslevel = compresslevel self.mode = mode self.pwd = None self._comment = b'' self._strict_timestamps = strict_timestamps # Check if we were passed a file-like object if isinstance(file, os.PathLike): file = os.fspath(file) if isinstance(file, str): # No, it's a filename self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b', 'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'} filemode = modeDict[mode] while True: try: self.fp = io.open(file, filemode) except OSError: if filemode in modeDict: filemode = modeDict[filemode] continue raise break else: self._filePassed = 1 self.fp = file self.filename = getattr(file, 'name', None) self._fileRefCnt = 1 self._lock = threading.RLock() self._seekable = True self._writing = False try: if mode == 'r': self._RealGetContents() elif mode in ('w', 'x'): # set the modified flag so central directory gets written # even if no files are added to the archive self._didModify = True try: self.start_dir = self.fp.tell() except (AttributeError, OSError): self.fp = _Tellable(self.fp) self.start_dir = 0 self._seekable = False else: # Some file-like objects can provide tell() but not seek() try: self.fp.seek(self.start_dir) except (AttributeError, OSError): self._seekable = False elif mode == 'a': try: # See if file is a zip file self._RealGetContents() # seek to start of directory and overwrite self.fp.seek(self.start_dir) except BadZipFile: # file is not a zip file, just append self.fp.seek(0, 2) # set the modified flag so central directory gets written # even if no files are added to the archive self._didModify = True self.start_dir = self.fp.tell() else: raise ValueError("Mode must be 'r', 'w', 'x', or 'a'") except: fp = self.fp self.fp = None self._fpclose(fp) raise def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __repr__(self): result = ['<%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)] if self.fp is not None: if self._filePassed: result.append(' file=%r' % self.fp) elif self.filename is not None: result.append(' filename=%r' % self.filename) result.append(' mode=%r' % self.mode) else: result.append(' [closed]') result.append('>') return ''.join(result) def _RealGetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp try: endrec = _EndRecData(fp) except OSError: raise BadZipFile("File is not a zip file") if not endrec: raise BadZipFile("File is not a zip file") if self.debug > 1: print(endrec) size_cd = endrec[_ECD_SIZE] # bytes in central directory offset_cd = endrec[_ECD_OFFSET] # offset of central directory self._comment = endrec[_ECD_COMMENT] # archive comment # "concat" is zero, unless zip was concatenated to another file concat = endrec[_ECD_LOCATION] - size_cd - offset_cd if endrec[_ECD_SIGNATURE] == stringEndArchive64: # If Zip64 extension structures are present, account for them concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator) if self.debug > 2: inferred = concat + offset_cd print("given, inferred, offset", offset_cd, inferred, concat) # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) data = fp.read(size_cd) fp = io.BytesIO(data) total = 0 while total < size_cd: centdir = fp.read(sizeCentralDir) if len(centdir) != sizeCentralDir: raise BadZipFile("Truncated central directory") centdir = struct.unpack(structCentralDir, centdir) if centdir[_CD_SIGNATURE] != stringCentralDir: raise BadZipFile("Bad magic number for central directory") if self.debug > 2: print(centdir) filename = fp.read(centdir[_CD_FILENAME_LENGTH]) flags = centdir[5] if flags & 0x800: # UTF-8 file names extension filename = filename.decode('utf-8') else: # Historical ZIP filename encoding filename = filename.decode('cp437') # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] if x.extract_version > MAX_EXTRACT_VERSION: raise NotImplementedError("zip file version %.1f" % (x.extract_version / 10)) x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x._raw_time = t x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) x._decodeExtra() x.header_offset = x.header_offset + concat self.filelist.append(x) self.NameToInfo[x.filename] = x # update total bytes read from central directory total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH] + centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]) if self.debug > 2: print("total", total) def namelist(self): """Return a list of file names in the archive.""" return [data.filename for data in self.filelist] def infolist(self): """Return a list of class ZipInfo instances for files in the archive.""" return self.filelist def printdir(self, file=None): """Print a table of contents for the zip file.""" print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"), file=file) for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size), file=file) def testzip(self): """Read all the files and check the CRC.""" chunk_size = 2 ** 20 for zinfo in self.filelist: try: # Read by chunks, to avoid an OverflowError or a # MemoryError with very large embedded files. with self.open(zinfo.filename, "r") as f: while f.read(chunk_size): # Check CRC-32 pass except BadZipFile: return zinfo.filename def getinfo(self, name): """Return the instance of ZipInfo given 'name'.""" info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info def setpassword(self, pwd): """Set default password for encrypted files.""" if pwd and not isinstance(pwd, bytes): raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__) if pwd: self.pwd = pwd else: self.pwd = None @property def comment(self): """The comment text associated with the ZIP file.""" return self._comment @comment.setter def comment(self, comment): if not isinstance(comment, bytes): raise TypeError("comment: expected bytes, got %s" % type(comment).__name__) # check for valid comment length if len(comment) > ZIP_MAX_COMMENT: import warnings warnings.warn('Archive comment is too long; truncating to %d bytes' % ZIP_MAX_COMMENT, stacklevel=2) comment = comment[:ZIP_MAX_COMMENT] self._comment = comment self._didModify = True def read(self, name, pwd=None): """Return file bytes for name.""" with self.open(name, "r", pwd) as fp: return fp.read() def open(self, name, mode="r", pwd=None, *, force_zip64=False): """Return file-like object for 'name'. name is a string for the file name within the ZIP file, or a ZipInfo object. mode should be 'r' to read a file already in the ZIP file, or 'w' to write to a file newly added to the archive. pwd is the password to decrypt files (only used for reading). When writing, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large files. If the size is known in advance, it is best to pass a ZipInfo instance for name, with zinfo.file_size set. """ if mode not in {"r", "w"}: raise ValueError('open() requires mode "r" or "w"') if pwd and not isinstance(pwd, bytes): raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__) if pwd and (mode == "w"): raise ValueError("pwd is only supported for reading files") if not self.fp: raise ValueError( "Attempt to use ZIP archive that was already closed") # Make sure we have an info object if isinstance(name, ZipInfo): # 'name' is already an info object zinfo = name elif mode == 'w': zinfo = ZipInfo(name) zinfo.compress_type = self.compression zinfo._compresslevel = self.compresslevel else: # Get info object for name zinfo = self.getinfo(name) if mode == 'w': return self._open_to_write(zinfo, force_zip64=force_zip64) if self._writing: raise ValueError("Can't read from the ZIP file while there " "is an open writing handle on it. " "Close the writing handle before trying to read.") # Open for reading: self._fileRefCnt += 1 zef_file = _SharedFile(self.fp, zinfo.header_offset, self._fpclose, self._lock, lambda: self._writing) try: # Skip the file header: fheader = zef_file.read(sizeFileHeader) if len(fheader) != sizeFileHeader: raise BadZipFile("Truncated file header") fheader = struct.unpack(structFileHeader, fheader) if fheader[_FH_SIGNATURE] != stringFileHeader: raise BadZipFile("Bad magic number for file header") fname = zef_file.read(fheader[_FH_FILENAME_LENGTH]) if fheader[_FH_EXTRA_FIELD_LENGTH]: zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH]) if zinfo.flag_bits & 0x20: # Zip 2.7: compressed patched data raise NotImplementedError("compressed patched data (flag bit 5)") if zinfo.flag_bits & 0x40: # strong encryption raise NotImplementedError("strong encryption (flag bit 6)") if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800: # UTF-8 filename fname_str = fname.decode("utf-8") else: fname_str = fname.decode("cp437") if fname_str != zinfo.orig_filename: raise BadZipFile( 'File name in directory %r and header %r differ.' % (zinfo.orig_filename, fname)) # check for encrypted flag & handle password is_encrypted = zinfo.flag_bits & 0x1 if is_encrypted: if not pwd: pwd = self.pwd if not pwd: raise RuntimeError("File %r is encrypted, password " "required for extraction" % name) else: pwd = None return ZipExtFile(zef_file, mode, zinfo, pwd, True) except: zef_file.close() raise def _open_to_write(self, zinfo, force_zip64=False): if force_zip64 and not self._allowZip64: raise ValueError( "force_zip64 is True, but allowZip64 was False when opening " "the ZIP file." ) if self._writing: raise ValueError("Can't write to the ZIP file while there is " "another write handle open on it. " "Close the first handle before opening another.") # Size and CRC are overwritten with correct data after processing the file zinfo.compress_size = 0 zinfo.CRC = 0 zinfo.flag_bits = 0x00 if zinfo.compress_type == ZIP_LZMA: # Compressed data includes an end-of-stream (EOS) marker zinfo.flag_bits |= 0x02 if not self._seekable: zinfo.flag_bits |= 0x08 if not zinfo.external_attr: zinfo.external_attr = 0o600 << 16 # permissions: ?rw------- # Compressed size can be larger than uncompressed size zip64 = self._allowZip64 and \ (force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT) if self._seekable: self.fp.seek(self.start_dir) zinfo.header_offset = self.fp.tell() self._writecheck(zinfo) self._didModify = True self.fp.write(zinfo.FileHeader(zip64)) self._writing = True return _ZipWriteFile(self, zinfo, zip64) def extract(self, member, path=None, pwd=None): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'. """ if path is None: path = os.getcwd() else: path = os.fspath(path) return self._extract_member(member, path, pwd) def extractall(self, path=None, members=None, pwd=None): """Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist(). """ if members is None: members = self.namelist() if path is None: path = os.getcwd() else: path = os.fspath(path) for zipinfo in members: self._extract_member(zipinfo, path, pwd) @classmethod def _sanitize_windows_name(cls, arcname, pathsep): """Replace bad characters and remove trailing dots from parts.""" table = cls._windows_illegal_name_trans_table if not table: illegal = ':<>|"?*' table = str.maketrans(illegal, '_' * len(illegal)) cls._windows_illegal_name_trans_table = table arcname = arcname.translate(table) # remove trailing dots arcname = (x.rstrip('.') for x in arcname.split(pathsep)) # rejoin, removing empty parts. arcname = pathsep.join(x for x in arcname if x) return arcname def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) # build the destination pathname, replacing # forward slashes to platform specific separators. arcname = member.filename.replace('/', os.path.sep) if os.path.altsep: arcname = arcname.replace(os.path.altsep, os.path.sep) # interpret absolute pathname as relative, remove drive letter or # UNC path, redundant separators, "." and ".." components. arcname = os.path.splitdrive(arcname)[1] invalid_path_parts = ('', os.path.curdir, os.path.pardir) arcname = os.path.sep.join(x for x in arcname.split(os.path.sep) if x not in invalid_path_parts) if os.path.sep == '\\': # filter illegal characters on Windows arcname = self._sanitize_windows_name(arcname, os.path.sep) targetpath = os.path.join(targetpath, arcname) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.is_dir(): if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath with self.open(member, pwd=pwd) as source, \ open(targetpath, "wb") as target: shutil.copyfileobj(source, target) return targetpath def _writecheck(self, zinfo): """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: import warnings warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3) if self.mode not in ('w', 'x', 'a'): raise ValueError("write() requires mode 'w', 'x', or 'a'") if not self.fp: raise ValueError( "Attempt to write ZIP archive that was already closed") _check_compression(zinfo.compress_type) if not self._allowZip64: requires_zip64 = None if len(self.filelist) >= ZIP_FILECOUNT_LIMIT: requires_zip64 = "Files count" elif zinfo.file_size > ZIP64_LIMIT: requires_zip64 = "Filesize" elif zinfo.header_offset > ZIP64_LIMIT: requires_zip64 = "Zipfile size" if requires_zip64: raise LargeZipFile(requires_zip64 + " would require ZIP64 extensions") def write(self, filename, arcname=None, compress_type=None, compresslevel=None): """Put the bytes from filename into the archive under the name arcname.""" if not self.fp: raise ValueError( "Attempt to write to ZIP archive that was already closed") if self._writing: raise ValueError( "Can't write to ZIP archive while an open writing handle exists" ) zinfo = ZipInfo.from_file(filename, arcname, strict_timestamps=self._strict_timestamps) if zinfo.is_dir(): zinfo.compress_size = 0 zinfo.CRC = 0 else: if compress_type is not None: zinfo.compress_type = compress_type else: zinfo.compress_type = self.compression if compresslevel is not None: zinfo._compresslevel = compresslevel else: zinfo._compresslevel = self.compresslevel if zinfo.is_dir(): with self._lock: if self._seekable: self.fp.seek(self.start_dir) zinfo.header_offset = self.fp.tell() # Start of header bytes if zinfo.compress_type == ZIP_LZMA: # Compressed data includes an end-of-stream (EOS) marker zinfo.flag_bits |= 0x02 self._writecheck(zinfo) self._didModify = True self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo self.fp.write(zinfo.FileHeader(False)) self.start_dir = self.fp.tell() else: with open(filename, "rb") as src, self.open(zinfo, 'w') as dest: shutil.copyfileobj(src, dest, 1024*8) def writestr(self, zinfo_or_arcname, data, compress_type=None, compresslevel=None): """Write a file into the archive. The contents is 'data', which may be either a 'str' or a 'bytes' instance; if it is a 'str', it is encoded as UTF-8 first. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" if isinstance(data, str): data = data.encode("utf-8") if not isinstance(zinfo_or_arcname, ZipInfo): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())[:6]) zinfo.compress_type = self.compression zinfo._compresslevel = self.compresslevel if zinfo.filename[-1] == '/': zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x zinfo.external_attr |= 0x10 # MS-DOS directory flag else: zinfo.external_attr = 0o600 << 16 # ?rw------- else: zinfo = zinfo_or_arcname if not self.fp: raise ValueError( "Attempt to write to ZIP archive that was already closed") if self._writing: raise ValueError( "Can't write to ZIP archive while an open writing handle exists." ) if compress_type is not None: zinfo.compress_type = compress_type if compresslevel is not None: zinfo._compresslevel = compresslevel zinfo.file_size = len(data) # Uncompressed size with self._lock: with self.open(zinfo, mode='w') as dest: dest.write(data) def __del__(self): """Call the "close()" method in case the user forgot.""" self.close() def close(self): """Close the file, and for mode 'w', 'x' and 'a' write the ending records.""" if self.fp is None: return if self._writing: raise ValueError("Can't close the ZIP file while there is " "an open writing handle on it. " "Close the writing handle before closing the zip.") try: if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records with self._lock: if self._seekable: self.fp.seek(self.start_dir) self._write_end_record() finally: fp = self.fp self.fp = None self._fpclose(fp) def _write_end_record(self): for zinfo in self.filelist: # write central directory dt = zinfo.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) extra = [] if zinfo.file_size > ZIP64_LIMIT \ or zinfo.compress_size > ZIP64_LIMIT: extra.append(zinfo.file_size) extra.append(zinfo.compress_size) file_size = 0xffffffff compress_size = 0xffffffff else: file_size = zinfo.file_size compress_size = zinfo.compress_size if zinfo.header_offset > ZIP64_LIMIT: extra.append(zinfo.header_offset) header_offset = 0xffffffff else: header_offset = zinfo.header_offset extra_data = zinfo.extra min_version = 0 if extra: # Append a ZIP64 field to the extra's extra_data = _strip_extra(extra_data, (1,)) extra_data = struct.pack( '<HH' + 'Q'*len(extra), 1, 8*len(extra), *extra) + extra_data min_version = ZIP64_VERSION if zinfo.compress_type == ZIP_BZIP2: min_version = max(BZIP2_VERSION, min_version) elif zinfo.compress_type == ZIP_LZMA: min_version = max(LZMA_VERSION, min_version) extract_version = max(min_version, zinfo.extract_version) create_version = max(min_version, zinfo.create_version) filename, flag_bits = zinfo._encodeFilenameFlags() centdir = struct.pack(structCentralDir, stringCentralDir, create_version, zinfo.create_system, extract_version, zinfo.reserved, flag_bits, zinfo.compress_type, dostime, dosdate, zinfo.CRC, compress_size, file_size, len(filename), len(extra_data), len(zinfo.comment), 0, zinfo.internal_attr, zinfo.external_attr, header_offset) self.fp.write(centdir) self.fp.write(filename) self.fp.write(extra_data) self.fp.write(zinfo.comment) pos2 = self.fp.tell() # Write end-of-zip-archive record centDirCount = len(self.filelist) centDirSize = pos2 - self.start_dir centDirOffset = self.start_dir requires_zip64 = None if centDirCount > ZIP_FILECOUNT_LIMIT: requires_zip64 = "Files count" elif centDirOffset > ZIP64_LIMIT: requires_zip64 = "Central directory offset" elif centDirSize > ZIP64_LIMIT: requires_zip64 = "Central directory size" if requires_zip64: # Need to write the ZIP64 end-of-archive records if not self._allowZip64: raise LargeZipFile(requires_zip64 + " would require ZIP64 extensions") zip64endrec = struct.pack( structEndArchive64, stringEndArchive64, 44, 45, 45, 0, 0, centDirCount, centDirCount, centDirSize, centDirOffset) self.fp.write(zip64endrec) zip64locrec = struct.pack( structEndArchive64Locator, stringEndArchive64Locator, 0, pos2, 1) self.fp.write(zip64locrec) centDirCount = min(centDirCount, 0xFFFF) centDirSize = min(centDirSize, 0xFFFFFFFF) centDirOffset = min(centDirOffset, 0xFFFFFFFF) endrec = struct.pack(structEndArchive, stringEndArchive, 0, 0, centDirCount, centDirCount, centDirSize, centDirOffset, len(self._comment)) self.fp.write(endrec) self.fp.write(self._comment) if self.mode == "a": self.fp.truncate() self.fp.flush() def _fpclose(self, fp): assert self._fileRefCnt > 0 self._fileRefCnt -= 1 if not self._fileRefCnt and not self._filePassed: fp.close() class PyZipFile(ZipFile): """Class to create ZIP archives with Python library files and packages.""" def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True, optimize=-1): ZipFile.__init__(self, file, mode=mode, compression=compression, allowZip64=allowZip64) self._optimize = optimize def writepy(self, pathname, basename="", filterfunc=None): """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyc. This method will compile the module.py into module.pyc if necessary. If filterfunc(pathname) is given, it is called with every argument. When it is False, the file or directory is skipped. """ pathname = os.fspath(pathname) if filterfunc and not filterfunc(pathname): if self.debug: label = 'path' if os.path.isdir(pathname) else 'file' print('%s %r skipped by filterfunc' % (label, pathname)) return dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print("Adding package in", pathname, "as", basename) fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) dirlist = sorted(os.listdir(pathname)) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename, filterfunc=filterfunc) # Recursive call elif ext == ".py": if filterfunc and not filterfunc(path): if self.debug: print('file %r skipped by filterfunc' % path) continue fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print("Adding files from directory", pathname) for filename in sorted(os.listdir(pathname)): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": if filterfunc and not filterfunc(path): if self.debug: print('file %r skipped by filterfunc' % path) continue fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError( 'Files added with writepy() must end with ".py"') fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print("Adding file", arcname) self.write(fname, arcname) def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ def _compile(file, optimize=-1): import py_compile if self.debug: print("Compiling", file) try: py_compile.compile(file, doraise=True, optimize=optimize) except py_compile.PyCompileError as err: print(err.msg) return False return True file_py = pathname + ".py" file_pyc = pathname + ".pyc" pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) if self._optimize == -1: # legacy mode: use whatever file is present if (os.path.isfile(file_pyc) and os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): # Use .pyc file. arcname = fname = file_pyc elif (os.path.isfile(pycache_opt0) and os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt0 arcname = file_pyc elif (os.path.isfile(pycache_opt1) and os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt1 arcname = file_pyc elif (os.path.isfile(pycache_opt2) and os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt2 arcname = file_pyc else: # Compile py into PEP 3147 pyc file. if _compile(file_py): if sys.flags.optimize == 0: fname = pycache_opt0 elif sys.flags.optimize == 1: fname = pycache_opt1 else: fname = pycache_opt2 arcname = file_pyc else: fname = arcname = file_py else: # new mode: use given optimization level if self._optimize == 0: fname = pycache_opt0 arcname = file_pyc else: arcname = file_pyc if self._optimize == 1: fname = pycache_opt1 elif self._optimize == 2: fname = pycache_opt2 else: msg = "invalid value for 'optimize': {!r}".format(self._optimize) raise ValueError(msg) if not (os.path.isfile(fname) and os.stat(fname).st_mtime >= os.stat(file_py).st_mtime): if not _compile(file_py, optimize=self._optimize): fname = arcname = file_py archivename = os.path.split(arcname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename) def _parents(path): """ Given a path with elements separated by posixpath.sep, generate all parents of that path. >>> list(_parents('b/d')) ['b'] >>> list(_parents('/b/d/')) ['/b'] >>> list(_parents('b/d/f/')) ['b/d', 'b'] >>> list(_parents('b')) [] >>> list(_parents('')) [] """ return itertools.islice(_ancestry(path), 1, None) def _ancestry(path): """ Given a path with elements separated by posixpath.sep, generate all elements of that path >>> list(_ancestry('b/d')) ['b/d', 'b'] >>> list(_ancestry('/b/d/')) ['/b/d', '/b'] >>> list(_ancestry('b/d/f/')) ['b/d/f', 'b/d', 'b'] >>> list(_ancestry('b')) ['b'] >>> list(_ancestry('')) [] """ path = path.rstrip(posixpath.sep) while path and path != posixpath.sep: yield path path, tail = posixpath.split(path) _dedupe = dict.fromkeys """Deduplicate an iterable in original order""" def _difference(minuend, subtrahend): """ Return items in minuend not in subtrahend, retaining order with O(1) lookup. """ return itertools.filterfalse(set(subtrahend).__contains__, minuend) class CompleteDirs(ZipFile): """ A ZipFile subclass that ensures that implied directories are always included in the namelist. """ @staticmethod def _implied_dirs(names): parents = itertools.chain.from_iterable(map(_parents, names)) as_dirs = (p + posixpath.sep for p in parents) return _dedupe(_difference(as_dirs, names)) def namelist(self): names = super(CompleteDirs, self).namelist() return names + list(self._implied_dirs(names)) def _name_set(self): return set(self.namelist()) def resolve_dir(self, name): """ If the name represents a directory, return that name as a directory (with the trailing slash). """ names = self._name_set() dirname = name + '/' dir_match = name not in names and dirname in names return dirname if dir_match else name @classmethod def make(cls, source): """ Given a source (filename or zipfile), return an appropriate CompleteDirs subclass. """ if isinstance(source, CompleteDirs): return source if not isinstance(source, ZipFile): return cls(source) # Only allow for FastPath when supplied zipfile is read-only if 'r' not in source.mode: cls = CompleteDirs res = cls.__new__(cls) vars(res).update(vars(source)) return res class FastLookup(CompleteDirs): """ ZipFile subclass to ensure implicit dirs exist and are resolved rapidly. """ def namelist(self): with contextlib.suppress(AttributeError): return self.__names self.__names = super(FastLookup, self).namelist() return self.__names def _name_set(self): with contextlib.suppress(AttributeError): return self.__lookup self.__lookup = super(FastLookup, self)._name_set() return self.__lookup class Path: """ A pathlib-compatible interface for zip files. Consider a zip file with this structure:: . ├── a.txt └── b ├── c.txt └── d └── e.txt >>> data = io.BytesIO() >>> zf = ZipFile(data, 'w') >>> zf.writestr('a.txt', 'content of a') >>> zf.writestr('b/c.txt', 'content of c') >>> zf.writestr('b/d/e.txt', 'content of e') >>> zf.filename = 'abcde.zip' Path accepts the zipfile object itself or a filename >>> root = Path(zf) From there, several path operations are available. Directory iteration (including the zip file itself): >>> a, b = root.iterdir() >>> a Path('abcde.zip', 'a.txt') >>> b Path('abcde.zip', 'b/') name property: >>> b.name 'b' join with divide operator: >>> c = b / 'c.txt' >>> c Path('abcde.zip', 'b/c.txt') >>> c.name 'c.txt' Read text: >>> c.read_text() 'content of c' existence: >>> c.exists() True >>> (b / 'missing.txt').exists() False Coercion to string: >>> str(c) 'abcde.zip/b/c.txt' """ __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" def __init__(self, root, at=""): self.root = FastLookup.make(root) self.at = at def open(self, mode='r', *args, **kwargs): """ Open this entry as text or binary following the semantics of ``pathlib.Path.open()`` by passing arguments through to io.TextIOWrapper(). """ pwd = kwargs.pop('pwd', None) zip_mode = mode[0] stream = self.root.open(self.at, zip_mode, pwd=pwd) if 'b' in mode: if args or kwargs: raise ValueError("encoding args invalid for binary operation") return stream return io.TextIOWrapper(stream, *args, **kwargs) @property def name(self): return posixpath.basename(self.at.rstrip("/")) def read_text(self, *args, **kwargs): with self.open('r', *args, **kwargs) as strm: return strm.read() def read_bytes(self): with self.open('rb') as strm: return strm.read() def _is_child(self, path): return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") def _next(self, at): return Path(self.root, at) def is_dir(self): return not self.at or self.at.endswith("/") def is_file(self): return not self.is_dir() def exists(self): return self.at in self.root._name_set() def iterdir(self): if not self.is_dir(): raise ValueError("Can't listdir a file") subs = map(self._next, self.root.namelist()) return filter(self._is_child, subs) def __str__(self): return posixpath.join(self.root.filename, self.at) def __repr__(self): return self.__repr.format(self=self) def joinpath(self, add): next = posixpath.join(self.at, add) return self._next(self.root.resolve_dir(next)) __truediv__ = joinpath @property def parent(self): parent_at = posixpath.dirname(self.at.rstrip('/')) if parent_at: parent_at += '/' return self._next(parent_at) def main(args=None): import argparse description = 'A simple command-line interface for zipfile module.' parser = argparse.ArgumentParser(description=description) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', metavar='<zipfile>', help='Show listing of a zipfile') group.add_argument('-e', '--extract', nargs=2, metavar=('<zipfile>', '<output_dir>'), help='Extract zipfile into target dir') group.add_argument('-c', '--create', nargs='+', metavar=('<name>', '<file>'), help='Create zipfile from sources') group.add_argument('-t', '--test', metavar='<zipfile>', help='Test if a zipfile is valid') args = parser.parse_args(args) if args.test is not None: src = args.test with ZipFile(src, 'r') as zf: badfile = zf.testzip() if badfile: print("The following enclosed file is corrupted: {!r}".format(badfile)) print("Done testing") elif args.list is not None: src = args.list with ZipFile(src, 'r') as zf: zf.printdir() elif args.extract is not None: src, curdir = args.extract with ZipFile(src, 'r') as zf: zf.extractall(curdir) elif args.create is not None: zip_name = args.create.pop(0) files = args.create def addToZip(zf, path, zippath): if os.path.isfile(path): zf.write(path, zippath, ZIP_DEFLATED) elif os.path.isdir(path): if zippath: zf.write(path, zippath) for nm in sorted(os.listdir(path)): addToZip(zf, os.path.join(path, nm), os.path.join(zippath, nm)) # else: ignore with ZipFile(zip_name, 'w') as zf: for path in files: zippath = os.path.basename(path) if not zippath: zippath = os.path.basename(os.path.dirname(path)) if zippath in ('', os.curdir, os.pardir): zippath = '' addToZip(zf, path, zippath) if __name__ == "__main__": main()
35.897373
102
0.569471
import binascii import importlib.util import io import itertools import os import posixpath import shutil import stat import struct import sys import threading import time import contextlib try: import zlib crc32 = zlib.crc32 except ImportError: zlib = None crc32 = binascii.crc32 try: import bz2 except ImportError: bz2 = None try: import lzma except ImportError: lzma = None __all__ = ["BadZipFile", "BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA", "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile", "Path"] class BadZipFile(Exception): pass class LargeZipFile(Exception): error = BadZipfile = BadZipFile ZIP64_LIMIT = (1 << 31) - 1 ZIP_FILECOUNT_LIMIT = (1 << 16) - 1 ZIP_MAX_COMMENT = (1 << 16) - 1 ZIP_STORED = 0 ZIP_DEFLATED = 8 ZIP_BZIP2 = 12 ZIP_LZMA = 14 DEFAULT_VERSION = 20 ZIP64_VERSION = 45 BZIP2_VERSION = 46 LZMA_VERSION = 63 MAX_EXTRACT_VERSION = 63 structEndArchive = b"<4s4H2LH" stringEndArchive = b"PK\005\006" sizeEndCentDir = struct.calcsize(structEndArchive) _ECD_SIGNATURE = 0 _ECD_DISK_NUMBER = 1 _ECD_DISK_START = 2 _ECD_ENTRIES_THIS_DISK = 3 _ECD_ENTRIES_TOTAL = 4 _ECD_SIZE = 5 _ECD_OFFSET = 6 _ECD_COMMENT_SIZE = 7 _ECD_COMMENT = 8 _ECD_LOCATION = 9 structCentralDir = "<4s4B4HL2L5H2L" stringCentralDir = b"PK\001\002" sizeCentralDir = struct.calcsize(structCentralDir) _CD_SIGNATURE = 0 _CD_CREATE_VERSION = 1 _CD_CREATE_SYSTEM = 2 _CD_EXTRACT_VERSION = 3 _CD_EXTRACT_SYSTEM = 4 _CD_FLAG_BITS = 5 _CD_COMPRESS_TYPE = 6 _CD_TIME = 7 _CD_DATE = 8 _CD_CRC = 9 _CD_COMPRESSED_SIZE = 10 _CD_UNCOMPRESSED_SIZE = 11 _CD_FILENAME_LENGTH = 12 _CD_EXTRA_FIELD_LENGTH = 13 _CD_COMMENT_LENGTH = 14 _CD_DISK_NUMBER_START = 15 _CD_INTERNAL_FILE_ATTRIBUTES = 16 _CD_EXTERNAL_FILE_ATTRIBUTES = 17 _CD_LOCAL_HEADER_OFFSET = 18 structFileHeader = "<4s2B4HL2L2H" stringFileHeader = b"PK\003\004" sizeFileHeader = struct.calcsize(structFileHeader) _FH_SIGNATURE = 0 _FH_EXTRACT_VERSION = 1 _FH_EXTRACT_SYSTEM = 2 _FH_GENERAL_PURPOSE_FLAG_BITS = 3 _FH_COMPRESSION_METHOD = 4 _FH_LAST_MOD_TIME = 5 _FH_LAST_MOD_DATE = 6 _FH_CRC = 7 _FH_COMPRESSED_SIZE = 8 _FH_UNCOMPRESSED_SIZE = 9 _FH_FILENAME_LENGTH = 10 _FH_EXTRA_FIELD_LENGTH = 11 structEndArchive64Locator = "<4sLQL" stringEndArchive64Locator = b"PK\x06\x07" sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator) structEndArchive64 = "<4sQ2H2L4Q" stringEndArchive64 = b"PK\x06\x06" sizeEndCentDir64 = struct.calcsize(structEndArchive64) _CD64_SIGNATURE = 0 _CD64_DIRECTORY_RECSIZE = 1 _CD64_CREATE_VERSION = 2 _CD64_EXTRACT_VERSION = 3 _CD64_DISK_NUMBER = 4 _CD64_DISK_NUMBER_START = 5 _CD64_NUMBER_ENTRIES_THIS_DISK = 6 _CD64_NUMBER_ENTRIES_TOTAL = 7 _CD64_DIRECTORY_SIZE = 8 _CD64_OFFSET_START_CENTDIR = 9 _DD_SIGNATURE = 0x08074b50 _EXTRA_FIELD_STRUCT = struct.Struct('<HH') def _strip_extra(extra, xids): unpack = _EXTRA_FIELD_STRUCT.unpack modified = False buffer = [] start = i = 0 while i + 4 <= len(extra): xid, xlen = unpack(extra[i : i + 4]) j = i + 4 + xlen if xid in xids: if i != start: buffer.append(extra[start : i]) start = j modified = True i = j if not modified: return extra return b''.join(buffer) def _check_zipfile(fp): try: if _EndRecData(fp): return True except OSError: pass return False def is_zipfile(filename): result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) except OSError: pass return result def _EndRecData64(fpin, offset, endrec): try: fpin.seek(offset - sizeEndCentDir64Locator, 2) except OSError: return endrec data = fpin.read(sizeEndCentDir64Locator) if len(data) != sizeEndCentDir64Locator: return endrec sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data) if sig != stringEndArchive64Locator: return endrec if diskno != 0 or disks > 1: raise BadZipFile("zipfiles that span multiple disks are not supported") fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2) data = fpin.read(sizeEndCentDir64) if len(data) != sizeEndCentDir64: return endrec sig, sz, create_version, read_version, disk_num, disk_dir, \ dircount, dircount2, dirsize, diroffset = \ struct.unpack(structEndArchive64, data) if sig != stringEndArchive64: return endrec endrec[_ECD_SIGNATURE] = sig endrec[_ECD_DISK_NUMBER] = disk_num endrec[_ECD_DISK_START] = disk_dir endrec[_ECD_ENTRIES_THIS_DISK] = dircount endrec[_ECD_ENTRIES_TOTAL] = dircount2 endrec[_ECD_SIZE] = dirsize endrec[_ECD_OFFSET] = diroffset return endrec def _EndRecData(fpin): fpin.seek(0, 2) filesize = fpin.tell() try: fpin.seek(-sizeEndCentDir, 2) except OSError: return None data = fpin.read() if (len(data) == sizeEndCentDir and data[0:4] == stringEndArchive and data[-2:] == b"\000\000"): endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append(b"") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] if len(recData) != sizeEndCentDir: # Zip file is corrupted. return None endrec = list(struct.unpack(structEndArchive, recData)) commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize] endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return None class ZipInfo (object): __slots__ = ( 'orig_filename', 'filename', 'date_time', 'compress_type', '_compresslevel', 'comment', 'extra', 'create_system', 'create_version', 'extract_version', 'reserved', 'flag_bits', 'volume', 'internal_attr', 'external_attr', 'header_offset', 'CRC', 'compress_size', 'file_size', '_raw_time', ) def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the # ZIP format specification. if os.sep != "/" and os.sep in filename: filename = filename.replace(os.sep, "/") self.filename = filename # Normalized file name self.date_time = date_time # year, month, day, hour, min, sec if date_time[0] < 1980: raise ValueError('ZIP does not support timestamps before 1980') # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self._compresslevel = None # Level for the compressor self.comment = b"" # Comment for each file self.extra = b"" # ZIP extra data if sys.platform == 'win32': self.create_system = 0 # System which created ZIP archive else: # Assume everything else is unix-y self.create_system = 3 # System which created ZIP archive self.create_version = DEFAULT_VERSION # Version which created ZIP archive self.extract_version = DEFAULT_VERSION # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes self.compress_size = 0 # Size of the compressed file self.file_size = 0 # Size of the uncompressed file # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # CRC CRC-32 of the uncompressed file def __repr__(self): result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)] if self.compress_type != ZIP_STORED: result.append(' compress_type=%s' % compressor_names.get(self.compress_type, self.compress_type)) hi = self.external_attr >> 16 lo = self.external_attr & 0xFFFF if hi: result.append(' filemode=%r' % stat.filemode(hi)) if lo: result.append(' external_attr=% isdir = self.is_dir() if not isdir or self.file_size: result.append(' file_size=%r' % self.file_size) if ((not isdir or self.compress_size) and (self.compress_type != ZIP_STORED or self.file_size != self.compress_size)): result.append(' compress_size=%r' % self.compress_size) result.append('>') return ''.join(result) def FileHeader(self, zip64=None): dt = self.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) if self.flag_bits & 0x08: # Set these to zero because we write them after the file data CRC = compress_size = file_size = 0 else: CRC = self.CRC compress_size = self.compress_size file_size = self.file_size extra = self.extra min_version = 0 if zip64 is None: zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT if zip64: fmt = '<HHQQ' extra = extra + struct.pack(fmt, 1, struct.calcsize(fmt)-4, file_size, compress_size) if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT: if not zip64: raise LargeZipFile("Filesize would require ZIP64 extensions") # File is larger than what fits into a 4 byte integer, # fall back to the ZIP64 extension file_size = 0xffffffff compress_size = 0xffffffff min_version = ZIP64_VERSION if self.compress_type == ZIP_BZIP2: min_version = max(BZIP2_VERSION, min_version) elif self.compress_type == ZIP_LZMA: min_version = max(LZMA_VERSION, min_version) self.extract_version = max(min_version, self.extract_version) self.create_version = max(min_version, self.create_version) filename, flag_bits = self._encodeFilenameFlags() header = struct.pack(structFileHeader, stringFileHeader, self.extract_version, self.reserved, flag_bits, self.compress_type, dostime, dosdate, CRC, compress_size, file_size, len(filename), len(extra)) return header + filename + extra def _encodeFilenameFlags(self): try: return self.filename.encode('ascii'), self.flag_bits except UnicodeEncodeError: return self.filename.encode('utf-8'), self.flag_bits | 0x800 def _decodeExtra(self): # Try to decode the extra field. extra = self.extra unpack = struct.unpack while len(extra) >= 4: tp, ln = unpack('<HH', extra[:4]) if ln+4 > len(extra): raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln)) if tp == 0x0001: data = extra[4:ln+4] # ZIP64 extension (large files and/or large archives) try: if self.file_size in (0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF): field = "File size" self.file_size, = unpack('<Q', data[:8]) data = data[8:] if self.compress_size == 0xFFFF_FFFF: field = "Compress size" self.compress_size, = unpack('<Q', data[:8]) data = data[8:] if self.header_offset == 0xFFFF_FFFF: field = "Header offset" self.header_offset, = unpack('<Q', data[:8]) except struct.error: raise BadZipFile(f"Corrupt zip64 extra field. " f"{field} not found.") from None extra = extra[ln+4:] @classmethod def from_file(cls, filename, arcname=None, *, strict_timestamps=True): if isinstance(filename, os.PathLike): filename = os.fspath(filename) st = os.stat(filename) isdir = stat.S_ISDIR(st.st_mode) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] if not strict_timestamps and date_time[0] < 1980: date_time = (1980, 1, 1, 0, 0, 0) elif not strict_timestamps and date_time[0] > 2107: date_time = (2107, 12, 31, 23, 59, 59) # Create ZipInfo instance to store file information if arcname is None: arcname = filename arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] if isdir: arcname += '/' zinfo = cls(arcname, date_time) zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes if isdir: zinfo.file_size = 0 zinfo.external_attr |= 0x10 # MS-DOS directory flag else: zinfo.file_size = st.st_size return zinfo def is_dir(self): return self.filename[-1] == '/' # ZIP encryption uses the CRC32 one-byte primitive for scrambling some # internal keys. We noticed that a direct implementation is faster than # relying on binascii.crc32(). _crctable = None def _gen_crc(crc): for j in range(8): if crc & 1: crc = (crc >> 1) ^ 0xEDB88320 else: crc >>= 1 return crc # ZIP supports a password-based form of encryption. Even though known # plaintext attacks have been found against it, it is still useful # to be able to get data out of such a file. # # Usage: # zd = _ZipDecrypter(mypwd) # plain_bytes = zd(cypher_bytes) def _ZipDecrypter(pwd): key0 = 305419896 key1 = 591751049 key2 = 878082192 global _crctable if _crctable is None: _crctable = list(map(_gen_crc, range(256))) crctable = _crctable def crc32(ch, crc): return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF] def update_keys(c): nonlocal key0, key1, key2 key0 = crc32(c, key0) key1 = (key1 + (key0 & 0xFF)) & 0xFFFFFFFF key1 = (key1 * 134775813 + 1) & 0xFFFFFFFF key2 = crc32(key1 >> 24, key2) for p in pwd: update_keys(p) def decrypter(data): result = bytearray() append = result.append for c in data: k = key2 | 2 c ^= ((k * (k^1)) >> 8) & 0xFF update_keys(c) append(c) return bytes(result) return decrypter class LZMACompressor: def __init__(self): self._comp = None def _init(self): props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1}) self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[ lzma._decode_filter_properties(lzma.FILTER_LZMA1, props) ]) return struct.pack('<BBH', 9, 4, len(props)) + props def compress(self, data): if self._comp is None: return self._init() + self._comp.compress(data) return self._comp.compress(data) def flush(self): if self._comp is None: return self._init() + self._comp.flush() return self._comp.flush() class LZMADecompressor: def __init__(self): self._decomp = None self._unconsumed = b'' self.eof = False def decompress(self, data): if self._decomp is None: self._unconsumed += data if len(self._unconsumed) <= 4: return b'' psize, = struct.unpack('<H', self._unconsumed[2:4]) if len(self._unconsumed) <= 4 + psize: return b'' self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[ lzma._decode_filter_properties(lzma.FILTER_LZMA1, self._unconsumed[4:4 + psize]) ]) data = self._unconsumed[4 + psize:] del self._unconsumed result = self._decomp.decompress(data) self.eof = self._decomp.eof return result compressor_names = { 0: 'store', 1: 'shrink', 2: 'reduce', 3: 'reduce', 4: 'reduce', 5: 'reduce', 6: 'implode', 7: 'tokenize', 8: 'deflate', 9: 'deflate64', 10: 'implode', 12: 'bzip2', 14: 'lzma', 18: 'terse', 19: 'lz77', 97: 'wavpack', 98: 'ppmd', } def _check_compression(compression): if compression == ZIP_STORED: pass elif compression == ZIP_DEFLATED: if not zlib: raise RuntimeError( "Compression requires the (missing) zlib module") elif compression == ZIP_BZIP2: if not bz2: raise RuntimeError( "Compression requires the (missing) bz2 module") elif compression == ZIP_LZMA: if not lzma: raise RuntimeError( "Compression requires the (missing) lzma module") else: raise NotImplementedError("That compression method is not supported") def _get_compressor(compress_type, compresslevel=None): if compress_type == ZIP_DEFLATED: if compresslevel is not None: return zlib.compressobj(compresslevel, zlib.DEFLATED, -15) return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) elif compress_type == ZIP_BZIP2: if compresslevel is not None: return bz2.BZ2Compressor(compresslevel) return bz2.BZ2Compressor() # compresslevel is ignored for ZIP_LZMA elif compress_type == ZIP_LZMA: return LZMACompressor() else: return None def _get_decompressor(compress_type): _check_compression(compress_type) if compress_type == ZIP_STORED: return None elif compress_type == ZIP_DEFLATED: return zlib.decompressobj(-15) elif compress_type == ZIP_BZIP2: return bz2.BZ2Decompressor() elif compress_type == ZIP_LZMA: return LZMADecompressor() else: descr = compressor_names.get(compress_type) if descr: raise NotImplementedError("compression type %d (%s)" % (compress_type, descr)) else: raise NotImplementedError("compression type %d" % (compress_type,)) class _SharedFile: def __init__(self, file, pos, close, lock, writing): self._file = file self._pos = pos self._close = close self._lock = lock self._writing = writing self.seekable = file.seekable self.tell = file.tell def seek(self, offset, whence=0): with self._lock: if self._writing(): raise ValueError("Can't reposition in the ZIP file while " "there is an open writing handle on it. " "Close the writing handle before trying to read.") self._file.seek(offset, whence) self._pos = self._file.tell() return self._pos def read(self, n=-1): with self._lock: if self._writing(): raise ValueError("Can't read from the ZIP file while there " "is an open writing handle on it. " "Close the writing handle before trying to read.") self._file.seek(self._pos) data = self._file.read(n) self._pos = self._file.tell() return data def close(self): if self._file is not None: fileobj = self._file self._file = None self._close(fileobj) # Provide the tell method for unseekable stream class _Tellable: def __init__(self, fp): self.fp = fp self.offset = 0 def write(self, data): n = self.fp.write(data) self.offset += n return n def tell(self): return self.offset def flush(self): self.fp.flush() def close(self): self.fp.close() class ZipExtFile(io.BufferedIOBase): # Max size supported by decompressor. MAX_N = 1 << 31 - 1 # Read from compressed files in 4k blocks. MIN_READ_SIZE = 4096 # Chunk size to read during seek MAX_SEEK_READ = 1 << 24 def __init__(self, fileobj, mode, zipinfo, pwd=None, close_fileobj=False): self._fileobj = fileobj self._pwd = pwd self._close_fileobj = close_fileobj self._compress_type = zipinfo.compress_type self._compress_left = zipinfo.compress_size self._left = zipinfo.file_size self._decompressor = _get_decompressor(self._compress_type) self._eof = False self._readbuffer = b'' self._offset = 0 self.newlines = None self.mode = mode self.name = zipinfo.filename if hasattr(zipinfo, 'CRC'): self._expected_crc = zipinfo.CRC self._running_crc = crc32(b'') else: self._expected_crc = None self._seekable = False try: if fileobj.seekable(): self._orig_compress_start = fileobj.tell() self._orig_compress_size = zipinfo.compress_size self._orig_file_size = zipinfo.file_size self._orig_start_crc = self._running_crc self._seekable = True except AttributeError: pass self._decrypter = None if pwd: if zipinfo.flag_bits & 0x8: # compare against the file type from extended local headers check_byte = (zipinfo._raw_time >> 8) & 0xff else: # compare against the CRC otherwise check_byte = (zipinfo.CRC >> 24) & 0xff h = self._init_decrypter() if h != check_byte: raise RuntimeError("Bad password for file %r" % zipinfo.orig_filename) def _init_decrypter(self): self._decrypter = _ZipDecrypter(self._pwd) # The first 12 bytes in the cypher stream is an encryption header # used to strengthen the algorithm. The first 11 bytes are # completely random, while the 12th contains the MSB of the CRC, # or the MSB of the file time depending on the header type # and is used to check the correctness of the password. header = self._fileobj.read(12) self._compress_left -= 12 return self._decrypter(header)[11] def __repr__(self): result = ['<%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)] if not self.closed: result.append(' name=%r mode=%r' % (self.name, self.mode)) if self._compress_type != ZIP_STORED: result.append(' compress_type=%s' % compressor_names.get(self._compress_type, self._compress_type)) else: result.append(' [closed]') result.append('>') return ''.join(result) def readline(self, limit=-1): if limit < 0: # Shortcut common case - newline found in buffer. i = self._readbuffer.find(b'\n', self._offset) + 1 if i > 0: line = self._readbuffer[self._offset: i] self._offset = i return line return io.BufferedIOBase.readline(self, limit) def peek(self, n=1): if n > len(self._readbuffer) - self._offset: chunk = self.read(n) if len(chunk) > self._offset: self._readbuffer = chunk + self._readbuffer[self._offset:] self._offset = 0 else: self._offset -= len(chunk) # Return up to 512 bytes to reduce allocation overhead for tight loops. return self._readbuffer[self._offset: self._offset + 512] def readable(self): if self.closed: raise ValueError("I/O operation on closed file.") return True def read(self, n=-1): if self.closed: raise ValueError("read from closed file.") if n is None or n < 0: buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while not self._eof: buf += self._read1(self.MAX_N) return buf end = n + self._offset if end < len(self._readbuffer): buf = self._readbuffer[self._offset:end] self._offset = end return buf n = end - len(self._readbuffer) buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while n > 0 and not self._eof: data = self._read1(n) if n < len(data): self._readbuffer = data self._offset = n buf += data[:n] break buf += data n -= len(data) return buf def _update_crc(self, newdata): # Update the CRC using the given data. if self._expected_crc is None: # No need to compute the CRC if we don't have a reference value return self._running_crc = crc32(newdata, self._running_crc) if self._eof and self._running_crc != self._expected_crc: raise BadZipFile("Bad CRC-32 for file %r" % self.name) def read1(self, n): if n is None or n < 0: buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 while not self._eof: data = self._read1(self.MAX_N) if data: buf += data break return buf end = n + self._offset if end < len(self._readbuffer): buf = self._readbuffer[self._offset:end] self._offset = end return buf n = end - len(self._readbuffer) buf = self._readbuffer[self._offset:] self._readbuffer = b'' self._offset = 0 if n > 0: while not self._eof: data = self._read1(n) if n < len(data): self._readbuffer = data self._offset = n buf += data[:n] break if data: buf += data break return buf def _read1(self, n): # Read up to n compressed bytes with at most one read() system call, # decrypt and decompress them. if self._eof or n <= 0: return b'' # Read from file. if self._compress_type == ZIP_DEFLATED: ## Handle unconsumed data. data = self._decompressor.unconsumed_tail if n > len(data): data += self._read2(n - len(data)) else: data = self._read2(n) if self._compress_type == ZIP_STORED: self._eof = self._compress_left <= 0 elif self._compress_type == ZIP_DEFLATED: n = max(n, self.MIN_READ_SIZE) data = self._decompressor.decompress(data, n) self._eof = (self._decompressor.eof or self._compress_left <= 0 and not self._decompressor.unconsumed_tail) if self._eof: data += self._decompressor.flush() else: data = self._decompressor.decompress(data) self._eof = self._decompressor.eof or self._compress_left <= 0 data = data[:self._left] self._left -= len(data) if self._left <= 0: self._eof = True self._update_crc(data) return data def _read2(self, n): if self._compress_left <= 0: return b'' n = max(n, self.MIN_READ_SIZE) n = min(n, self._compress_left) data = self._fileobj.read(n) self._compress_left -= len(data) if not data: raise EOFError if self._decrypter is not None: data = self._decrypter(data) return data def close(self): try: if self._close_fileobj: self._fileobj.close() finally: super().close() def seekable(self): if self.closed: raise ValueError("I/O operation on closed file.") return self._seekable def seek(self, offset, whence=0): if self.closed: raise ValueError("seek on closed file.") if not self._seekable: raise io.UnsupportedOperation("underlying stream is not seekable") curr_pos = self.tell() if whence == 0: # Seek from start of file new_pos = offset elif whence == 1: # Seek from current position new_pos = curr_pos + offset elif whence == 2: # Seek from EOF new_pos = self._orig_file_size + offset else: raise ValueError("whence must be os.SEEK_SET (0), " "os.SEEK_CUR (1), or os.SEEK_END (2)") if new_pos > self._orig_file_size: new_pos = self._orig_file_size if new_pos < 0: new_pos = 0 read_offset = new_pos - curr_pos buff_offset = read_offset + self._offset if buff_offset >= 0 and buff_offset < len(self._readbuffer): # Just move the _offset index if the new position is in the _readbuffer self._offset = buff_offset read_offset = 0 elif read_offset < 0: # Position is before the current position. Reset the ZipExtFile self._fileobj.seek(self._orig_compress_start) self._running_crc = self._orig_start_crc self._compress_left = self._orig_compress_size self._left = self._orig_file_size self._readbuffer = b'' self._offset = 0 self._decompressor = _get_decompressor(self._compress_type) self._eof = False read_offset = new_pos if self._decrypter is not None: self._init_decrypter() while read_offset > 0: read_len = min(self.MAX_SEEK_READ, read_offset) self.read(read_len) read_offset -= read_len return self.tell() def tell(self): if self.closed: raise ValueError("tell on closed file.") if not self._seekable: raise io.UnsupportedOperation("underlying stream is not seekable") filepos = self._orig_file_size - self._left - len(self._readbuffer) + self._offset return filepos class _ZipWriteFile(io.BufferedIOBase): def __init__(self, zf, zinfo, zip64): self._zinfo = zinfo self._zip64 = zip64 self._zipfile = zf self._compressor = _get_compressor(zinfo.compress_type, zinfo._compresslevel) self._file_size = 0 self._compress_size = 0 self._crc = 0 @property def _fileobj(self): return self._zipfile.fp def writable(self): return True def write(self, data): if self.closed: raise ValueError('I/O operation on closed file.') # Accept any data that supports the buffer protocol if isinstance(data, (bytes, bytearray)): nbytes = len(data) else: data = memoryview(data) nbytes = data.nbytes self._file_size += nbytes self._crc = crc32(data, self._crc) if self._compressor: data = self._compressor.compress(data) self._compress_size += len(data) self._fileobj.write(data) return nbytes def close(self): if self.closed: return try: super().close() # Flush any data from the compressor, and update header info if self._compressor: buf = self._compressor.flush() self._compress_size += len(buf) self._fileobj.write(buf) self._zinfo.compress_size = self._compress_size else: self._zinfo.compress_size = self._file_size self._zinfo.CRC = self._crc self._zinfo.file_size = self._file_size # Write updated header info if self._zinfo.flag_bits & 0x08: # Write CRC and file sizes after the file data fmt = '<LLQQ' if self._zip64 else '<LLLL' self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC, self._zinfo.compress_size, self._zinfo.file_size)) self._zipfile.start_dir = self._fileobj.tell() else: if not self._zip64: if self._file_size > ZIP64_LIMIT: raise RuntimeError( 'File size unexpectedly exceeded ZIP64 limit') if self._compress_size > ZIP64_LIMIT: raise RuntimeError( 'Compressed size unexpectedly exceeded ZIP64 limit') # Seek backwards and write file header (which will now include # correct CRC and file sizes) # Preserve current position in file self._zipfile.start_dir = self._fileobj.tell() self._fileobj.seek(self._zinfo.header_offset) self._fileobj.write(self._zinfo.FileHeader(self._zip64)) self._fileobj.seek(self._zipfile.start_dir) # Successfully written: Add file to our caches self._zipfile.filelist.append(self._zinfo) self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo finally: self._zipfile._writing = False class ZipFile: fp = None # Set here since __del__ checks it _windows_illegal_name_trans_table = None def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True): if mode not in ('r', 'w', 'x', 'a'): raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'") _check_compression(compression) self._allowZip64 = allowZip64 self._didModify = False self.debug = 0 # Level of printing: 0 through 3 self.NameToInfo = {} # Find file info given name self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.compresslevel = compresslevel self.mode = mode self.pwd = None self._comment = b'' self._strict_timestamps = strict_timestamps # Check if we were passed a file-like object if isinstance(file, os.PathLike): file = os.fspath(file) if isinstance(file, str): # No, it's a filename self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b', 'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'} filemode = modeDict[mode] while True: try: self.fp = io.open(file, filemode) except OSError: if filemode in modeDict: filemode = modeDict[filemode] continue raise break else: self._filePassed = 1 self.fp = file self.filename = getattr(file, 'name', None) self._fileRefCnt = 1 self._lock = threading.RLock() self._seekable = True self._writing = False try: if mode == 'r': self._RealGetContents() elif mode in ('w', 'x'): self._didModify = True try: self.start_dir = self.fp.tell() except (AttributeError, OSError): self.fp = _Tellable(self.fp) self.start_dir = 0 self._seekable = False else: try: self.fp.seek(self.start_dir) except (AttributeError, OSError): self._seekable = False elif mode == 'a': try: self._RealGetContents() self.fp.seek(self.start_dir) except BadZipFile: self.fp.seek(0, 2) self._didModify = True self.start_dir = self.fp.tell() else: raise ValueError("Mode must be 'r', 'w', 'x', or 'a'") except: fp = self.fp self.fp = None self._fpclose(fp) raise def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __repr__(self): result = ['<%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)] if self.fp is not None: if self._filePassed: result.append(' file=%r' % self.fp) elif self.filename is not None: result.append(' filename=%r' % self.filename) result.append(' mode=%r' % self.mode) else: result.append(' [closed]') result.append('>') return ''.join(result) def _RealGetContents(self): fp = self.fp try: endrec = _EndRecData(fp) except OSError: raise BadZipFile("File is not a zip file") if not endrec: raise BadZipFile("File is not a zip file") if self.debug > 1: print(endrec) size_cd = endrec[_ECD_SIZE] offset_cd = endrec[_ECD_OFFSET] self._comment = endrec[_ECD_COMMENT] concat = endrec[_ECD_LOCATION] - size_cd - offset_cd if endrec[_ECD_SIGNATURE] == stringEndArchive64: concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator) if self.debug > 2: inferred = concat + offset_cd print("given, inferred, offset", offset_cd, inferred, concat) self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) data = fp.read(size_cd) fp = io.BytesIO(data) total = 0 while total < size_cd: centdir = fp.read(sizeCentralDir) if len(centdir) != sizeCentralDir: raise BadZipFile("Truncated central directory") centdir = struct.unpack(structCentralDir, centdir) if centdir[_CD_SIGNATURE] != stringCentralDir: raise BadZipFile("Bad magic number for central directory") if self.debug > 2: print(centdir) filename = fp.read(centdir[_CD_FILENAME_LENGTH]) flags = centdir[5] if flags & 0x800: filename = filename.decode('utf-8') else: filename = filename.decode('cp437') x = ZipInfo(filename) x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] if x.extract_version > MAX_EXTRACT_VERSION: raise NotImplementedError("zip file version %.1f" % (x.extract_version / 10)) x.volume, x.internal_attr, x.external_attr = centdir[15:18] x._raw_time = t x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) x._decodeExtra() x.header_offset = x.header_offset + concat self.filelist.append(x) self.NameToInfo[x.filename] = x total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH] + centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]) if self.debug > 2: print("total", total) def namelist(self): return [data.filename for data in self.filelist] def infolist(self): return self.filelist def printdir(self, file=None): print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"), file=file) for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size), file=file) def testzip(self): chunk_size = 2 ** 20 for zinfo in self.filelist: try: with self.open(zinfo.filename, "r") as f: while f.read(chunk_size): pass except BadZipFile: return zinfo.filename def getinfo(self, name): info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info def setpassword(self, pwd): if pwd and not isinstance(pwd, bytes): raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__) if pwd: self.pwd = pwd else: self.pwd = None @property def comment(self): return self._comment @comment.setter def comment(self, comment): if not isinstance(comment, bytes): raise TypeError("comment: expected bytes, got %s" % type(comment).__name__) if len(comment) > ZIP_MAX_COMMENT: import warnings warnings.warn('Archive comment is too long; truncating to %d bytes' % ZIP_MAX_COMMENT, stacklevel=2) comment = comment[:ZIP_MAX_COMMENT] self._comment = comment self._didModify = True def read(self, name, pwd=None): with self.open(name, "r", pwd) as fp: return fp.read() def open(self, name, mode="r", pwd=None, *, force_zip64=False): if mode not in {"r", "w"}: raise ValueError('open() requires mode "r" or "w"') if pwd and not isinstance(pwd, bytes): raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__) if pwd and (mode == "w"): raise ValueError("pwd is only supported for reading files") if not self.fp: raise ValueError( "Attempt to use ZIP archive that was already closed") if isinstance(name, ZipInfo): zinfo = name elif mode == 'w': zinfo = ZipInfo(name) zinfo.compress_type = self.compression zinfo._compresslevel = self.compresslevel else: zinfo = self.getinfo(name) if mode == 'w': return self._open_to_write(zinfo, force_zip64=force_zip64) if self._writing: raise ValueError("Can't read from the ZIP file while there " "is an open writing handle on it. " "Close the writing handle before trying to read.") # Open for reading: self._fileRefCnt += 1 zef_file = _SharedFile(self.fp, zinfo.header_offset, self._fpclose, self._lock, lambda: self._writing) try: # Skip the file header: fheader = zef_file.read(sizeFileHeader) if len(fheader) != sizeFileHeader: raise BadZipFile("Truncated file header") fheader = struct.unpack(structFileHeader, fheader) if fheader[_FH_SIGNATURE] != stringFileHeader: raise BadZipFile("Bad magic number for file header") fname = zef_file.read(fheader[_FH_FILENAME_LENGTH]) if fheader[_FH_EXTRA_FIELD_LENGTH]: zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH]) if zinfo.flag_bits & 0x20: # Zip 2.7: compressed patched data raise NotImplementedError("compressed patched data (flag bit 5)") if zinfo.flag_bits & 0x40: # strong encryption raise NotImplementedError("strong encryption (flag bit 6)") if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800: # UTF-8 filename fname_str = fname.decode("utf-8") else: fname_str = fname.decode("cp437") if fname_str != zinfo.orig_filename: raise BadZipFile( 'File name in directory %r and header %r differ.' % (zinfo.orig_filename, fname)) # check for encrypted flag & handle password is_encrypted = zinfo.flag_bits & 0x1 if is_encrypted: if not pwd: pwd = self.pwd if not pwd: raise RuntimeError("File %r is encrypted, password " "required for extraction" % name) else: pwd = None return ZipExtFile(zef_file, mode, zinfo, pwd, True) except: zef_file.close() raise def _open_to_write(self, zinfo, force_zip64=False): if force_zip64 and not self._allowZip64: raise ValueError( "force_zip64 is True, but allowZip64 was False when opening " "the ZIP file." ) if self._writing: raise ValueError("Can't write to the ZIP file while there is " "another write handle open on it. " "Close the first handle before opening another.") zinfo.compress_size = 0 zinfo.CRC = 0 zinfo.flag_bits = 0x00 if zinfo.compress_type == ZIP_LZMA: zinfo.flag_bits |= 0x02 if not self._seekable: zinfo.flag_bits |= 0x08 if not zinfo.external_attr: zinfo.external_attr = 0o600 << 16 zip64 = self._allowZip64 and \ (force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT) if self._seekable: self.fp.seek(self.start_dir) zinfo.header_offset = self.fp.tell() self._writecheck(zinfo) self._didModify = True self.fp.write(zinfo.FileHeader(zip64)) self._writing = True return _ZipWriteFile(self, zinfo, zip64) def extract(self, member, path=None, pwd=None): if path is None: path = os.getcwd() else: path = os.fspath(path) return self._extract_member(member, path, pwd) def extractall(self, path=None, members=None, pwd=None): if members is None: members = self.namelist() if path is None: path = os.getcwd() else: path = os.fspath(path) for zipinfo in members: self._extract_member(zipinfo, path, pwd) @classmethod def _sanitize_windows_name(cls, arcname, pathsep): table = cls._windows_illegal_name_trans_table if not table: illegal = ':<>|"?*' table = str.maketrans(illegal, '_' * len(illegal)) cls._windows_illegal_name_trans_table = table arcname = arcname.translate(table) # remove trailing dots arcname = (x.rstrip('.') for x in arcname.split(pathsep)) # rejoin, removing empty parts. arcname = pathsep.join(x for x in arcname if x) return arcname def _extract_member(self, member, targetpath, pwd): if not isinstance(member, ZipInfo): member = self.getinfo(member) # build the destination pathname, replacing # forward slashes to platform specific separators. arcname = member.filename.replace('/', os.path.sep) if os.path.altsep: arcname = arcname.replace(os.path.altsep, os.path.sep) # interpret absolute pathname as relative, remove drive letter or # UNC path, redundant separators, "." and ".." components. arcname = os.path.splitdrive(arcname)[1] invalid_path_parts = ('', os.path.curdir, os.path.pardir) arcname = os.path.sep.join(x for x in arcname.split(os.path.sep) if x not in invalid_path_parts) if os.path.sep == '\\': # filter illegal characters on Windows arcname = self._sanitize_windows_name(arcname, os.path.sep) targetpath = os.path.join(targetpath, arcname) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.is_dir(): if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath with self.open(member, pwd=pwd) as source, \ open(targetpath, "wb") as target: shutil.copyfileobj(source, target) return targetpath def _writecheck(self, zinfo): if zinfo.filename in self.NameToInfo: import warnings warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3) if self.mode not in ('w', 'x', 'a'): raise ValueError("write() requires mode 'w', 'x', or 'a'") if not self.fp: raise ValueError( "Attempt to write ZIP archive that was already closed") _check_compression(zinfo.compress_type) if not self._allowZip64: requires_zip64 = None if len(self.filelist) >= ZIP_FILECOUNT_LIMIT: requires_zip64 = "Files count" elif zinfo.file_size > ZIP64_LIMIT: requires_zip64 = "Filesize" elif zinfo.header_offset > ZIP64_LIMIT: requires_zip64 = "Zipfile size" if requires_zip64: raise LargeZipFile(requires_zip64 + " would require ZIP64 extensions") def write(self, filename, arcname=None, compress_type=None, compresslevel=None): if not self.fp: raise ValueError( "Attempt to write to ZIP archive that was already closed") if self._writing: raise ValueError( "Can't write to ZIP archive while an open writing handle exists" ) zinfo = ZipInfo.from_file(filename, arcname, strict_timestamps=self._strict_timestamps) if zinfo.is_dir(): zinfo.compress_size = 0 zinfo.CRC = 0 else: if compress_type is not None: zinfo.compress_type = compress_type else: zinfo.compress_type = self.compression if compresslevel is not None: zinfo._compresslevel = compresslevel else: zinfo._compresslevel = self.compresslevel if zinfo.is_dir(): with self._lock: if self._seekable: self.fp.seek(self.start_dir) zinfo.header_offset = self.fp.tell() # Start of header bytes if zinfo.compress_type == ZIP_LZMA: # Compressed data includes an end-of-stream (EOS) marker zinfo.flag_bits |= 0x02 self._writecheck(zinfo) self._didModify = True self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo self.fp.write(zinfo.FileHeader(False)) self.start_dir = self.fp.tell() else: with open(filename, "rb") as src, self.open(zinfo, 'w') as dest: shutil.copyfileobj(src, dest, 1024*8) def writestr(self, zinfo_or_arcname, data, compress_type=None, compresslevel=None): if isinstance(data, str): data = data.encode("utf-8") if not isinstance(zinfo_or_arcname, ZipInfo): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())[:6]) zinfo.compress_type = self.compression zinfo._compresslevel = self.compresslevel if zinfo.filename[-1] == '/': zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x zinfo.external_attr |= 0x10 # MS-DOS directory flag else: zinfo.external_attr = 0o600 << 16 # ?rw------- else: zinfo = zinfo_or_arcname if not self.fp: raise ValueError( "Attempt to write to ZIP archive that was already closed") if self._writing: raise ValueError( "Can't write to ZIP archive while an open writing handle exists." ) if compress_type is not None: zinfo.compress_type = compress_type if compresslevel is not None: zinfo._compresslevel = compresslevel zinfo.file_size = len(data) # Uncompressed size with self._lock: with self.open(zinfo, mode='w') as dest: dest.write(data) def __del__(self): self.close() def close(self): if self.fp is None: return if self._writing: raise ValueError("Can't close the ZIP file while there is " "an open writing handle on it. " "Close the writing handle before closing the zip.") try: if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records with self._lock: if self._seekable: self.fp.seek(self.start_dir) self._write_end_record() finally: fp = self.fp self.fp = None self._fpclose(fp) def _write_end_record(self): for zinfo in self.filelist: # write central directory dt = zinfo.date_time dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) extra = [] if zinfo.file_size > ZIP64_LIMIT \ or zinfo.compress_size > ZIP64_LIMIT: extra.append(zinfo.file_size) extra.append(zinfo.compress_size) file_size = 0xffffffff compress_size = 0xffffffff else: file_size = zinfo.file_size compress_size = zinfo.compress_size if zinfo.header_offset > ZIP64_LIMIT: extra.append(zinfo.header_offset) header_offset = 0xffffffff else: header_offset = zinfo.header_offset extra_data = zinfo.extra min_version = 0 if extra: # Append a ZIP64 field to the extra's extra_data = _strip_extra(extra_data, (1,)) extra_data = struct.pack( '<HH' + 'Q'*len(extra), 1, 8*len(extra), *extra) + extra_data min_version = ZIP64_VERSION if zinfo.compress_type == ZIP_BZIP2: min_version = max(BZIP2_VERSION, min_version) elif zinfo.compress_type == ZIP_LZMA: min_version = max(LZMA_VERSION, min_version) extract_version = max(min_version, zinfo.extract_version) create_version = max(min_version, zinfo.create_version) filename, flag_bits = zinfo._encodeFilenameFlags() centdir = struct.pack(structCentralDir, stringCentralDir, create_version, zinfo.create_system, extract_version, zinfo.reserved, flag_bits, zinfo.compress_type, dostime, dosdate, zinfo.CRC, compress_size, file_size, len(filename), len(extra_data), len(zinfo.comment), 0, zinfo.internal_attr, zinfo.external_attr, header_offset) self.fp.write(centdir) self.fp.write(filename) self.fp.write(extra_data) self.fp.write(zinfo.comment) pos2 = self.fp.tell() # Write end-of-zip-archive record centDirCount = len(self.filelist) centDirSize = pos2 - self.start_dir centDirOffset = self.start_dir requires_zip64 = None if centDirCount > ZIP_FILECOUNT_LIMIT: requires_zip64 = "Files count" elif centDirOffset > ZIP64_LIMIT: requires_zip64 = "Central directory offset" elif centDirSize > ZIP64_LIMIT: requires_zip64 = "Central directory size" if requires_zip64: # Need to write the ZIP64 end-of-archive records if not self._allowZip64: raise LargeZipFile(requires_zip64 + " would require ZIP64 extensions") zip64endrec = struct.pack( structEndArchive64, stringEndArchive64, 44, 45, 45, 0, 0, centDirCount, centDirCount, centDirSize, centDirOffset) self.fp.write(zip64endrec) zip64locrec = struct.pack( structEndArchive64Locator, stringEndArchive64Locator, 0, pos2, 1) self.fp.write(zip64locrec) centDirCount = min(centDirCount, 0xFFFF) centDirSize = min(centDirSize, 0xFFFFFFFF) centDirOffset = min(centDirOffset, 0xFFFFFFFF) endrec = struct.pack(structEndArchive, stringEndArchive, 0, 0, centDirCount, centDirCount, centDirSize, centDirOffset, len(self._comment)) self.fp.write(endrec) self.fp.write(self._comment) if self.mode == "a": self.fp.truncate() self.fp.flush() def _fpclose(self, fp): assert self._fileRefCnt > 0 self._fileRefCnt -= 1 if not self._fileRefCnt and not self._filePassed: fp.close() class PyZipFile(ZipFile): def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True, optimize=-1): ZipFile.__init__(self, file, mode=mode, compression=compression, allowZip64=allowZip64) self._optimize = optimize def writepy(self, pathname, basename="", filterfunc=None): pathname = os.fspath(pathname) if filterfunc and not filterfunc(pathname): if self.debug: label = 'path' if os.path.isdir(pathname) else 'file' print('%s %r skipped by filterfunc' % (label, pathname)) return dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print("Adding package in", pathname, "as", basename) fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) dirlist = sorted(os.listdir(pathname)) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename, filterfunc=filterfunc) # Recursive call elif ext == ".py": if filterfunc and not filterfunc(path): if self.debug: print('file %r skipped by filterfunc' % path) continue fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print("Adding files from directory", pathname) for filename in sorted(os.listdir(pathname)): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": if filterfunc and not filterfunc(path): if self.debug: print('file %r skipped by filterfunc' % path) continue fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print("Adding", arcname) self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError( 'Files added with writepy() must end with ".py"') fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print("Adding file", arcname) self.write(fname, arcname) def _get_codename(self, pathname, basename): def _compile(file, optimize=-1): import py_compile if self.debug: print("Compiling", file) try: py_compile.compile(file, doraise=True, optimize=optimize) except py_compile.PyCompileError as err: print(err.msg) return False return True file_py = pathname + ".py" file_pyc = pathname + ".pyc" pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) if self._optimize == -1: # legacy mode: use whatever file is present if (os.path.isfile(file_pyc) and os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): # Use .pyc file. arcname = fname = file_pyc elif (os.path.isfile(pycache_opt0) and os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt0 arcname = file_pyc elif (os.path.isfile(pycache_opt1) and os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt1 arcname = file_pyc elif (os.path.isfile(pycache_opt2) and os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt2 arcname = file_pyc else: # Compile py into PEP 3147 pyc file. if _compile(file_py): if sys.flags.optimize == 0: fname = pycache_opt0 elif sys.flags.optimize == 1: fname = pycache_opt1 else: fname = pycache_opt2 arcname = file_pyc else: fname = arcname = file_py else: # new mode: use given optimization level if self._optimize == 0: fname = pycache_opt0 arcname = file_pyc else: arcname = file_pyc if self._optimize == 1: fname = pycache_opt1 elif self._optimize == 2: fname = pycache_opt2 else: msg = "invalid value for 'optimize': {!r}".format(self._optimize) raise ValueError(msg) if not (os.path.isfile(fname) and os.stat(fname).st_mtime >= os.stat(file_py).st_mtime): if not _compile(file_py, optimize=self._optimize): fname = arcname = file_py archivename = os.path.split(arcname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename) def _parents(path): return itertools.islice(_ancestry(path), 1, None) def _ancestry(path): path = path.rstrip(posixpath.sep) while path and path != posixpath.sep: yield path path, tail = posixpath.split(path) _dedupe = dict.fromkeys def _difference(minuend, subtrahend): return itertools.filterfalse(set(subtrahend).__contains__, minuend) class CompleteDirs(ZipFile): @staticmethod def _implied_dirs(names): parents = itertools.chain.from_iterable(map(_parents, names)) as_dirs = (p + posixpath.sep for p in parents) return _dedupe(_difference(as_dirs, names)) def namelist(self): names = super(CompleteDirs, self).namelist() return names + list(self._implied_dirs(names)) def _name_set(self): return set(self.namelist()) def resolve_dir(self, name): names = self._name_set() dirname = name + '/' dir_match = name not in names and dirname in names return dirname if dir_match else name @classmethod def make(cls, source): if isinstance(source, CompleteDirs): return source if not isinstance(source, ZipFile): return cls(source) # Only allow for FastPath when supplied zipfile is read-only if 'r' not in source.mode: cls = CompleteDirs res = cls.__new__(cls) vars(res).update(vars(source)) return res class FastLookup(CompleteDirs): def namelist(self): with contextlib.suppress(AttributeError): return self.__names self.__names = super(FastLookup, self).namelist() return self.__names def _name_set(self): with contextlib.suppress(AttributeError): return self.__lookup self.__lookup = super(FastLookup, self)._name_set() return self.__lookup class Path: __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" def __init__(self, root, at=""): self.root = FastLookup.make(root) self.at = at def open(self, mode='r', *args, **kwargs): pwd = kwargs.pop('pwd', None) zip_mode = mode[0] stream = self.root.open(self.at, zip_mode, pwd=pwd) if 'b' in mode: if args or kwargs: raise ValueError("encoding args invalid for binary operation") return stream return io.TextIOWrapper(stream, *args, **kwargs) @property def name(self): return posixpath.basename(self.at.rstrip("/")) def read_text(self, *args, **kwargs): with self.open('r', *args, **kwargs) as strm: return strm.read() def read_bytes(self): with self.open('rb') as strm: return strm.read() def _is_child(self, path): return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") def _next(self, at): return Path(self.root, at) def is_dir(self): return not self.at or self.at.endswith("/") def is_file(self): return not self.is_dir() def exists(self): return self.at in self.root._name_set() def iterdir(self): if not self.is_dir(): raise ValueError("Can't listdir a file") subs = map(self._next, self.root.namelist()) return filter(self._is_child, subs) def __str__(self): return posixpath.join(self.root.filename, self.at) def __repr__(self): return self.__repr.format(self=self) def joinpath(self, add): next = posixpath.join(self.at, add) return self._next(self.root.resolve_dir(next)) __truediv__ = joinpath @property def parent(self): parent_at = posixpath.dirname(self.at.rstrip('/')) if parent_at: parent_at += '/' return self._next(parent_at) def main(args=None): import argparse description = 'A simple command-line interface for zipfile module.' parser = argparse.ArgumentParser(description=description) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', metavar='<zipfile>', help='Show listing of a zipfile') group.add_argument('-e', '--extract', nargs=2, metavar=('<zipfile>', '<output_dir>'), help='Extract zipfile into target dir') group.add_argument('-c', '--create', nargs='+', metavar=('<name>', '<file>'), help='Create zipfile from sources') group.add_argument('-t', '--test', metavar='<zipfile>', help='Test if a zipfile is valid') args = parser.parse_args(args) if args.test is not None: src = args.test with ZipFile(src, 'r') as zf: badfile = zf.testzip() if badfile: print("The following enclosed file is corrupted: {!r}".format(badfile)) print("Done testing") elif args.list is not None: src = args.list with ZipFile(src, 'r') as zf: zf.printdir() elif args.extract is not None: src, curdir = args.extract with ZipFile(src, 'r') as zf: zf.extractall(curdir) elif args.create is not None: zip_name = args.create.pop(0) files = args.create def addToZip(zf, path, zippath): if os.path.isfile(path): zf.write(path, zippath, ZIP_DEFLATED) elif os.path.isdir(path): if zippath: zf.write(path, zippath) for nm in sorted(os.listdir(path)): addToZip(zf, os.path.join(path, nm), os.path.join(zippath, nm)) # else: ignore with ZipFile(zip_name, 'w') as zf: for path in files: zippath = os.path.basename(path) if not zippath: zippath = os.path.basename(os.path.dirname(path)) if zippath in ('', os.curdir, os.pardir): zippath = '' addToZip(zf, path, zippath) if __name__ == "__main__": main()
true
true
f72c6a59206b96eb9586897deebd2a857da10ff7
2,944
py
Python
Demo/sgi/video/Vreceive.py
AtjonTV/Python-1.4
2a80562c5a163490f444181cb75ca1b3089759ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
Demo/sgi/video/Vreceive.py
AtjonTV/Python-1.4
2a80562c5a163490f444181cb75ca1b3089759ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
Demo/sgi/video/Vreceive.py
AtjonTV/Python-1.4
2a80562c5a163490f444181cb75ca1b3089759ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
#!/ufs/guido/bin/sgi/python # Receive live video UDP packets. # Usage: Vreceive [port] import sys import struct from socket import * # syscalls and support functions from SOCKET import * # <sys/socket.h> from IN import * # <netinet/in.h> import select import struct import gl, GL, DEVICE sys.path.append('/ufs/guido/src/video') import LiveVideoOut import regsub import getopt from senddefs import * # Print usage message and exit(2). def usage(msg): print msg print 'usage: Vreceive [-m mcastgrp] [-p port] [-c type]' print '-m mcastgrp: multicast group (default ' + `DEFMCAST` + ')' print '-p port : port (default ' + `DEFPORT` + ')' print '-c type : signal type: rgb8, grey or mono (default rgb8)' sys.exit(2) # Main program: parse options and main loop. def main(): sys.stdout = sys.stderr group = DEFMCAST port = DEFPORT width = DEFWIDTH height = DEFHEIGHT vtype = 'rgb8' try: opts, args = getopt.getopt(sys.argv[1:], 'm:p:c:') except getopt.error, msg: usage(msg) try: for opt, optarg in opts: if opt == '-p': port = string.atoi(optarg) if opt == '-m': group = gethostbyname(optarg) if opt == '-c': vtype = optarg except string.atoi_error, msg: usage('bad integer: ' + msg) s = opensocket(group, port) gl.foreground() gl.prefsize(width, height) wid = gl.winopen('Vreceive') gl.winconstraints() gl.qdevice(DEVICE.ESCKEY) gl.qdevice(DEVICE.WINSHUT) gl.qdevice(DEVICE.WINQUIT) lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) ifdlist = [gl.qgetfd(), s.fileno()] ofdlist = [] xfdlist = [] timeout = 1.0 selectargs = (ifdlist, ofdlist, xfdlist, timeout) while 1: if gl.qtest(): dev, val = gl.qread() if dev in (DEVICE.ESCKEY, \ DEVICE.WINSHUT, DEVICE.WINQUIT): break if dev == DEVICE.REDRAW: lvo.reshapewindow() elif s.avail(): data = s.recv(16*1024) pos, w, h = struct.unpack('hhh', data[:6]) if (w, h) <> (width, height): x, y = gl.getorigin() y = y + height - h gl.winposition(x, x+w-1, y, y+h-1) width, height = w, h lvo.resizevideo(width, height) lvo.putnextpacket(pos, data[6:]) else: x = select.select(selectargs) lvo.close() # Subroutine to create and properly initialize the receiving socket def opensocket(group, port): # Create the socket s = socket(AF_INET, SOCK_DGRAM) # Allow multiple copies of this program on one machine s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # (Not strictly needed) # Bind the port to it s.bind('', port) # Look up the group once group = gethostbyname(group) # Construct binary group address group_bytes = eval(regsub.gsub('\.', ',', group)) grpaddr = 0 for byte in group_bytes: grpaddr = (grpaddr << 8) | byte # Construct struct mreq from grpaddr and ifaddr ifaddr = INADDR_ANY mreq = struct.pack('ll', grpaddr, ifaddr) # Add group membership s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) return s main()
21.647059
68
0.66712
import sys import struct from socket import * from SOCKET import * from IN import * import select import struct import gl, GL, DEVICE sys.path.append('/ufs/guido/src/video') import LiveVideoOut import regsub import getopt from senddefs import * def usage(msg): print msg print 'usage: Vreceive [-m mcastgrp] [-p port] [-c type]' print '-m mcastgrp: multicast group (default ' + `DEFMCAST` + ')' print '-p port : port (default ' + `DEFPORT` + ')' print '-c type : signal type: rgb8, grey or mono (default rgb8)' sys.exit(2) def main(): sys.stdout = sys.stderr group = DEFMCAST port = DEFPORT width = DEFWIDTH height = DEFHEIGHT vtype = 'rgb8' try: opts, args = getopt.getopt(sys.argv[1:], 'm:p:c:') except getopt.error, msg: usage(msg) try: for opt, optarg in opts: if opt == '-p': port = string.atoi(optarg) if opt == '-m': group = gethostbyname(optarg) if opt == '-c': vtype = optarg except string.atoi_error, msg: usage('bad integer: ' + msg) s = opensocket(group, port) gl.foreground() gl.prefsize(width, height) wid = gl.winopen('Vreceive') gl.winconstraints() gl.qdevice(DEVICE.ESCKEY) gl.qdevice(DEVICE.WINSHUT) gl.qdevice(DEVICE.WINQUIT) lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) ifdlist = [gl.qgetfd(), s.fileno()] ofdlist = [] xfdlist = [] timeout = 1.0 selectargs = (ifdlist, ofdlist, xfdlist, timeout) while 1: if gl.qtest(): dev, val = gl.qread() if dev in (DEVICE.ESCKEY, \ DEVICE.WINSHUT, DEVICE.WINQUIT): break if dev == DEVICE.REDRAW: lvo.reshapewindow() elif s.avail(): data = s.recv(16*1024) pos, w, h = struct.unpack('hhh', data[:6]) if (w, h) <> (width, height): x, y = gl.getorigin() y = y + height - h gl.winposition(x, x+w-1, y, y+h-1) width, height = w, h lvo.resizevideo(width, height) lvo.putnextpacket(pos, data[6:]) else: x = select.select(selectargs) lvo.close() def opensocket(group, port): s = socket(AF_INET, SOCK_DGRAM) s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) s.bind('', port) group = gethostbyname(group) group_bytes = eval(regsub.gsub('\.', ',', group)) grpaddr = 0 for byte in group_bytes: grpaddr = (grpaddr << 8) | byte ifaddr = INADDR_ANY mreq = struct.pack('ll', grpaddr, ifaddr) s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) return s main()
false
true
f72c6a5b0a88709c33bc15b7b8f421bdb28239fe
806
py
Python
Scripts/bulk_image_download.py
POSCON-United-Kingdom/UK-Radar-Data
6a020b03fbfeffe9f7eb53e4b4559de48134e351
[ "Apache-2.0" ]
2
2022-01-15T14:01:36.000Z
2022-01-15T22:54:40.000Z
Scripts/bulk_image_download.py
POSCON-United-Kingdom/UK-Radar-Data
6a020b03fbfeffe9f7eb53e4b4559de48134e351
[ "Apache-2.0" ]
null
null
null
Scripts/bulk_image_download.py
POSCON-United-Kingdom/UK-Radar-Data
6a020b03fbfeffe9f7eb53e4b4559de48134e351
[ "Apache-2.0" ]
null
null
null
import re import requests import urllib.request import urllib3 from bs4 import BeautifulSoup print('Beginning file download with urllib2...') url = "https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/html/eSUP/EG-eSUP-2020-017-en-GB.html" """Parse the given table into a beautifulsoup object""" count = 0 http = urllib3.PoolManager() error = http.request("GET", url) if (error.status == 404): print("File not found") page = requests.get(url) soup = BeautifulSoup(page.content, "lxml") searchData = soup.find_all("img") for img in searchData: file = re.search(r"(ID_[\d]{7}\.gif)", str(img)) if file: url = f'https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/graphics/{file.group(1)}' urllib.request.urlretrieve(url, f'{count}.gif') count += 1
29.851852
107
0.69727
import re import requests import urllib.request import urllib3 from bs4 import BeautifulSoup print('Beginning file download with urllib2...') url = "https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/html/eSUP/EG-eSUP-2020-017-en-GB.html" count = 0 http = urllib3.PoolManager() error = http.request("GET", url) if (error.status == 404): print("File not found") page = requests.get(url) soup = BeautifulSoup(page.content, "lxml") searchData = soup.find_all("img") for img in searchData: file = re.search(r"(ID_[\d]{7}\.gif)", str(img)) if file: url = f'https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/graphics/{file.group(1)}' urllib.request.urlretrieve(url, f'{count}.gif') count += 1
true
true
f72c6be17e996073ee98833c5d3263506ac82ca5
987
py
Python
test/unit/sorting/test_wordle_solver.py
bestpersonyes2/algorithms
4225b3ebcdcbd29c80abe0b086d986875526dfcc
[ "MIT" ]
null
null
null
test/unit/sorting/test_wordle_solver.py
bestpersonyes2/algorithms
4225b3ebcdcbd29c80abe0b086d986875526dfcc
[ "MIT" ]
null
null
null
test/unit/sorting/test_wordle_solver.py
bestpersonyes2/algorithms
4225b3ebcdcbd29c80abe0b086d986875526dfcc
[ "MIT" ]
null
null
null
import os from algorithms.sorting.wordle_solver import _read_file, get_best_guess, get_most_common def test_get_most_common(): file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json')) most_common_start, most_common_letters, possible_words = get_most_common(file_data) assert type(most_common_start) == list assert type(most_common_letters) == list assert type(possible_words) == list def test_get_best_guess(): file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json')) best_guess = get_best_guess(file_data) assert type(best_guess) == list def test_read_file(): answer_file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json')) non_answer_file_data = _read_file( os.path.join('algorithms', 'assets', 'wordle_non_answer_possible_words_list.json') ) assert len(answer_file_data) == 2309 assert len(non_answer_file_data) == 10638
32.9
98
0.749747
import os from algorithms.sorting.wordle_solver import _read_file, get_best_guess, get_most_common def test_get_most_common(): file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json')) most_common_start, most_common_letters, possible_words = get_most_common(file_data) assert type(most_common_start) == list assert type(most_common_letters) == list assert type(possible_words) == list def test_get_best_guess(): file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json')) best_guess = get_best_guess(file_data) assert type(best_guess) == list def test_read_file(): answer_file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json')) non_answer_file_data = _read_file( os.path.join('algorithms', 'assets', 'wordle_non_answer_possible_words_list.json') ) assert len(answer_file_data) == 2309 assert len(non_answer_file_data) == 10638
true
true
f72c6c14815e59ace61d84641f721f81f31b67ac
8,156
py
Python
sentence_transformers/datasets/SentenceLabelDataset.py
dd-dos/sentence-transformers
8f9c36b788e15141f723d80fea67ed16785cd18e
[ "Apache-2.0" ]
31
2021-04-06T16:20:30.000Z
2022-02-16T08:29:24.000Z
sentence_transformers/datasets/SentenceLabelDataset.py
dd-dos/sentence-transformers
8f9c36b788e15141f723d80fea67ed16785cd18e
[ "Apache-2.0" ]
5
2021-07-02T04:37:04.000Z
2021-07-21T00:02:58.000Z
sentence_transformers/datasets/SentenceLabelDataset.py
dd-dos/sentence-transformers
8f9c36b788e15141f723d80fea67ed16785cd18e
[ "Apache-2.0" ]
5
2021-04-07T08:35:06.000Z
2022-03-08T08:33:05.000Z
from torch.utils.data import Dataset from typing import List import bisect import torch import logging import numpy as np from tqdm import tqdm from .. import SentenceTransformer from ..readers.InputExample import InputExample from multiprocessing import Pool, cpu_count import multiprocessing class SentenceLabelDataset(Dataset): """ Dataset for training with triplet loss. This dataset takes a list of sentences grouped by their label and uses this grouping to dynamically select a positive example from the same group and a negative example from the other sentences for a selected anchor sentence. This dataset should be used in combination with dataset_reader.LabelSentenceReader One iteration over this dataset selects every sentence as anchor once. This also uses smart batching like SentenceDataset. """ def __init__(self, examples: List[InputExample], model: SentenceTransformer, provide_positive: bool = True, provide_negative: bool = True, parallel_tokenization: bool = True, max_processes: int = 4, chunk_size: int = 5000): """ Converts input examples to a SentenceLabelDataset usable to train the model with SentenceTransformer.smart_batching_collate as the collate_fn for the DataLoader Assumes only one sentence per InputExample and labels as integers from 0 to max_num_labels and should be used in combination with dataset_reader.LabelSentenceReader. Labels with only one example are ignored. smart_batching_collate as collate_fn is required because it transforms the tokenized texts to the tensors. :param examples: the input examples for the training :param model the Sentence BERT model for the conversion :param provide_positive: set this to False, if you don't need a positive example (e.g. for BATCH_HARD_TRIPLET_LOSS). :param provide_negative: set this to False, if you don't need a negative example (e.g. for BATCH_HARD_TRIPLET_LOSS or MULTIPLE_NEGATIVES_RANKING_LOSS). :param parallel_tokenization If true, multiple processes will be started for the tokenization :param max_processes Maximum number of processes started for tokenization. Cannot be larger can cpu_count() :param chunk_size #chunk_size number of examples are send to each process. Larger values increase overall tokenization speed """ self.model = model self.groups_right_border = [] self.grouped_inputs = [] self.grouped_labels = [] self.num_labels = 0 self.max_processes = min(max_processes, cpu_count()) self.chunk_size = chunk_size self.parallel_tokenization = parallel_tokenization if self.parallel_tokenization: if multiprocessing.get_start_method() != 'fork': logging.info("Parallel tokenization is only available on Unix systems which allow to fork processes. Fall back to sequential tokenization") self.parallel_tokenization = False self.convert_input_examples(examples, model) self.idxs = np.arange(len(self.grouped_inputs)) self.provide_positive = provide_positive self.provide_negative = provide_negative def convert_input_examples(self, examples: List[InputExample], model: SentenceTransformer): """ Converts input examples to a SentenceLabelDataset. Assumes only one sentence per InputExample and labels as integers from 0 to max_num_labels and should be used in combination with dataset_reader.LabelSentenceReader. Labels with only one example are ignored. :param examples: the input examples for the training :param model the Sentence Transformer model for the conversion :param is_pretokenized If set to true, no tokenization will be applied. It is expected that the input is tokenized via model.tokenize """ inputs = [] labels = [] label_sent_mapping = {} too_long = 0 label_type = None logging.info("Start tokenization") if not self.parallel_tokenization or self.max_processes == 1 or len(examples) <= self.chunk_size: tokenized_texts = [self.tokenize_example(example) for example in examples] else: logging.info("Use multi-process tokenization with {} processes".format(self.max_processes)) self.model.to('cpu') with Pool(self.max_processes) as p: tokenized_texts = list(p.imap(self.tokenize_example, examples, chunksize=self.chunk_size)) # Group examples and labels # Add examples with the same label to the same dict for ex_index, example in enumerate(tqdm(examples, desc="Convert dataset")): if label_type is None: if isinstance(example.label, int): label_type = torch.long elif isinstance(example.label, float): label_type = torch.float tokenized_text = tokenized_texts[ex_index][0] if hasattr(model, 'max_seq_length') and model.max_seq_length is not None and model.max_seq_length > 0 and len(tokenized_text) > model.max_seq_length: too_long += 1 if example.label in label_sent_mapping: label_sent_mapping[example.label].append(ex_index) else: label_sent_mapping[example.label] = [ex_index] inputs.append(tokenized_text) labels.append(example.label) # Group sentences, such that sentences with the same label # are besides each other. Only take labels with at least 2 examples distinct_labels = list(label_sent_mapping.keys()) for i in range(len(distinct_labels)): label = distinct_labels[i] if len(label_sent_mapping[label]) >= 2: self.grouped_inputs.extend([inputs[j] for j in label_sent_mapping[label]]) self.grouped_labels.extend([labels[j] for j in label_sent_mapping[label]]) self.groups_right_border.append(len(self.grouped_inputs)) #At which position does this label group / bucket end? self.num_labels += 1 self.grouped_labels = torch.tensor(self.grouped_labels, dtype=label_type) logging.info("Num sentences: %d" % (len(self.grouped_inputs))) logging.info("Sentences longer than max_seqence_length: {}".format(too_long)) logging.info("Number of labels with >1 examples: {}".format(len(distinct_labels))) def tokenize_example(self, example): if example.texts_tokenized is not None: return example.texts_tokenized return [self.model.tokenize(text) for text in example.texts] def __getitem__(self, item): if not self.provide_positive and not self.provide_negative: return [self.grouped_inputs[item]], self.grouped_labels[item] # Anchor element anchor = self.grouped_inputs[item] # Check start and end position for this label in our list of grouped sentences group_idx = bisect.bisect_right(self.groups_right_border, item) left_border = 0 if group_idx == 0 else self.groups_right_border[group_idx - 1] right_border = self.groups_right_border[group_idx] if self.provide_positive: positive_item_idx = np.random.choice(np.concatenate([self.idxs[left_border:item], self.idxs[item + 1:right_border]])) positive = self.grouped_inputs[positive_item_idx] else: positive = [] if self.provide_negative: negative_item_idx = np.random.choice(np.concatenate([self.idxs[0:left_border], self.idxs[right_border:]])) negative = self.grouped_inputs[negative_item_idx] else: negative = [] return [anchor, positive, negative], self.grouped_labels[item] def __len__(self): return len(self.grouped_inputs)
44.086486
161
0.676067
from torch.utils.data import Dataset from typing import List import bisect import torch import logging import numpy as np from tqdm import tqdm from .. import SentenceTransformer from ..readers.InputExample import InputExample from multiprocessing import Pool, cpu_count import multiprocessing class SentenceLabelDataset(Dataset): def __init__(self, examples: List[InputExample], model: SentenceTransformer, provide_positive: bool = True, provide_negative: bool = True, parallel_tokenization: bool = True, max_processes: int = 4, chunk_size: int = 5000): self.model = model self.groups_right_border = [] self.grouped_inputs = [] self.grouped_labels = [] self.num_labels = 0 self.max_processes = min(max_processes, cpu_count()) self.chunk_size = chunk_size self.parallel_tokenization = parallel_tokenization if self.parallel_tokenization: if multiprocessing.get_start_method() != 'fork': logging.info("Parallel tokenization is only available on Unix systems which allow to fork processes. Fall back to sequential tokenization") self.parallel_tokenization = False self.convert_input_examples(examples, model) self.idxs = np.arange(len(self.grouped_inputs)) self.provide_positive = provide_positive self.provide_negative = provide_negative def convert_input_examples(self, examples: List[InputExample], model: SentenceTransformer): inputs = [] labels = [] label_sent_mapping = {} too_long = 0 label_type = None logging.info("Start tokenization") if not self.parallel_tokenization or self.max_processes == 1 or len(examples) <= self.chunk_size: tokenized_texts = [self.tokenize_example(example) for example in examples] else: logging.info("Use multi-process tokenization with {} processes".format(self.max_processes)) self.model.to('cpu') with Pool(self.max_processes) as p: tokenized_texts = list(p.imap(self.tokenize_example, examples, chunksize=self.chunk_size)) for ex_index, example in enumerate(tqdm(examples, desc="Convert dataset")): if label_type is None: if isinstance(example.label, int): label_type = torch.long elif isinstance(example.label, float): label_type = torch.float tokenized_text = tokenized_texts[ex_index][0] if hasattr(model, 'max_seq_length') and model.max_seq_length is not None and model.max_seq_length > 0 and len(tokenized_text) > model.max_seq_length: too_long += 1 if example.label in label_sent_mapping: label_sent_mapping[example.label].append(ex_index) else: label_sent_mapping[example.label] = [ex_index] inputs.append(tokenized_text) labels.append(example.label) distinct_labels = list(label_sent_mapping.keys()) for i in range(len(distinct_labels)): label = distinct_labels[i] if len(label_sent_mapping[label]) >= 2: self.grouped_inputs.extend([inputs[j] for j in label_sent_mapping[label]]) self.grouped_labels.extend([labels[j] for j in label_sent_mapping[label]]) self.groups_right_border.append(len(self.grouped_inputs)) self.num_labels += 1 self.grouped_labels = torch.tensor(self.grouped_labels, dtype=label_type) logging.info("Num sentences: %d" % (len(self.grouped_inputs))) logging.info("Sentences longer than max_seqence_length: {}".format(too_long)) logging.info("Number of labels with >1 examples: {}".format(len(distinct_labels))) def tokenize_example(self, example): if example.texts_tokenized is not None: return example.texts_tokenized return [self.model.tokenize(text) for text in example.texts] def __getitem__(self, item): if not self.provide_positive and not self.provide_negative: return [self.grouped_inputs[item]], self.grouped_labels[item] anchor = self.grouped_inputs[item] group_idx = bisect.bisect_right(self.groups_right_border, item) left_border = 0 if group_idx == 0 else self.groups_right_border[group_idx - 1] right_border = self.groups_right_border[group_idx] if self.provide_positive: positive_item_idx = np.random.choice(np.concatenate([self.idxs[left_border:item], self.idxs[item + 1:right_border]])) positive = self.grouped_inputs[positive_item_idx] else: positive = [] if self.provide_negative: negative_item_idx = np.random.choice(np.concatenate([self.idxs[0:left_border], self.idxs[right_border:]])) negative = self.grouped_inputs[negative_item_idx] else: negative = [] return [anchor, positive, negative], self.grouped_labels[item] def __len__(self): return len(self.grouped_inputs)
true
true
f72c6c43bcf8f2dbd66c55523b66a5c428917e0a
3,129
py
Python
Set3/The CBC padding oracle/padding_oracle.py
BadMonkey7/Cryptopals
53bbef43d0d0dc62286514122c2651b1ce8e7471
[ "MIT" ]
1
2021-05-07T16:35:24.000Z
2021-05-07T16:35:24.000Z
Set3/The CBC padding oracle/padding_oracle.py
BadMonkey7/Cryptopals
53bbef43d0d0dc62286514122c2651b1ce8e7471
[ "MIT" ]
null
null
null
Set3/The CBC padding oracle/padding_oracle.py
BadMonkey7/Cryptopals
53bbef43d0d0dc62286514122c2651b1ce8e7471
[ "MIT" ]
null
null
null
# coding=utf-8 from random import randint import os from Crypto.Cipher import AES from base64 import b64decode all = [ "MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=", "MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic=", "MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw==", "MDAwMDAzQ29va2luZyBNQydzIGxpa2UgYSBwb3VuZCBvZiBiYWNvbg==", "MDAwMDA0QnVybmluZyAnZW0sIGlmIHlvdSBhaW4ndCBxdWljayBhbmQgbmltYmxl", "MDAwMDA1SSBnbyBjcmF6eSB3aGVuIEkgaGVhciBhIGN5bWJhbA==", "MDAwMDA2QW5kIGEgaGlnaCBoYXQgd2l0aCBhIHNvdXBlZCB1cCB0ZW1wbw==", "MDAwMDA3SSdtIG9uIGEgcm9sbCwgaXQncyB0aW1lIHRvIGdvIHNvbG8=", "MDAwMDA4b2xsaW4nIGluIG15IGZpdmUgcG9pbnQgb2g=", "MDAwMDA5aXRoIG15IHJhZy10b3AgZG93biBzbyBteSBoYWlyIGNhbiBibG93" ] # key = os.urandom(16) # pad = lambda s: s+chr(16-len(s)%16)*(16-len(s)%16) # unpad = lambda s: s[-ord(s[-1]):] == chr(ord(s[-1]))*ord(s[-1]) # def oracle(): m = b64decode(all[randint(0, 9)]) iv = os.urandom(AES.block_size) cipher = AES.new(key,AES.MODE_CBC,iv) enc = cipher.encrypt(pad(m)) return iv+enc # def check_oracle(enc): iv = enc[0:AES.block_size] cipher = AES.new(key,AES.MODE_CBC,iv) mess = cipher.decrypt(enc[AES.block_size:]) # res = unpad(mess) # print res[1] return unpad(mess) ############################################## def xor(a,b): return ''.join([chr(ord(i)^ord(j)) for i,j in zip(a,b)]) # 注意事项 可能有多个合法padding,需要处理,我的解决方法不太好当是也能凑合用,即记录下所有可能,找出一种合法的即可 def judge(bs,tmp,enc,pos): if pos == bs: return [True,''.join(tmp)] for i in range(pos,bs): j = 0 nxt = '' for k in range(i, 0, -1): nxt += chr(ord(tmp[-k]) ^ (i + 1)) record = [] while j < 256: payload = chr(0) * (bs - i - 1) + chr(j) + nxt if check_oracle(payload + enc): record.append(chr(j ^ (i + 1))) j += 1 # 非法,可能是因为之前猜测的结果错误的原因 if len(record) == 0: return [False,''] elif len(record) == 1: # 只有一种可能不用调用函数 tmp[-i-1] = record[0] else: # 尝试所有可能性 for k in record: tmp[-i-1] = k res = judge(bs,tmp,enc,i+1) # 合法的可能 直接返回,不合法的不考虑 if res[0]: return [True, res[1]] return [True,''.join(tmp)] # # # 一块一块暴力破解 def padding_oracle_block(iv,bs,enc): tmp = ['']*bs res = judge(bs,tmp,enc,0)[1] return xor(iv,res) def padding_oracle(): enc = oracle() bs = AES.block_size iv = enc[0:bs] blocks = [enc[bs*i:bs*i+bs] for i in range(1,len(enc[bs:])/bs)] message = '' for block in blocks: try: message += padding_oracle_block(iv,bs,block) except: f = open('log.txt','w+') log = "iv == "+iv.encode('hex')+'\n'+"key == "+key.encode('hex')+'\n'+'block=='+block.encode('hex')+'\n' f.write(log) f.close() return 'error please check your logs to see more details' # print message iv = block return message print padding_oracle()
28.972222
116
0.590284
from random import randint import os from Crypto.Cipher import AES from base64 import b64decode all = [ "MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=", "MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic=", "MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw==", "MDAwMDAzQ29va2luZyBNQydzIGxpa2UgYSBwb3VuZCBvZiBiYWNvbg==", "MDAwMDA0QnVybmluZyAnZW0sIGlmIHlvdSBhaW4ndCBxdWljayBhbmQgbmltYmxl", "MDAwMDA1SSBnbyBjcmF6eSB3aGVuIEkgaGVhciBhIGN5bWJhbA==", "MDAwMDA2QW5kIGEgaGlnaCBoYXQgd2l0aCBhIHNvdXBlZCB1cCB0ZW1wbw==", "MDAwMDA3SSdtIG9uIGEgcm9sbCwgaXQncyB0aW1lIHRvIGdvIHNvbG8=", "MDAwMDA4b2xsaW4nIGluIG15IGZpdmUgcG9pbnQgb2g=", "MDAwMDA5aXRoIG15IHJhZy10b3AgZG93biBzbyBteSBoYWlyIGNhbiBibG93" ] key = os.urandom(16) pad = lambda s: s+chr(16-len(s)%16)*(16-len(s)%16) unpad = lambda s: s[-ord(s[-1]):] == chr(ord(s[-1]))*ord(s[-1]) def oracle(): m = b64decode(all[randint(0, 9)]) iv = os.urandom(AES.block_size) cipher = AES.new(key,AES.MODE_CBC,iv) enc = cipher.encrypt(pad(m)) return iv+enc def check_oracle(enc): iv = enc[0:AES.block_size] cipher = AES.new(key,AES.MODE_CBC,iv) mess = cipher.decrypt(enc[AES.block_size:]) return unpad(mess) le(): enc = oracle() bs = AES.block_size iv = enc[0:bs] blocks = [enc[bs*i:bs*i+bs] for i in range(1,len(enc[bs:])/bs)] message = '' for block in blocks: try: message += padding_oracle_block(iv,bs,block) except: f = open('log.txt','w+') log = "iv == "+iv.encode('hex')+'\n'+"key == "+key.encode('hex')+'\n'+'block=='+block.encode('hex')+'\n' f.write(log) f.close() return 'error please check your logs to see more details' iv = block return message print padding_oracle()
false
true
f72c6cbe53ce184511d53967dee75da42ddc4cbb
11,828
py
Python
main_multi.py
erfanMhi/Cooperative-Coevolution-Transfer-Optimization
e75b7930bd8b55a160668b1039ac154a0d0270d7
[ "MIT" ]
3
2019-08-04T18:37:58.000Z
2020-08-16T13:01:40.000Z
main_multi.py
erfanMhi/Cooperative-Coevolution-Transfer-Optimization
e75b7930bd8b55a160668b1039ac154a0d0270d7
[ "MIT" ]
null
null
null
main_multi.py
erfanMhi/Cooperative-Coevolution-Transfer-Optimization
e75b7930bd8b55a160668b1039ac154a0d0270d7
[ "MIT" ]
null
null
null
import argparse import os import queue import multiprocessing as mp # import SharedArray as sa import numpy as np from copy import deepcopy from time import time from pprint import pprint from utils.data_manipulators import * from evolution.operators import * from to.probabilistic_model import ProbabilisticModel from to.mixture_model import MixtureModel from evolution.chromosome import * class EAProcess(mp.Process): def __init__(self, dims, psize, gen, problem, shared_queue, shared_array, t_lock, list_lock, return_list, transfer_interval=2): super(EAProcess, self).__init__() self.dims = dims self.psize = psize print('hi') self.gen = gen self.problem = problem self.shared_queue = shared_queue self.shared_array = shared_array # self.shared_lock = shared_lock self.t_lock = t_lock self.list_lock = list_lock self.transfer_interval = transfer_interval self.reinitialize() self.return_list = return_list def reinitialize(self): self.fitness_hist = np.zeros((self.gen, self.psize)) self.fitness_time = np.zeros((self.gen)) init_func = lambda n: np.round(np.random.rand(n)) self.pop = get_pop_init(self.psize, self.dims, init_func) def _ea(self): start = time() for i in range(self.psize): self.pop[i].fitness_calc(self.problem) self.bestfitness = np.max(self.pop).fitness self.fitness = Chromosome.fitness_to_numpy(self.pop) self.fitness_hist[0, :] = self.fitness self.fitness_time[0] = start - time() for i in range(1, self.gen): start = time() if i%self.transfer_interval == 0 and i//self.transfer_interval == 1: print('transfer start') self.t_lock.release() if i%self.transfer_interval == 0: recieved_pops = None try: while True: if recieved_pops is None: recieved_pops = list(self.shared_queue.get(block=True)) else: recieved_pops += list(self.shared_queue.get(block=False)) except queue.Empty: print('Queue is empty now') print('recieved_pops: ', len(recieved_pops)) self.pop = total_selection_pop(np.concatenate((self.pop, recieved_pops)), self.psize) offsprings = total_crossover(self.pop) for j in range(self.psize): offsprings[j].mutation(1/self.dims) # Fitness Calculation cfitness = np.zeros(self.psize) for j in range(self.psize): cfitness[j] = offsprings[j].fitness_calc(self.problem) self.pop, self.fitness = total_selection(np.concatenate((self.pop, offsprings)), np.concatenate((self.fitness, cfitness)), self.psize) self.fitness_hist[i, :] = self.fitness if self.fitness[0] > self.bestfitness: self.bestfitness = self.fitness[0] print('Generation %d best fitness = %f' % (i, self.bestfitness)) self.list_lock.acquire() self.shared_array[:] = Chromosome.genes_to_list(self.pop) self.list_lock.release() self.fitness_time[i] = time() - start print('Shared Array is now available') self.return_list.append([self.fitness_time, self.fitness_hist]) def run(self): # When target array is prepared it will be unlocked print ('called run method in process: %s' %self.name) self._ea() return class TransferProcess(mp.Process): def __init__(self, dims, problem, mutation_strength, sample_size, sub_sample_size, src_models, shared_queue, shared_array, t_lock, list_lock, transfer_interval=2): super(TransferProcess, self).__init__() self.dims = dims self.problem = problem self.src_models = src_models self.mutation_strength = mutation_strength self.sample_size = sample_size self.sub_sample_size = sub_sample_size self.shared_queue = shared_queue self.shared_array = shared_array # self.shared_lock = shared_lock self.t_lock = t_lock self.list_lock = list_lock self.transfer_interval = transfer_interval self.reinitialize() def reinitialize(self): # self.fitness_hist = np.zeros((self.gen, self.psize)) # self.fitness_time = np.zeros((self.gen)) dims_s2 = len(self.src_models)+1 self.second_specie = StrategyChromosome(dims_s2) def _transfer_ea(self): prev_samples = None genes_differ = None target_model = ProbabilisticModel(modelType='umd') self.list_lock.acquire() target_array = np.array(self.shared_array[:]) self.list_lock.release() target_model.buildModel(target_array) _, sampled_offsprings, prev_samples = \ self.second_specie.fitness_calc(self.problem, self.src_models, target_model, self.sample_size, self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples), efficient_version=True) self.shared_queue.put(sampled_offsprings) while True: offspring = deepcopy(self.second_specie) genes_differ = offspring.mutation(self.mutation_strength, 0, 1) target_model = ProbabilisticModel(modelType='umd') self.list_lock.acquire() target_array = np.array(self.shared_array[:]) self.list_lock.release() target_model.buildModel(target_array) _, sampled_offsprings, prev_samples_tmp = \ offspring.fitness_calc(self.problem, self.src_models, target_model, self.sample_size, self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples), efficient_version=True) self.shared_queue.put(sampled_offsprings) self.second_specie, self.mutation_strength, is_off_selected = selection_adoption(self.second_specie, offspring, self.mutation_strength) if is_off_selected: prev_samples = prev_samples_tmp # second_species_gen_num += 1 # while True: def run(self): self.t_lock.acquire() print ('called run method in process: %s' %self.name) self._transfer_ea() return def get_args(): parser = argparse.ArgumentParser(description='CoOperative CoEvolution Transfer Optimization Algorithm for Solving Multi-location Inventory Planning with Lateral Transshipments') parser.add_argument('--stop_condition', default=True, type=bool, nargs='?', help="Stop after i number of iteraction if fitness didn't changed") parser.add_argument('--reps', default=1, type=int, nargs='?', help='Number of repetition') parser.add_argument('--delta', default=2, type=int, nargs='?', help='Step for switiching between transfer optimization and evolutionary operations') # parser.add_argument('--buildmodel', default=True, # type=bool, nargs='?', # help='Should we build source models?') parser.add_argument('--src_version', default='v1', type=str, nargs='?', help='What version of source models should be used?') parser.add_argument('--s1_psize', default=50, type=int, nargs='?', help='Population size for the first species?') # parser.add_argument('--s2_psize', default=20, # type=int, nargs='?', # help='Population size for the second species?') parser.add_argument('--sample_size', default=50, type=int, nargs='?', help='Number of samples generated from each AlphaChromosome?') parser.add_argument('--sub_sample_size', default=50, type=int, nargs='?', help='How many samples should we take from sample_size number of samples generated?') # parser.add_argument('-v', dest='version', default='v1', # type=str, nargs='?', # help='What version should be executed?') parser.add_argument('--mutation_strength', default=1, type=int, nargs='?', help='The same step-size which we use in evolution strategy') parser.add_argument('--injection_type', default='elite', type=str, nargs='?', help='What method do you want to use for injection of species 2 to species 1?') parser.add_argument('--to_repititon_num', default=1, type=int, nargs='?', help='How many time should we repeat the transferring step in evolution strategy?') parser.add_argument('--selection_version', default='v1', type=str, nargs='?', help='What selection version should we use in evolution strategy E(1 + 1)?') parser.add_argument('-c', default=2, type=int, nargs='?', help='Parameter of E(1 + 1) algorithm selection') parser.add_argument('--efficient_version', default=False, type=bool, nargs='?', help='Efficient version of evaluation strategy version?') parser.add_argument('--transfer_repeat_num', default=None, type=int, nargs='?', help=''' Number of times transfer optimization should be run. if it is None, it will be repeated in every delta iteration''') # parser.add_argument('-q', dest='matrix_num', default='a', # type=str, nargs='?', # help='T^0_H matrix selector for section b') return parser.parse_args() def main_multi(args): # constants models_path = 'models' source_models_path = os.path.join(models_path, 'knapsack_source_models') knapsack_problem_path = 'problems/knapsack' dims = 1000 psize = args.s1_psize mutation_strength = args.mutation_strength reps = args.reps transfer_interval = args.delta sub_sample_size = args.sub_sample_size sample_size = args.sample_size gen = 100 # Loading Target Problem target_problem = Tools.load_from_file(os.path.join(knapsack_problem_path, 'KP_uc_ak')) # Loading Source Models src_models = Tools.load_from_file(source_models_path + '_{}'.format(args.src_version)) main_m = mp.Manager() return_list = main_m.list() for i in range(reps): # Shared Variables m = mp.Manager() shared_queue = m.Queue() shared_array = m.list([[0 for j in range(dims)] for i in range(psize)]) # prep_lock = m.Lock() # This lock is used for starting transfer learning # prep_lock.acquire() list_lock = m.Lock() # \\ for synchronozing read & write of the list # q_lock = m.Lock() # \\ for synchronozing put & get of the queue transfer_lock = m.Lock() # \\ will synchronize the transfer_interval for EAProcess transfer_lock.acquire() ea_process = EAProcess(dims, psize, gen, target_problem, shared_queue, shared_array, transfer_lock, list_lock, return_list, transfer_interval=transfer_interval) tr_process = TransferProcess(dims, target_problem, mutation_strength, sample_size, sub_sample_size, src_models, shared_queue, shared_array, transfer_lock, list_lock, transfer_interval=transfer_interval) ea_process.start() tr_process.start() ea_process.join() tr_process.terminate() tr_process.join() Tools.save_to_file(args.save_path, return_list[:]) if __name__ == '__main__': args = get_args() main_multi(args)
34.086455
179
0.633581
import argparse import os import queue import multiprocessing as mp import numpy as np from copy import deepcopy from time import time from pprint import pprint from utils.data_manipulators import * from evolution.operators import * from to.probabilistic_model import ProbabilisticModel from to.mixture_model import MixtureModel from evolution.chromosome import * class EAProcess(mp.Process): def __init__(self, dims, psize, gen, problem, shared_queue, shared_array, t_lock, list_lock, return_list, transfer_interval=2): super(EAProcess, self).__init__() self.dims = dims self.psize = psize print('hi') self.gen = gen self.problem = problem self.shared_queue = shared_queue self.shared_array = shared_array self.t_lock = t_lock self.list_lock = list_lock self.transfer_interval = transfer_interval self.reinitialize() self.return_list = return_list def reinitialize(self): self.fitness_hist = np.zeros((self.gen, self.psize)) self.fitness_time = np.zeros((self.gen)) init_func = lambda n: np.round(np.random.rand(n)) self.pop = get_pop_init(self.psize, self.dims, init_func) def _ea(self): start = time() for i in range(self.psize): self.pop[i].fitness_calc(self.problem) self.bestfitness = np.max(self.pop).fitness self.fitness = Chromosome.fitness_to_numpy(self.pop) self.fitness_hist[0, :] = self.fitness self.fitness_time[0] = start - time() for i in range(1, self.gen): start = time() if i%self.transfer_interval == 0 and i//self.transfer_interval == 1: print('transfer start') self.t_lock.release() if i%self.transfer_interval == 0: recieved_pops = None try: while True: if recieved_pops is None: recieved_pops = list(self.shared_queue.get(block=True)) else: recieved_pops += list(self.shared_queue.get(block=False)) except queue.Empty: print('Queue is empty now') print('recieved_pops: ', len(recieved_pops)) self.pop = total_selection_pop(np.concatenate((self.pop, recieved_pops)), self.psize) offsprings = total_crossover(self.pop) for j in range(self.psize): offsprings[j].mutation(1/self.dims) cfitness = np.zeros(self.psize) for j in range(self.psize): cfitness[j] = offsprings[j].fitness_calc(self.problem) self.pop, self.fitness = total_selection(np.concatenate((self.pop, offsprings)), np.concatenate((self.fitness, cfitness)), self.psize) self.fitness_hist[i, :] = self.fitness if self.fitness[0] > self.bestfitness: self.bestfitness = self.fitness[0] print('Generation %d best fitness = %f' % (i, self.bestfitness)) self.list_lock.acquire() self.shared_array[:] = Chromosome.genes_to_list(self.pop) self.list_lock.release() self.fitness_time[i] = time() - start print('Shared Array is now available') self.return_list.append([self.fitness_time, self.fitness_hist]) def run(self): print ('called run method in process: %s' %self.name) self._ea() return class TransferProcess(mp.Process): def __init__(self, dims, problem, mutation_strength, sample_size, sub_sample_size, src_models, shared_queue, shared_array, t_lock, list_lock, transfer_interval=2): super(TransferProcess, self).__init__() self.dims = dims self.problem = problem self.src_models = src_models self.mutation_strength = mutation_strength self.sample_size = sample_size self.sub_sample_size = sub_sample_size self.shared_queue = shared_queue self.shared_array = shared_array self.t_lock = t_lock self.list_lock = list_lock self.transfer_interval = transfer_interval self.reinitialize() def reinitialize(self): dims_s2 = len(self.src_models)+1 self.second_specie = StrategyChromosome(dims_s2) def _transfer_ea(self): prev_samples = None genes_differ = None target_model = ProbabilisticModel(modelType='umd') self.list_lock.acquire() target_array = np.array(self.shared_array[:]) self.list_lock.release() target_model.buildModel(target_array) _, sampled_offsprings, prev_samples = \ self.second_specie.fitness_calc(self.problem, self.src_models, target_model, self.sample_size, self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples), efficient_version=True) self.shared_queue.put(sampled_offsprings) while True: offspring = deepcopy(self.second_specie) genes_differ = offspring.mutation(self.mutation_strength, 0, 1) target_model = ProbabilisticModel(modelType='umd') self.list_lock.acquire() target_array = np.array(self.shared_array[:]) self.list_lock.release() target_model.buildModel(target_array) _, sampled_offsprings, prev_samples_tmp = \ offspring.fitness_calc(self.problem, self.src_models, target_model, self.sample_size, self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples), efficient_version=True) self.shared_queue.put(sampled_offsprings) self.second_specie, self.mutation_strength, is_off_selected = selection_adoption(self.second_specie, offspring, self.mutation_strength) if is_off_selected: prev_samples = prev_samples_tmp def run(self): self.t_lock.acquire() print ('called run method in process: %s' %self.name) self._transfer_ea() return def get_args(): parser = argparse.ArgumentParser(description='CoOperative CoEvolution Transfer Optimization Algorithm for Solving Multi-location Inventory Planning with Lateral Transshipments') parser.add_argument('--stop_condition', default=True, type=bool, nargs='?', help="Stop after i number of iteraction if fitness didn't changed") parser.add_argument('--reps', default=1, type=int, nargs='?', help='Number of repetition') parser.add_argument('--delta', default=2, type=int, nargs='?', help='Step for switiching between transfer optimization and evolutionary operations') # parser.add_argument('--buildmodel', default=True, # type=bool, nargs='?', # help='Should we build source models?') parser.add_argument('--src_version', default='v1', type=str, nargs='?', help='What version of source models should be used?') parser.add_argument('--s1_psize', default=50, type=int, nargs='?', help='Population size for the first species?') # parser.add_argument('--s2_psize', default=20, # type=int, nargs='?', # help='Population size for the second species?') parser.add_argument('--sample_size', default=50, type=int, nargs='?', help='Number of samples generated from each AlphaChromosome?') parser.add_argument('--sub_sample_size', default=50, type=int, nargs='?', help='How many samples should we take from sample_size number of samples generated?') # parser.add_argument('-v', dest='version', default='v1', # type=str, nargs='?', # help='What version should be executed?') parser.add_argument('--mutation_strength', default=1, type=int, nargs='?', help='The same step-size which we use in evolution strategy') parser.add_argument('--injection_type', default='elite', type=str, nargs='?', help='What method do you want to use for injection of species 2 to species 1?') parser.add_argument('--to_repititon_num', default=1, type=int, nargs='?', help='How many time should we repeat the transferring step in evolution strategy?') parser.add_argument('--selection_version', default='v1', type=str, nargs='?', help='What selection version should we use in evolution strategy E(1 + 1)?') parser.add_argument('-c', default=2, type=int, nargs='?', help='Parameter of E(1 + 1) algorithm selection') parser.add_argument('--efficient_version', default=False, type=bool, nargs='?', help='Efficient version of evaluation strategy version?') parser.add_argument('--transfer_repeat_num', default=None, type=int, nargs='?', help=''' Number of times transfer optimization should be run. if it is None, it will be repeated in every delta iteration''') # parser.add_argument('-q', dest='matrix_num', default='a', # type=str, nargs='?', # help='T^0_H matrix selector for section b') return parser.parse_args() def main_multi(args): # constants models_path = 'models' source_models_path = os.path.join(models_path, 'knapsack_source_models') knapsack_problem_path = 'problems/knapsack' dims = 1000 psize = args.s1_psize mutation_strength = args.mutation_strength reps = args.reps transfer_interval = args.delta sub_sample_size = args.sub_sample_size sample_size = args.sample_size gen = 100 # Loading Target Problem target_problem = Tools.load_from_file(os.path.join(knapsack_problem_path, 'KP_uc_ak')) # Loading Source Models src_models = Tools.load_from_file(source_models_path + '_{}'.format(args.src_version)) main_m = mp.Manager() return_list = main_m.list() for i in range(reps): # Shared Variables m = mp.Manager() shared_queue = m.Queue() shared_array = m.list([[0 for j in range(dims)] for i in range(psize)]) # prep_lock = m.Lock() # This lock is used for starting transfer learning # prep_lock.acquire() list_lock = m.Lock() # \\ for synchronozing read & write of the list # q_lock = m.Lock() # \\ for synchronozing put & get of the queue transfer_lock = m.Lock() # \\ will synchronize the transfer_interval for EAProcess transfer_lock.acquire() ea_process = EAProcess(dims, psize, gen, target_problem, shared_queue, shared_array, transfer_lock, list_lock, return_list, transfer_interval=transfer_interval) tr_process = TransferProcess(dims, target_problem, mutation_strength, sample_size, sub_sample_size, src_models, shared_queue, shared_array, transfer_lock, list_lock, transfer_interval=transfer_interval) ea_process.start() tr_process.start() ea_process.join() tr_process.terminate() tr_process.join() Tools.save_to_file(args.save_path, return_list[:]) if __name__ == '__main__': args = get_args() main_multi(args)
true
true
f72c6d1c6f29288f9f93496e8adfb3d17d94900b
291
py
Python
orb_simulator/other_language/testing_ast/Div.py
dmguezjaviersnet/IA-Sim-Comp-Project
8165b9546efc45f98091a3774e2dae4f45942048
[ "MIT" ]
1
2022-01-19T22:49:09.000Z
2022-01-19T22:49:09.000Z
orb_simulator/other_language/testing_ast/Div.py
dmguezjaviersnet/IA-Sim-Comp-Project
8165b9546efc45f98091a3774e2dae4f45942048
[ "MIT" ]
15
2021-11-10T14:25:02.000Z
2022-02-12T19:17:11.000Z
orb_simulator/other_language/testing_ast/Div.py
dmguezjaviersnet/IA-Sim-Comp-Project
8165b9546efc45f98091a3774e2dae4f45942048
[ "MIT" ]
null
null
null
from other_language.testing_ast.BinaryExpression import * class Div(BinaryExpression): def __init__(self, left: Expression, right: Expression): super().__init__(left, right) def eval(self): self.left.eval() // self.right.eval()
19.4
60
0.608247
from other_language.testing_ast.BinaryExpression import * class Div(BinaryExpression): def __init__(self, left: Expression, right: Expression): super().__init__(left, right) def eval(self): self.left.eval() // self.right.eval()
true
true
f72c6dc05c0249cca7efdc46371d16e808b21190
7,782
py
Python
tests/dataset.py
Juan0001/yellowbrick-docs-zh
36275d9704fc2a946c5bec5f802106bb5281efd1
[ "Apache-2.0" ]
20
2018-03-24T02:29:20.000Z
2022-03-03T05:01:40.000Z
tests/dataset.py
Juan0001/yellowbrick-docs-zh
36275d9704fc2a946c5bec5f802106bb5281efd1
[ "Apache-2.0" ]
4
2018-03-20T12:01:17.000Z
2019-04-07T16:02:19.000Z
tests/dataset.py
Juan0001/yellowbrick-docs-zh
36275d9704fc2a946c5bec5f802106bb5281efd1
[ "Apache-2.0" ]
5
2018-03-17T08:18:57.000Z
2019-11-15T02:20:20.000Z
# tests.dataset # Helper functions for tests that utilize downloadable datasets. # # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Thu Oct 13 19:55:53 2016 -0400 # # Copyright (C) 2016 District Data Labs # For license information, see LICENSE.txt # # ID: dataset.py [8f4de77] benjamin@bengfort.com $ """ Helper functions for tests that utilize downloadable datasets. """ ########################################################################## ## Imports ########################################################################## import os import shutil import hashlib import zipfile import numpy as np from sklearn.datasets.base import Bunch try: import requests except ImportError: requests = None ########################################################################## ## Fixtures ########################################################################## DATASETS = { 'concrete': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/concrete.zip', 'signature': 'b9ea5f26a7bb272a040e2f1a993b26babbf8dc4a04ab8198bb315ca66d71f10d', 'type': 'numpy', }, 'energy': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/energy.zip', 'signature': '19fb86f3bcdde208eed46944172cb643ef6a7d58da103fb568fae43205ed89d3', 'type': 'numpy', }, 'credit': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/credit.zip', 'signature': '4a91339c69f55e18f3f48004328fbcb7868070b618208fed099920427b084e5e', 'type': 'numpy', }, 'occupancy': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/occupancy.zip', 'signature': '429cfe376dc9929a1fa528da89f0e1626e34e19695f3f555d8954025bbc522b8', 'type': 'numpy', }, 'mushroom': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/mushroom.zip', 'signature': '884c43cb70db35d211c67b1cf6a3683b2b4569393d2789d5c07840da4dc85ba8', 'type': 'numpy', }, 'hobbies': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/hobbies.zip', 'signature': '415c8f68df1486d5d84a1d1757a5aa3035aef5ad63ede5013c261d622fbd29d8', 'type': 'corpus', }, 'game': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/game.zip', 'signature': 'b1bd85789a014a898daa34cb5f89ceab6d2cd6488a2e572187e34aa4ec21a43b', 'type': 'numpy', }, 'bikeshare': { 'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/bikeshare.zip', 'signature': 'a9b440f65549746dff680c92ff8bdca3c7265f09db1cf09e708e6e26fc8aba44', 'type': 'numpy', }, } FIXTURES = os.path.join(os.path.dirname(__file__), "fixtures") ########################################################################## ## Test Cases that Require Download ########################################################################## class DatasetMixin(object): """ Mixin for unittest.TestCase class to download datasets from S3 for testing real world machine learning visual diagnostics. """ @staticmethod def sha256sum(path, blocksize=65536): """ Computes the SHA256 signature of a file to verify that the file has not been modified in transit and that it is the correct version of the data. """ sig = hashlib.sha256() with open(path, 'rb') as f: buf = f.read(blocksize) while len(buf) > 0: sig.update(buf) buf = f.read(blocksize) return sig.hexdigest() @staticmethod def download_data(url, path=FIXTURES, signature=None, extract=True): """ Downloads the zipped data set specified at the given URL, saving it to the output path specified. This function verifies the download with the given signature (if supplied) and extracts the zip file if requested. """ if requests is None: raise ImportError( "The requests module is required to download data --\n" "please install it with pip install requests." ) # Create the output directory if it does not exist if not os.path.exists(path): os.mkdir(path) # Get the name of the file from the URL name = os.path.basename(url) dlpath = os.path.join(path, name) # Fetch the response in a streaming fashion and write it to disk. response = requests.get(url, stream=True) with open(dlpath, 'wb') as f: for chunk in response.iter_content(65536): f.write(chunk) # If verify, compare the signature if signature is not None: dlsignature = DatasetMixin.sha256sum(dlpath) if signature != dlsignature: raise ValueError( "Download signature does not match hardcoded signature!" ) # If extract, extract the zipfile. if extract: zf = zipfile.ZipFile(dlpath) zf.extractall(path) @staticmethod def download_all(path=FIXTURES, verify=True, extract=True): """ Downloads all the example datasets. If verify is True then compare the download signature with the hardcoded signature. If extract is True then extract the contents of the zipfile to the given path. """ for name, meta in DATASETS.items(): url = meta['url'] signature = meta['signature'] if verify else None DatasetMixin.download_data( url, path=path, signature=signature, extract=extract ) @staticmethod def remove_all(fixtures=FIXTURES): """ Removes all the downloaded datasets as clean up """ shutil.rmtree(fixtures) @staticmethod def load_data(name, fixtures=FIXTURES): """ Loads the numpy matrix from the specified data set, downloads it if it hasn't already been downloaded. """ # Just in case this is a corpus data set, then do that instead. if DATASETS[name]['type'] == 'corpus': return DatasetMixin.load_corpus(name, fixtures) path = os.path.join(fixtures, name, "{}.csv".format(name)) if not os.path.exists(path): DatasetMixin.download_all(path=fixtures) return np.genfromtxt(path, dtype=float, delimiter=',', names=True) @staticmethod def load_corpus(name, fixtures=FIXTURES): """ Loads a sklearn Bunch with the corpus and downloads it if it hasn't already been downloaded. Used to test text visualizers. """ path = os.path.join(fixtures, name) if not os.path.exists(path): DatasetMixin.download_all(path=fixtures) # Read the directories in the directory as the categories. categories = [ cat for cat in os.listdir(path) if os.path.isdir(os.path.join(path, cat)) ] files = [] # holds the file names relative to the root data = [] # holds the text read from the file target = [] # holds the string of the category # Load the data from the files in the corpus for cat in categories: for name in os.listdir(os.path.join(path, cat)): files.append(os.path.join(path, cat, name)) target.append(cat) with open(os.path.join(path, cat, name), 'r') as f: data.append(f.read()) # Return the data bunch for use similar to the newsgroups example return Bunch( categories=categories, files=files, data=data, target=target, )
34.741071
88
0.585582
true
true
f72c6f6d29ba313be7a1401cddf2903254a2b3ac
1,192
py
Python
tweets/views.py
hariharaselvam/djangotraining
77722b9bae1487b2b39c20db216d3edd46eddffb
[ "Apache-2.0" ]
null
null
null
tweets/views.py
hariharaselvam/djangotraining
77722b9bae1487b2b39c20db216d3edd46eddffb
[ "Apache-2.0" ]
null
null
null
tweets/views.py
hariharaselvam/djangotraining
77722b9bae1487b2b39c20db216d3edd46eddffb
[ "Apache-2.0" ]
null
null
null
from django.shortcuts import render, redirect from django.http import HttpResponse from django.views import View from .forms import TwitterForm from .models import * from .tasks import get_tweets #from twython import Twython # Create your views here. def twitter_view(request): if request.method == 'GET': form = TwitterForm() return render( request, 'tweets.html', { 'twitter_form':form } ) if request.method == 'POST': form = TwitterForm(request.POST) if form.is_valid(): hashtag=form.cleaned_data['hashtag'] hashtag= "hariharaselvam" tweets = get_tweets.delay(hashtag) #product = form.save() #tw = Twython( # "yJ9GXtYiLH2yMXukUijR6R3dH", # "Ad8ZMpJNZvYe1CulUDUHPJiw1lg9pgalcLSFdWUQQRemP7jKhz", # "239795044-XqQ5P6tYWIZJip5EaWWO2Q8mPVwJVZ6hWJ4N9pEO", # "uC9cjPyNtUPg1ekJvWZCCMwtLojpFA7d6dyzoMAyfIlQQ" #) #tweets = tw.search(q=hashtag,count=10) print tweets return redirect('timeline_view') #return HttpResponse(tweets) def timeline_view(request): if request.method == 'GET': statuses = Status.objects.all() return render( request, 'timeline.html', { 'status_list':statuses } )
22.490566
58
0.707215
from django.shortcuts import render, redirect from django.http import HttpResponse from django.views import View from .forms import TwitterForm from .models import * from .tasks import get_tweets def twitter_view(request): if request.method == 'GET': form = TwitterForm() return render( request, 'tweets.html', { 'twitter_form':form } ) if request.method == 'POST': form = TwitterForm(request.POST) if form.is_valid(): hashtag=form.cleaned_data['hashtag'] hashtag= "hariharaselvam" tweets = get_tweets.delay(hashtag) print tweets return redirect('timeline_view') def timeline_view(request): if request.method == 'GET': statuses = Status.objects.all() return render( request, 'timeline.html', { 'status_list':statuses } )
false
true
f72c705b69032d729b976d015ba6742b4d314c78
17,180
py
Python
src/olympia/files/tests/test_file_viewer.py
shashwatsingh/addons-server
8fce98901104349055a828b5a47865f5e8f4120b
[ "BSD-3-Clause" ]
null
null
null
src/olympia/files/tests/test_file_viewer.py
shashwatsingh/addons-server
8fce98901104349055a828b5a47865f5e8f4120b
[ "BSD-3-Clause" ]
null
null
null
src/olympia/files/tests/test_file_viewer.py
shashwatsingh/addons-server
8fce98901104349055a828b5a47865f5e8f4120b
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- import mimetypes import os import shutil import zipfile from django import forms from django.conf import settings from django.core.cache import cache from django.core.files.storage import default_storage as storage import pytest from freezegun import freeze_time from unittest.mock import Mock, patch from olympia import amo from olympia.amo.tests import TestCase from olympia.files.file_viewer import DiffHelper, FileViewer, extract_file from olympia.files.models import File from olympia.files.utils import SafeZip, get_all_files from olympia.files.tests.test_utils import _run_lock_holding_process root = os.path.join(settings.ROOT, 'src/olympia/files/fixtures/files') def get_file(filename): return os.path.join(root, filename) def make_file(pk, file_path, **kwargs): obj = Mock() obj.id = obj.pk = pk for k, v in kwargs.items(): setattr(obj, k, v) obj.file_path = file_path obj.current_file_path = file_path obj.__str__ = lambda x: x.pk obj.version = Mock() obj.version.version = 1 return obj class TestFileViewer(TestCase): def setUp(self): super(TestFileViewer, self).setUp() self.viewer = FileViewer(make_file(1, get_file('dictionary-test.xpi'))) def tearDown(self): self.viewer.cleanup() super(TestFileViewer, self).tearDown() def test_files_not_extracted(self): assert not self.viewer.is_extracted() def test_files_extracted(self): self.viewer.extract() assert self.viewer.is_extracted() def test_recurse_extract(self): self.viewer.src = get_file('recurse.xpi') self.viewer.extract() assert self.viewer.is_extracted() def test_recurse_contents(self): self.viewer.src = get_file('recurse.xpi') self.viewer.extract() files = self.viewer.get_files() # We do not extract nested .zip or .xpi files anymore assert list(files.keys()) == [ u'recurse', u'recurse/chrome', u'recurse/chrome/test-root.txt', u'recurse/chrome/test.jar', u'recurse/notazip.jar', u'recurse/recurse.xpi', u'recurse/somejar.jar'] def test_locked(self): self.viewer.src = get_file('dictionary-test.xpi') # Lock was successfully attained assert self.viewer.extract() lock_name = f'file-viewer-{self.viewer.file.pk}' with _run_lock_holding_process(lock_name, sleep=3): # Not extracting, the viewer is locked, lock could not be attained assert not self.viewer.extract() def test_extract_file_locked_message(self): self.viewer.src = get_file('dictionary-test.xpi') assert not self.viewer.is_extracted() lock_name = f'file-viewer-{self.viewer.file.pk}' with _run_lock_holding_process(lock_name, sleep=3): msg = extract_file(self.viewer) assert str(msg.get()).startswith(u'File viewer is locked') msg.delete() def test_cleanup(self): self.viewer.extract() self.viewer.cleanup() assert not self.viewer.is_extracted() @freeze_time('2017-01-08 02:01:00') def test_dest(self): viewer = FileViewer(make_file(1, get_file('webextension.xpi'))) assert viewer.dest == os.path.join( settings.TMP_PATH, 'file_viewer', '0108', str(self.viewer.file.pk)) def test_isbinary(self): binary = self.viewer._is_binary for f in ['foo.rdf', 'foo.xml', 'foo.js', 'foo.py' 'foo.html', 'foo.txt', 'foo.dtd', 'foo.xul', 'foo.sh', 'foo.properties', 'foo.json', 'foo.src', 'CHANGELOG']: m, encoding = mimetypes.guess_type(f) assert not binary(m, f), '%s should not be binary' % f for f in ['foo.png', 'foo.gif', 'foo.exe', 'foo.swf']: m, encoding = mimetypes.guess_type(f) assert binary(m, f), '%s should be binary' % f filename = os.path.join(settings.TMP_PATH, 'test_isbinary') for txt in ['#!/usr/bin/python', '#python', u'\0x2']: open(filename, 'w').write(txt) m, encoding = mimetypes.guess_type(filename) assert not binary(m, filename), '%s should not be binary' % txt for txt in ['MZ']: open(filename, 'w').write(txt) m, encoding = mimetypes.guess_type(filename) assert binary(m, filename), '%s should be binary' % txt os.remove(filename) def test_truncate(self): truncate = self.viewer.truncate for x, y in (['foo.rdf', 'foo.rdf'], ['somelongfilename.rdf', 'somelongfilenam...rdf'], [u'unicode삮.txt', u'unicode\uc0ae.txt'], [u'unicodesomelong삮.txt', u'unicodesomelong...txt'], ['somelongfilename.somelongextension', 'somelongfilenam...somelonge..'],): assert truncate(x) == y def test_get_files_not_extracted_runs_extraction(self): self.viewer.src = get_file('dictionary-test.xpi') assert not self.viewer.is_extracted() self.viewer.get_files() assert self.viewer.is_extracted() def test_get_files_size(self): self.viewer.extract() files = self.viewer.get_files() assert len(files) == 14 def test_get_files_directory(self): self.viewer.extract() files = self.viewer.get_files() assert not files['install.js']['directory'] assert not files['install.js']['binary'] assert files['__MACOSX']['directory'] assert not files['__MACOSX']['binary'] def test_get_files_depth(self): self.viewer.extract() files = self.viewer.get_files() assert files['dictionaries/license.txt']['depth'] == 1 def test_bom(self): dest = os.path.join(settings.TMP_PATH, 'test_bom') with open(dest, 'wb') as f: f.write('foo'.encode('utf-16')) self.viewer.select('foo') self.viewer.selected = {'full': dest, 'size': 1} assert self.viewer.read_file() == u'foo' os.remove(dest) def test_syntax(self): for filename, syntax in [('foo.rdf', 'xml'), ('foo.xul', 'xml'), ('foo.json', 'js'), ('foo.jsm', 'js'), ('foo.htm', 'html'), ('foo.bar', 'plain'), ('foo.diff', 'plain')]: assert self.viewer.get_syntax(filename) == syntax def test_file_order(self): self.viewer.extract() dest = self.viewer.dest open(os.path.join(dest, 'chrome.manifest'), 'w') subdir = os.path.join(dest, 'chrome') os.mkdir(subdir) open(os.path.join(subdir, 'foo'), 'w') cache.delete(self.viewer._cache_key()) files = list(self.viewer.get_files().keys()) rt = files.index(u'chrome') assert files[rt:rt + 3] == [u'chrome', u'chrome/foo', u'dictionaries'] @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5) def test_file_size(self): self.viewer.extract() self.viewer.get_files() self.viewer.select('install.js') res = self.viewer.read_file() assert res == '' assert self.viewer.selected['msg'].startswith('File size is') @pytest.mark.needs_locales_compilation @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5) def test_file_size_unicode(self): with self.activate(locale='he'): self.viewer.extract() self.viewer.get_files() self.viewer.select('install.js') res = self.viewer.read_file() assert res == '' assert ( self.viewer.selected['msg'].startswith(u'גודל הקובץ חורג')) @patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5) def test_contents_size(self): self.assertRaises(forms.ValidationError, self.viewer.extract) def test_default(self): self.viewer.extract() assert self.viewer.get_default(None) == 'install.rdf' def test_default_webextension(self): viewer = FileViewer(make_file(2, get_file('webextension.xpi'))) viewer.extract() assert viewer.get_default(None) == 'manifest.json' def test_default_webextension_zip(self): viewer = FileViewer(make_file(2, get_file('webextension_no_id.zip'))) viewer.extract() assert viewer.get_default(None) == 'manifest.json' def test_default_webextension_crx(self): viewer = FileViewer(make_file(2, get_file('webextension.crx'))) viewer.extract() assert viewer.get_default(None) == 'manifest.json' def test_default_package_json(self): viewer = FileViewer(make_file(3, get_file('new-format-0.0.1.xpi'))) viewer.extract() assert viewer.get_default(None) == 'package.json' def test_delete_mid_read(self): self.viewer.extract() self.viewer.select('install.js') os.remove(os.path.join(self.viewer.dest, 'install.js')) res = self.viewer.read_file() assert res == '' assert self.viewer.selected['msg'].startswith('That file no') @patch('olympia.files.file_viewer.get_sha256') def test_delete_mid_tree(self, get_sha256): get_sha256.side_effect = IOError('ow') self.viewer.extract() with self.assertRaises(IOError): self.viewer.get_files() @patch('olympia.files.file_viewer.os.fsync') def test_verify_files_doesnt_call_fsync_regularly(self, fsync): self.viewer.extract() assert not fsync.called @patch('olympia.files.file_viewer.os.fsync') def test_verify_files_calls_fsync_on_differences(self, fsync): self.viewer.extract() assert not fsync.called files_to_verify = get_all_files(self.viewer.dest) files_to_verify.pop() module_path = 'olympia.files.file_viewer.get_all_files' with patch(module_path) as get_all_files_mck: get_all_files_mck.return_value = files_to_verify with pytest.raises(ValueError): # We don't put things back into place after fsync # so a `ValueError` is raised self.viewer._verify_files(files_to_verify) assert len(fsync.call_args_list) == len(files_to_verify) + 1 class TestSearchEngineHelper(TestCase): fixtures = ['base/addon_4594_a9'] def setUp(self): super(TestSearchEngineHelper, self).setUp() self.left = File.objects.get(pk=25753) self.viewer = FileViewer(self.left) if not os.path.exists(os.path.dirname(self.viewer.src)): os.makedirs(os.path.dirname(self.viewer.src)) with storage.open(self.viewer.src, 'w') as f: f.write('some data\n') def tearDown(self): self.viewer.cleanup() super(TestSearchEngineHelper, self).tearDown() def test_is_search_engine(self): assert self.viewer.is_search_engine() def test_extract_search_engine(self): self.viewer.extract() assert os.path.exists(self.viewer.dest) def test_default(self): self.viewer.extract() assert self.viewer.get_default(None) == 'a9.xml' def test_default_no_files(self): self.viewer.extract() os.remove(os.path.join(self.viewer.dest, 'a9.xml')) assert self.viewer.get_default(None) is None class TestDiffSearchEngine(TestCase): def setUp(self): super(TestDiffSearchEngine, self).setUp() src = os.path.join(settings.ROOT, get_file('search.xml')) if not storage.exists(src): with storage.open(src, 'w') as f: f.write(open(src).read()) self.helper = DiffHelper(make_file(1, src, filename='search.xml'), make_file(2, src, filename='search.xml')) def tearDown(self): self.helper.cleanup() super(TestDiffSearchEngine, self).tearDown() @patch( 'olympia.files.file_viewer.FileViewer.is_search_engine') def test_diff_search(self, is_search_engine): is_search_engine.return_value = True self.helper.extract() shutil.copyfile(os.path.join(self.helper.left.dest, 'search.xml'), os.path.join(self.helper.right.dest, 's-20010101.xml')) assert self.helper.select('search.xml') assert len(self.helper.get_deleted_files()) == 0 class TestDiffHelper(TestCase): def setUp(self): super(TestDiffHelper, self).setUp() src = os.path.join(settings.ROOT, get_file('dictionary-test.xpi')) self.helper = DiffHelper(make_file(1, src), make_file(2, src)) def tearDown(self): self.helper.cleanup() super(TestDiffHelper, self).tearDown() def clear_cache(self): cache.delete(self.helper.left._cache_key()) cache.delete(self.helper.right._cache_key()) def test_files_not_extracted(self): assert not self.helper.is_extracted() def test_files_extracted(self): self.helper.extract() assert self.helper.is_extracted() def test_get_files(self): assert self.helper.left.get_files() == ( self.helper.get_files()) def test_diffable(self): self.helper.extract() self.helper.select('install.js') assert self.helper.is_diffable() def test_diffable_one_missing(self): self.helper.extract() os.remove(os.path.join(self.helper.right.dest, 'install.js')) self.helper.select('install.js') assert self.helper.is_diffable() def test_diffable_allow_empty(self): self.helper.extract() self.assertRaises(AssertionError, self.helper.right.read_file) assert self.helper.right.read_file(allow_empty=True) == '' def test_diffable_both_missing(self): self.helper.extract() self.helper.select('foo.js') assert not self.helper.is_diffable() def test_diffable_deleted_files(self): self.helper.extract() os.remove(os.path.join(self.helper.left.dest, 'install.js')) assert 'install.js' in self.helper.get_deleted_files() def test_diffable_one_binary_same(self): self.helper.extract() self.helper.select('install.js') self.helper.left.selected['binary'] = True assert self.helper.is_binary() def test_diffable_one_binary_diff(self): self.helper.extract() self.change(self.helper.left.dest, 'asd') self.helper.select('install.js') self.helper.left.selected['binary'] = True assert self.helper.is_binary() def test_diffable_two_binary_diff(self): self.helper.extract() self.change(self.helper.left.dest, 'asd') self.change(self.helper.right.dest, 'asd123') self.clear_cache() self.helper.select('install.js') self.helper.left.selected['binary'] = True self.helper.right.selected['binary'] = True assert self.helper.is_binary() def test_diffable_one_directory(self): self.helper.extract() self.helper.select('install.js') self.helper.left.selected['directory'] = True assert not self.helper.is_diffable() assert self.helper.left.selected['msg'].startswith('This file') def test_diffable_parent(self): self.helper.extract() self.change(self.helper.left.dest, 'asd', filename='__MACOSX/._dictionaries') self.clear_cache() files = self.helper.get_files() assert files['__MACOSX/._dictionaries']['diff'] assert files['__MACOSX']['diff'] def change(self, file, text, filename='install.js'): path = os.path.join(file, filename) with open(path, 'rb') as f: data = f.read() data += text.encode('utf-8') with open(path, 'wb') as f2: f2.write(data) class TestSafeZipFile(TestCase, amo.tests.AMOPaths): # TODO(andym): get full coverage for existing SafeZip methods, most # is covered in the file viewer tests. @patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5) def test_unzip_limit(self): with pytest.raises(forms.ValidationError): SafeZip(self.xpi_path('langpack-localepicker')) def test_unzip_fatal(self): with pytest.raises(zipfile.BadZipFile): SafeZip(self.xpi_path('search.xml')) def test_read(self): zip_file = SafeZip(self.xpi_path('langpack-localepicker')) assert b'locale browser de' in zip_file.read('chrome.manifest') def test_not_secure(self): zip_file = SafeZip(self.xpi_path('extension')) assert not zip_file.is_signed() def test_is_secure(self): zip_file = SafeZip(self.xpi_path('signed')) assert zip_file.is_signed() def test_is_broken(self): zip_file = SafeZip(self.xpi_path('signed')) zip_file.info_list[2].filename = 'META-INF/foo.sf' assert not zip_file.is_signed()
35.349794
79
0.626659
import mimetypes import os import shutil import zipfile from django import forms from django.conf import settings from django.core.cache import cache from django.core.files.storage import default_storage as storage import pytest from freezegun import freeze_time from unittest.mock import Mock, patch from olympia import amo from olympia.amo.tests import TestCase from olympia.files.file_viewer import DiffHelper, FileViewer, extract_file from olympia.files.models import File from olympia.files.utils import SafeZip, get_all_files from olympia.files.tests.test_utils import _run_lock_holding_process root = os.path.join(settings.ROOT, 'src/olympia/files/fixtures/files') def get_file(filename): return os.path.join(root, filename) def make_file(pk, file_path, **kwargs): obj = Mock() obj.id = obj.pk = pk for k, v in kwargs.items(): setattr(obj, k, v) obj.file_path = file_path obj.current_file_path = file_path obj.__str__ = lambda x: x.pk obj.version = Mock() obj.version.version = 1 return obj class TestFileViewer(TestCase): def setUp(self): super(TestFileViewer, self).setUp() self.viewer = FileViewer(make_file(1, get_file('dictionary-test.xpi'))) def tearDown(self): self.viewer.cleanup() super(TestFileViewer, self).tearDown() def test_files_not_extracted(self): assert not self.viewer.is_extracted() def test_files_extracted(self): self.viewer.extract() assert self.viewer.is_extracted() def test_recurse_extract(self): self.viewer.src = get_file('recurse.xpi') self.viewer.extract() assert self.viewer.is_extracted() def test_recurse_contents(self): self.viewer.src = get_file('recurse.xpi') self.viewer.extract() files = self.viewer.get_files() assert list(files.keys()) == [ u'recurse', u'recurse/chrome', u'recurse/chrome/test-root.txt', u'recurse/chrome/test.jar', u'recurse/notazip.jar', u'recurse/recurse.xpi', u'recurse/somejar.jar'] def test_locked(self): self.viewer.src = get_file('dictionary-test.xpi') assert self.viewer.extract() lock_name = f'file-viewer-{self.viewer.file.pk}' with _run_lock_holding_process(lock_name, sleep=3): assert not self.viewer.extract() def test_extract_file_locked_message(self): self.viewer.src = get_file('dictionary-test.xpi') assert not self.viewer.is_extracted() lock_name = f'file-viewer-{self.viewer.file.pk}' with _run_lock_holding_process(lock_name, sleep=3): msg = extract_file(self.viewer) assert str(msg.get()).startswith(u'File viewer is locked') msg.delete() def test_cleanup(self): self.viewer.extract() self.viewer.cleanup() assert not self.viewer.is_extracted() @freeze_time('2017-01-08 02:01:00') def test_dest(self): viewer = FileViewer(make_file(1, get_file('webextension.xpi'))) assert viewer.dest == os.path.join( settings.TMP_PATH, 'file_viewer', '0108', str(self.viewer.file.pk)) def test_isbinary(self): binary = self.viewer._is_binary for f in ['foo.rdf', 'foo.xml', 'foo.js', 'foo.py' 'foo.html', 'foo.txt', 'foo.dtd', 'foo.xul', 'foo.sh', 'foo.properties', 'foo.json', 'foo.src', 'CHANGELOG']: m, encoding = mimetypes.guess_type(f) assert not binary(m, f), '%s should not be binary' % f for f in ['foo.png', 'foo.gif', 'foo.exe', 'foo.swf']: m, encoding = mimetypes.guess_type(f) assert binary(m, f), '%s should be binary' % f filename = os.path.join(settings.TMP_PATH, 'test_isbinary') for txt in ['#!/usr/bin/python', '#python', u'\0x2']: open(filename, 'w').write(txt) m, encoding = mimetypes.guess_type(filename) assert not binary(m, filename), '%s should not be binary' % txt for txt in ['MZ']: open(filename, 'w').write(txt) m, encoding = mimetypes.guess_type(filename) assert binary(m, filename), '%s should be binary' % txt os.remove(filename) def test_truncate(self): truncate = self.viewer.truncate for x, y in (['foo.rdf', 'foo.rdf'], ['somelongfilename.rdf', 'somelongfilenam...rdf'], [u'unicode삮.txt', u'unicode\uc0ae.txt'], [u'unicodesomelong삮.txt', u'unicodesomelong...txt'], ['somelongfilename.somelongextension', 'somelongfilenam...somelonge..'],): assert truncate(x) == y def test_get_files_not_extracted_runs_extraction(self): self.viewer.src = get_file('dictionary-test.xpi') assert not self.viewer.is_extracted() self.viewer.get_files() assert self.viewer.is_extracted() def test_get_files_size(self): self.viewer.extract() files = self.viewer.get_files() assert len(files) == 14 def test_get_files_directory(self): self.viewer.extract() files = self.viewer.get_files() assert not files['install.js']['directory'] assert not files['install.js']['binary'] assert files['__MACOSX']['directory'] assert not files['__MACOSX']['binary'] def test_get_files_depth(self): self.viewer.extract() files = self.viewer.get_files() assert files['dictionaries/license.txt']['depth'] == 1 def test_bom(self): dest = os.path.join(settings.TMP_PATH, 'test_bom') with open(dest, 'wb') as f: f.write('foo'.encode('utf-16')) self.viewer.select('foo') self.viewer.selected = {'full': dest, 'size': 1} assert self.viewer.read_file() == u'foo' os.remove(dest) def test_syntax(self): for filename, syntax in [('foo.rdf', 'xml'), ('foo.xul', 'xml'), ('foo.json', 'js'), ('foo.jsm', 'js'), ('foo.htm', 'html'), ('foo.bar', 'plain'), ('foo.diff', 'plain')]: assert self.viewer.get_syntax(filename) == syntax def test_file_order(self): self.viewer.extract() dest = self.viewer.dest open(os.path.join(dest, 'chrome.manifest'), 'w') subdir = os.path.join(dest, 'chrome') os.mkdir(subdir) open(os.path.join(subdir, 'foo'), 'w') cache.delete(self.viewer._cache_key()) files = list(self.viewer.get_files().keys()) rt = files.index(u'chrome') assert files[rt:rt + 3] == [u'chrome', u'chrome/foo', u'dictionaries'] @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5) def test_file_size(self): self.viewer.extract() self.viewer.get_files() self.viewer.select('install.js') res = self.viewer.read_file() assert res == '' assert self.viewer.selected['msg'].startswith('File size is') @pytest.mark.needs_locales_compilation @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5) def test_file_size_unicode(self): with self.activate(locale='he'): self.viewer.extract() self.viewer.get_files() self.viewer.select('install.js') res = self.viewer.read_file() assert res == '' assert ( self.viewer.selected['msg'].startswith(u'גודל הקובץ חורג')) @patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5) def test_contents_size(self): self.assertRaises(forms.ValidationError, self.viewer.extract) def test_default(self): self.viewer.extract() assert self.viewer.get_default(None) == 'install.rdf' def test_default_webextension(self): viewer = FileViewer(make_file(2, get_file('webextension.xpi'))) viewer.extract() assert viewer.get_default(None) == 'manifest.json' def test_default_webextension_zip(self): viewer = FileViewer(make_file(2, get_file('webextension_no_id.zip'))) viewer.extract() assert viewer.get_default(None) == 'manifest.json' def test_default_webextension_crx(self): viewer = FileViewer(make_file(2, get_file('webextension.crx'))) viewer.extract() assert viewer.get_default(None) == 'manifest.json' def test_default_package_json(self): viewer = FileViewer(make_file(3, get_file('new-format-0.0.1.xpi'))) viewer.extract() assert viewer.get_default(None) == 'package.json' def test_delete_mid_read(self): self.viewer.extract() self.viewer.select('install.js') os.remove(os.path.join(self.viewer.dest, 'install.js')) res = self.viewer.read_file() assert res == '' assert self.viewer.selected['msg'].startswith('That file no') @patch('olympia.files.file_viewer.get_sha256') def test_delete_mid_tree(self, get_sha256): get_sha256.side_effect = IOError('ow') self.viewer.extract() with self.assertRaises(IOError): self.viewer.get_files() @patch('olympia.files.file_viewer.os.fsync') def test_verify_files_doesnt_call_fsync_regularly(self, fsync): self.viewer.extract() assert not fsync.called @patch('olympia.files.file_viewer.os.fsync') def test_verify_files_calls_fsync_on_differences(self, fsync): self.viewer.extract() assert not fsync.called files_to_verify = get_all_files(self.viewer.dest) files_to_verify.pop() module_path = 'olympia.files.file_viewer.get_all_files' with patch(module_path) as get_all_files_mck: get_all_files_mck.return_value = files_to_verify with pytest.raises(ValueError): # so a `ValueError` is raised self.viewer._verify_files(files_to_verify) assert len(fsync.call_args_list) == len(files_to_verify) + 1 class TestSearchEngineHelper(TestCase): fixtures = ['base/addon_4594_a9'] def setUp(self): super(TestSearchEngineHelper, self).setUp() self.left = File.objects.get(pk=25753) self.viewer = FileViewer(self.left) if not os.path.exists(os.path.dirname(self.viewer.src)): os.makedirs(os.path.dirname(self.viewer.src)) with storage.open(self.viewer.src, 'w') as f: f.write('some data\n') def tearDown(self): self.viewer.cleanup() super(TestSearchEngineHelper, self).tearDown() def test_is_search_engine(self): assert self.viewer.is_search_engine() def test_extract_search_engine(self): self.viewer.extract() assert os.path.exists(self.viewer.dest) def test_default(self): self.viewer.extract() assert self.viewer.get_default(None) == 'a9.xml' def test_default_no_files(self): self.viewer.extract() os.remove(os.path.join(self.viewer.dest, 'a9.xml')) assert self.viewer.get_default(None) is None class TestDiffSearchEngine(TestCase): def setUp(self): super(TestDiffSearchEngine, self).setUp() src = os.path.join(settings.ROOT, get_file('search.xml')) if not storage.exists(src): with storage.open(src, 'w') as f: f.write(open(src).read()) self.helper = DiffHelper(make_file(1, src, filename='search.xml'), make_file(2, src, filename='search.xml')) def tearDown(self): self.helper.cleanup() super(TestDiffSearchEngine, self).tearDown() @patch( 'olympia.files.file_viewer.FileViewer.is_search_engine') def test_diff_search(self, is_search_engine): is_search_engine.return_value = True self.helper.extract() shutil.copyfile(os.path.join(self.helper.left.dest, 'search.xml'), os.path.join(self.helper.right.dest, 's-20010101.xml')) assert self.helper.select('search.xml') assert len(self.helper.get_deleted_files()) == 0 class TestDiffHelper(TestCase): def setUp(self): super(TestDiffHelper, self).setUp() src = os.path.join(settings.ROOT, get_file('dictionary-test.xpi')) self.helper = DiffHelper(make_file(1, src), make_file(2, src)) def tearDown(self): self.helper.cleanup() super(TestDiffHelper, self).tearDown() def clear_cache(self): cache.delete(self.helper.left._cache_key()) cache.delete(self.helper.right._cache_key()) def test_files_not_extracted(self): assert not self.helper.is_extracted() def test_files_extracted(self): self.helper.extract() assert self.helper.is_extracted() def test_get_files(self): assert self.helper.left.get_files() == ( self.helper.get_files()) def test_diffable(self): self.helper.extract() self.helper.select('install.js') assert self.helper.is_diffable() def test_diffable_one_missing(self): self.helper.extract() os.remove(os.path.join(self.helper.right.dest, 'install.js')) self.helper.select('install.js') assert self.helper.is_diffable() def test_diffable_allow_empty(self): self.helper.extract() self.assertRaises(AssertionError, self.helper.right.read_file) assert self.helper.right.read_file(allow_empty=True) == '' def test_diffable_both_missing(self): self.helper.extract() self.helper.select('foo.js') assert not self.helper.is_diffable() def test_diffable_deleted_files(self): self.helper.extract() os.remove(os.path.join(self.helper.left.dest, 'install.js')) assert 'install.js' in self.helper.get_deleted_files() def test_diffable_one_binary_same(self): self.helper.extract() self.helper.select('install.js') self.helper.left.selected['binary'] = True assert self.helper.is_binary() def test_diffable_one_binary_diff(self): self.helper.extract() self.change(self.helper.left.dest, 'asd') self.helper.select('install.js') self.helper.left.selected['binary'] = True assert self.helper.is_binary() def test_diffable_two_binary_diff(self): self.helper.extract() self.change(self.helper.left.dest, 'asd') self.change(self.helper.right.dest, 'asd123') self.clear_cache() self.helper.select('install.js') self.helper.left.selected['binary'] = True self.helper.right.selected['binary'] = True assert self.helper.is_binary() def test_diffable_one_directory(self): self.helper.extract() self.helper.select('install.js') self.helper.left.selected['directory'] = True assert not self.helper.is_diffable() assert self.helper.left.selected['msg'].startswith('This file') def test_diffable_parent(self): self.helper.extract() self.change(self.helper.left.dest, 'asd', filename='__MACOSX/._dictionaries') self.clear_cache() files = self.helper.get_files() assert files['__MACOSX/._dictionaries']['diff'] assert files['__MACOSX']['diff'] def change(self, file, text, filename='install.js'): path = os.path.join(file, filename) with open(path, 'rb') as f: data = f.read() data += text.encode('utf-8') with open(path, 'wb') as f2: f2.write(data) class TestSafeZipFile(TestCase, amo.tests.AMOPaths): # TODO(andym): get full coverage for existing SafeZip methods, most # is covered in the file viewer tests. @patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5) def test_unzip_limit(self): with pytest.raises(forms.ValidationError): SafeZip(self.xpi_path('langpack-localepicker')) def test_unzip_fatal(self): with pytest.raises(zipfile.BadZipFile): SafeZip(self.xpi_path('search.xml')) def test_read(self): zip_file = SafeZip(self.xpi_path('langpack-localepicker')) assert b'locale browser de' in zip_file.read('chrome.manifest') def test_not_secure(self): zip_file = SafeZip(self.xpi_path('extension')) assert not zip_file.is_signed() def test_is_secure(self): zip_file = SafeZip(self.xpi_path('signed')) assert zip_file.is_signed() def test_is_broken(self): zip_file = SafeZip(self.xpi_path('signed')) zip_file.info_list[2].filename = 'META-INF/foo.sf' assert not zip_file.is_signed()
true
true
f72c7105b40a75a34bc96103e54bc62ef812eb03
4,785
py
Python
rapvis/rapvis_process.py
liuwell/rapvis
a69d06a31b1d7fe4510c1c90bfeee22b68a9b3b9
[ "MIT" ]
1
2020-10-25T10:23:45.000Z
2020-10-25T10:23:45.000Z
rapvis/rapvis_process.py
liuwell/rapvis
a69d06a31b1d7fe4510c1c90bfeee22b68a9b3b9
[ "MIT" ]
null
null
null
rapvis/rapvis_process.py
liuwell/rapvis
a69d06a31b1d7fe4510c1c90bfeee22b68a9b3b9
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import glob import argparse import numpy as np import subprocess import os import time import sys #from rapvis_merge import merge_profiles, merge_gene_counts #from rapvis_gene_dis import gene_dis #from rapvis_quality import rRNAratio from rapvis_general import current_time import rapvis_rRNA def process2(R1, R2, output, adapter, threads, libpath, mapper, minlen, trim5, counts, rRNA): file_name = R1.split("/")[-1].split("_")[0] outdir = os.path.join(output, file_name) ### make directory if not os.path.exists(outdir): try: os.makedirs(outdir) except Exception as e: pass prefix = os.path.join(outdir, file_name) out_R1_p = prefix + "_R1.fq.gz" out_R1_u = prefix + "_R1_unpaired.gz" out_R2_p = prefix + "_R2.fq.gz" out_R2_u = prefix + "_R2_unpaired.gz" out_log = prefix + "_trimmomatic.log" print("\n%s Processing: %s, %s" % (current_time(), R1,R2)) realpath = sys.path[0] ### trimmomatic subprocess.call("trimmomatic PE -threads %d -phred33 %s %s %s %s %s %s ILLUMINACLIP:%s/../library/adapter/%s:1:30:10:5 SLIDINGWINDOW:4:20 MINLEN:%d HEADCROP:%d 2> %s" % (threads, R1, R2, out_R1_p, out_R1_u, out_R2_p, out_R2_u, realpath, adapter, minlen, trim5, out_log), shell=True) ### Mapping by hisat2 if mapper == 'hisat2': SummaryFile = prefix + "_hisat_summary.txt" MapOut = prefix + "_hisat_sort.bam" subprocess.call("hisat2 -p %d -x %s/genome_tran -1 %s -2 %s -U %s,%s -t --dta --summary-file %s --new-summary|samtools sort -@ %d -m 10G -o %s" % (threads, libpath, out_R1_p, out_R2_p, out_R1_u, out_R2_u, SummaryFile, threads, MapOut), shell=True) ### Mapping by STAR elif mapper == 'STAR': STARprefix = prefix + "_STAR_" subprocess.call("STAR --runThreadN %d --outSAMtype BAM SortedByCoordinate --genomeDir %s --readFilesIn %s %s --readFilesCommand zcat --outFileNamePrefix %s --quantMode GeneCounts --outFilterScoreMinOverLread 0.1 --outFilterMatchNminOverLread 0.1 --outFilterMatchNmin 0 --outFilterMismatchNmax 2" % (threads, libpath, out_R1_p, out_R2_p, STARprefix), shell=True) MapOut = prefix + "_STAR_Aligned.sortedByCoord.out.bam" ## sorted bam file ### Asemble by stringtie print("%s Asemble ..." % current_time()) stringtieGTF = prefix + '_stringtie.gtf' stringtieGene = prefix + '_gene_abund.tab' subprocess.call("stringtie %s -e -G %s/annotation.gtf -p %d -o %s -A %s" % (MapOut, libpath, threads, stringtieGTF, stringtieGene), shell=True) ### Gene counts if counts: countOut = prefix + '_gene_counts.txt' subprocess.call("featureCounts -a %s/annotation.gtf -o %s %s -t exon -g gene_name -T %d -Q 30 -p" % (libpath, countOut, MapOut, threads), shell=True) ### rRNA if rRNA: rapvis_rRNA.rRNA(R1, R2, output, threads) if __name__ == '__main__': parser = argparse.ArgumentParser(description='A tool for RNAseq processing and visualization') parser.add_argument('-R1', required=True, help='the input data R1') parser.add_argument('-R2', required=True, help='the input data R2') parser.add_argument('-o', '--output', default = 'processed_data', help = 'output directory (default: processed_data)') parser.add_argument('-p', '--threads', default=5, type=int, help='number of threads (CPUs) to use (default: 5)') #parser.add_argument('-s', '--species', default='Human', choices=['Human', 'Mouse', 'Rat', 'Rabbit', 'GoldenHamster', 'Zebrafish'], type=str, help='choose reference species for mapping and annotaion (default: Human)') parser.add_argument('-lib', '--libraryPath', type=str, help='choose reference species for mapping and annotaion') parser.add_argument('-m', '--mapper', default='hisat2', choices=['hisat2', 'STAR'], type=str, help='choose the mapping program (default: hisat2)') parser.add_argument('-a', '--adapter', default='nextera', type=str, help='choose illumina adaptor (default: nextera), choices {nextera, universal, pAAAAA}') parser.add_argument('--minlen', default=35, type=int, help='discard reads shorter than LEN (default: 35)') parser.add_argument('--trim5', default=0, type=int, help='remove bases from the begining of each read (default:0)') parser.add_argument('--counts', action='store_true', help='Get gene counts') parser.add_argument('--rRNA', action='store_true', help='whether mapping to rRNA(Human)') parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.2') args = parser.parse_args() #print("\n%s ..... Start RNAseq processing" % (current_time())) #start_time = time.time() process2(args.R1, args.R2, args.output, args.adapter, args.threads, args.libraryPath, args.mapper, args.minlen, args.trim5, args.counts, args.rRNA) ### #end_time = time.time() #run_time = round((end_time - start_time)/60, 5) #print("\n%s ..... Finished all. Used time: %s m\n" % (current_time(), run_time))
47.376238
366
0.708255
import glob import argparse import numpy as np import subprocess import os import time import sys from rapvis_general import current_time import rapvis_rRNA def process2(R1, R2, output, adapter, threads, libpath, mapper, minlen, trim5, counts, rRNA): file_name = R1.split("/")[-1].split("_")[0] outdir = os.path.join(output, file_name) try: os.makedirs(outdir) except Exception as e: pass prefix = os.path.join(outdir, file_name) out_R1_p = prefix + "_R1.fq.gz" out_R1_u = prefix + "_R1_unpaired.gz" out_R2_p = prefix + "_R2.fq.gz" out_R2_u = prefix + "_R2_unpaired.gz" out_log = prefix + "_trimmomatic.log" print("\n%s Processing: %s, %s" % (current_time(), R1,R2)) realpath = sys.path[0] tic PE -threads %d -phred33 %s %s %s %s %s %s ILLUMINACLIP:%s/../library/adapter/%s:1:30:10:5 SLIDINGWINDOW:4:20 MINLEN:%d HEADCROP:%d 2> %s" % (threads, R1, R2, out_R1_p, out_R1_u, out_R2_p, out_R2_u, realpath, adapter, minlen, trim5, out_log), shell=True) = prefix + "_hisat_summary.txt" MapOut = prefix + "_hisat_sort.bam" subprocess.call("hisat2 -p %d -x %s/genome_tran -1 %s -2 %s -U %s,%s -t --dta --summary-file %s --new-summary|samtools sort -@ %d -m 10G -o %s" % (threads, libpath, out_R1_p, out_R2_p, out_R1_u, out_R2_u, SummaryFile, threads, MapOut), shell=True) ix = prefix + "_STAR_" subprocess.call("STAR --runThreadN %d --outSAMtype BAM SortedByCoordinate --genomeDir %s --readFilesIn %s %s --readFilesCommand zcat --outFileNamePrefix %s --quantMode GeneCounts --outFilterScoreMinOverLread 0.1 --outFilterMatchNminOverLread 0.1 --outFilterMatchNmin 0 --outFilterMismatchNmax 2" % (threads, libpath, out_R1_p, out_R2_p, STARprefix), shell=True) MapOut = prefix + "_STAR_Aligned.sortedByCoord.out.bam" = prefix + '_stringtie.gtf' stringtieGene = prefix + '_gene_abund.tab' subprocess.call("stringtie %s -e -G %s/annotation.gtf -p %d -o %s -A %s" % (MapOut, libpath, threads, stringtieGTF, stringtieGene), shell=True) refix + '_gene_counts.txt' subprocess.call("featureCounts -a %s/annotation.gtf -o %s %s -t exon -g gene_name -T %d -Q 30 -p" % (libpath, countOut, MapOut, threads), shell=True) rapvis_rRNA.rRNA(R1, R2, output, threads) if __name__ == '__main__': parser = argparse.ArgumentParser(description='A tool for RNAseq processing and visualization') parser.add_argument('-R1', required=True, help='the input data R1') parser.add_argument('-R2', required=True, help='the input data R2') parser.add_argument('-o', '--output', default = 'processed_data', help = 'output directory (default: processed_data)') parser.add_argument('-p', '--threads', default=5, type=int, help='number of threads (CPUs) to use (default: 5)') parser.add_argument('-lib', '--libraryPath', type=str, help='choose reference species for mapping and annotaion') parser.add_argument('-m', '--mapper', default='hisat2', choices=['hisat2', 'STAR'], type=str, help='choose the mapping program (default: hisat2)') parser.add_argument('-a', '--adapter', default='nextera', type=str, help='choose illumina adaptor (default: nextera), choices {nextera, universal, pAAAAA}') parser.add_argument('--minlen', default=35, type=int, help='discard reads shorter than LEN (default: 35)') parser.add_argument('--trim5', default=0, type=int, help='remove bases from the begining of each read (default:0)') parser.add_argument('--counts', action='store_true', help='Get gene counts') parser.add_argument('--rRNA', action='store_true', help='whether mapping to rRNA(Human)') parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.2') args = parser.parse_args() process2(args.R1, args.R2, args.output, args.adapter, args.threads, args.libraryPath, args.mapper, args.minlen, args.trim5, args.counts, args.rRNA)
true
true
f72c731f3e730de450ee248c0486bff1226a032a
322
py
Python
bin/gen-nfs-fstab.py
french-tries/auto-distro
bd2fccd7862f97b0f91e742b3c53af045b0a4475
[ "MIT" ]
null
null
null
bin/gen-nfs-fstab.py
french-tries/auto-distro
bd2fccd7862f97b0f91e742b3c53af045b0a4475
[ "MIT" ]
null
null
null
bin/gen-nfs-fstab.py
french-tries/auto-distro
bd2fccd7862f97b0f91e742b3c53af045b0a4475
[ "MIT" ]
null
null
null
import os import configuration output = '/etc/fstab' with open(output, mode='a') as fstab: fstab.write('\n\n') for entry in configuration.nfs_entries: os.makedirs(entry[1], exist_ok=True) fstab.write(entry[0].ljust(50) + entry[1].ljust(40) + 'nfs'.ljust(10) + 'noauto'.ljust(30) + '0 0\n')
24.769231
109
0.630435
import os import configuration output = '/etc/fstab' with open(output, mode='a') as fstab: fstab.write('\n\n') for entry in configuration.nfs_entries: os.makedirs(entry[1], exist_ok=True) fstab.write(entry[0].ljust(50) + entry[1].ljust(40) + 'nfs'.ljust(10) + 'noauto'.ljust(30) + '0 0\n')
true
true
f72c73488e94790062a1acf9156e490fc7770946
7,753
py
Python
sdk/python/pulumi_azure_native/datalakeanalytics/compute_policy.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/datalakeanalytics/compute_policy.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/datalakeanalytics/compute_policy.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from ._enums import * __all__ = ['ComputePolicy'] class ComputePolicy(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, account_name: Optional[pulumi.Input[str]] = None, compute_policy_name: Optional[pulumi.Input[str]] = None, max_degree_of_parallelism_per_job: Optional[pulumi.Input[int]] = None, min_priority_per_job: Optional[pulumi.Input[int]] = None, object_id: Optional[pulumi.Input[str]] = None, object_type: Optional[pulumi.Input[Union[str, 'AADObjectType']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): """ Data Lake Analytics compute policy information. API Version: 2016-11-01. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] account_name: The name of the Data Lake Analytics account. :param pulumi.Input[str] compute_policy_name: The name of the compute policy to create or update. :param pulumi.Input[int] max_degree_of_parallelism_per_job: The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. :param pulumi.Input[int] min_priority_per_job: The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. :param pulumi.Input[str] object_id: The AAD object identifier for the entity to create a policy for. :param pulumi.Input[Union[str, 'AADObjectType']] object_type: The type of AAD object the object identifier refers to. :param pulumi.Input[str] resource_group_name: The name of the Azure resource group. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() if account_name is None and not opts.urn: raise TypeError("Missing required property 'account_name'") __props__['account_name'] = account_name __props__['compute_policy_name'] = compute_policy_name __props__['max_degree_of_parallelism_per_job'] = max_degree_of_parallelism_per_job __props__['min_priority_per_job'] = min_priority_per_job if object_id is None and not opts.urn: raise TypeError("Missing required property 'object_id'") __props__['object_id'] = object_id if object_type is None and not opts.urn: raise TypeError("Missing required property 'object_type'") __props__['object_type'] = object_type if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['name'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:datalakeanalytics:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20161101:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20161101:ComputePolicy")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ComputePolicy, __self__).__init__( 'azure-native:datalakeanalytics:ComputePolicy', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ComputePolicy': """ Get an existing ComputePolicy resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["max_degree_of_parallelism_per_job"] = None __props__["min_priority_per_job"] = None __props__["name"] = None __props__["object_id"] = None __props__["object_type"] = None __props__["type"] = None return ComputePolicy(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="maxDegreeOfParallelismPerJob") def max_degree_of_parallelism_per_job(self) -> pulumi.Output[int]: """ The maximum degree of parallelism per job this user can use to submit jobs. """ return pulumi.get(self, "max_degree_of_parallelism_per_job") @property @pulumi.getter(name="minPriorityPerJob") def min_priority_per_job(self) -> pulumi.Output[int]: """ The minimum priority per job this user can use to submit jobs. """ return pulumi.get(self, "min_priority_per_job") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="objectId") def object_id(self) -> pulumi.Output[str]: """ The AAD object identifier for the entity to create a policy for. """ return pulumi.get(self, "object_id") @property @pulumi.getter(name="objectType") def object_type(self) -> pulumi.Output[str]: """ The type of AAD object the object identifier refers to. """ return pulumi.get(self, "object_type") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ The resource type. """ return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
47.564417
601
0.665549
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from ._enums import * __all__ = ['ComputePolicy'] class ComputePolicy(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, account_name: Optional[pulumi.Input[str]] = None, compute_policy_name: Optional[pulumi.Input[str]] = None, max_degree_of_parallelism_per_job: Optional[pulumi.Input[int]] = None, min_priority_per_job: Optional[pulumi.Input[int]] = None, object_id: Optional[pulumi.Input[str]] = None, object_type: Optional[pulumi.Input[Union[str, 'AADObjectType']]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() if account_name is None and not opts.urn: raise TypeError("Missing required property 'account_name'") __props__['account_name'] = account_name __props__['compute_policy_name'] = compute_policy_name __props__['max_degree_of_parallelism_per_job'] = max_degree_of_parallelism_per_job __props__['min_priority_per_job'] = min_priority_per_job if object_id is None and not opts.urn: raise TypeError("Missing required property 'object_id'") __props__['object_id'] = object_id if object_type is None and not opts.urn: raise TypeError("Missing required property 'object_type'") __props__['object_type'] = object_type if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['name'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:datalakeanalytics:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20161101:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20161101:ComputePolicy")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ComputePolicy, __self__).__init__( 'azure-native:datalakeanalytics:ComputePolicy', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ComputePolicy': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["max_degree_of_parallelism_per_job"] = None __props__["min_priority_per_job"] = None __props__["name"] = None __props__["object_id"] = None __props__["object_type"] = None __props__["type"] = None return ComputePolicy(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="maxDegreeOfParallelismPerJob") def max_degree_of_parallelism_per_job(self) -> pulumi.Output[int]: return pulumi.get(self, "max_degree_of_parallelism_per_job") @property @pulumi.getter(name="minPriorityPerJob") def min_priority_per_job(self) -> pulumi.Output[int]: return pulumi.get(self, "min_priority_per_job") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="objectId") def object_id(self) -> pulumi.Output[str]: return pulumi.get(self, "object_id") @property @pulumi.getter(name="objectType") def object_type(self) -> pulumi.Output[str]: return pulumi.get(self, "object_type") @property @pulumi.getter def type(self) -> pulumi.Output[str]: return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
true
true
f72c7352f5956d525aae8e8f597fdae21fe13578
547
py
Python
examples/get_server_info.py
edvinerikson/frostbite-rcon-utils
089e1a59b7fcd72b8d8d3153fb396cfd8d4869f3
[ "MIT" ]
7
2016-10-10T08:21:15.000Z
2022-03-12T23:45:24.000Z
examples/get_server_info.py
EdvinErikson/frostbite-rcon-utils
089e1a59b7fcd72b8d8d3153fb396cfd8d4869f3
[ "MIT" ]
2
2016-02-18T16:11:48.000Z
2016-02-18T17:24:14.000Z
examples/get_server_info.py
EdvinErikson/frostbite-rcon-utils
089e1a59b7fcd72b8d8d3153fb396cfd8d4869f3
[ "MIT" ]
2
2016-02-17T22:14:47.000Z
2016-08-13T01:52:32.000Z
import socket from frostbite_rcon_utils import create_packet, encode_packet, decode_packet, contains_complete_packet connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.settimeout(1) connection.connect(('188.126.64.4', 47215)) connection.setblocking(1) packet_to_send = encode_packet(create_packet(0, False, False, ['serverInfo'])) connection.send(packet_to_send) data_buffer = "" while not contains_complete_packet(data_buffer): data_buffer += connection.recv(2048) packet = decode_packet(data_buffer) print(packet)
30.388889
102
0.8117
import socket from frostbite_rcon_utils import create_packet, encode_packet, decode_packet, contains_complete_packet connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.settimeout(1) connection.connect(('188.126.64.4', 47215)) connection.setblocking(1) packet_to_send = encode_packet(create_packet(0, False, False, ['serverInfo'])) connection.send(packet_to_send) data_buffer = "" while not contains_complete_packet(data_buffer): data_buffer += connection.recv(2048) packet = decode_packet(data_buffer) print(packet)
true
true
f72c73592fff23ee5fe753971e6446fe835d7fc5
1,158
py
Python
sympy/strategies/branch/tests/test_traverse.py
ovolve/sympy
0a15782f20505673466b940454b33b8014a25c13
[ "BSD-3-Clause" ]
1
2016-02-22T22:46:50.000Z
2016-02-22T22:46:50.000Z
sympy/strategies/branch/tests/test_traverse.py
ovolve/sympy
0a15782f20505673466b940454b33b8014a25c13
[ "BSD-3-Clause" ]
7
2017-05-01T14:15:32.000Z
2017-09-06T20:44:24.000Z
sympy/strategies/branch/tests/test_traverse.py
ovolve/sympy
0a15782f20505673466b940454b33b8014a25c13
[ "BSD-3-Clause" ]
1
2020-09-09T15:20:27.000Z
2020-09-09T15:20:27.000Z
from sympy import Basic from sympy.strategies.branch.traverse import top_down, sall from sympy.strategies.branch.core import do_one, identity def inc(x): if isinstance(x, int): yield x + 1 def test_top_down_easy(): expr = Basic(1, 2) expected = Basic(2, 3) brl = top_down(inc) assert set(brl(expr)) == set([expected]) def test_top_down_big_tree(): expr = Basic(1, Basic(2), Basic(3, Basic(4), 5)) expected = Basic(2, Basic(3), Basic(4, Basic(5), 6)) brl = top_down(inc) assert set(brl(expr)) == set([expected]) def test_top_down_harder_function(): def split5(x): if x == 5: yield x - 1 yield x + 1 expr = Basic(Basic(5, 6), 1) expected = set([Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)]) brl = top_down(split5) assert set(brl(expr)) == expected def test_sall(): expr = Basic(1, 2) expected = Basic(2, 3) brl = sall(inc) assert list(brl(expr)) == [expected] expr = Basic(1, 2, Basic(3, 4)) expected = Basic(2, 3, Basic(3, 4)) brl = sall(do_one(inc, identity)) assert list(brl(expr)) == [expected]
24.638298
66
0.58981
from sympy import Basic from sympy.strategies.branch.traverse import top_down, sall from sympy.strategies.branch.core import do_one, identity def inc(x): if isinstance(x, int): yield x + 1 def test_top_down_easy(): expr = Basic(1, 2) expected = Basic(2, 3) brl = top_down(inc) assert set(brl(expr)) == set([expected]) def test_top_down_big_tree(): expr = Basic(1, Basic(2), Basic(3, Basic(4), 5)) expected = Basic(2, Basic(3), Basic(4, Basic(5), 6)) brl = top_down(inc) assert set(brl(expr)) == set([expected]) def test_top_down_harder_function(): def split5(x): if x == 5: yield x - 1 yield x + 1 expr = Basic(Basic(5, 6), 1) expected = set([Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)]) brl = top_down(split5) assert set(brl(expr)) == expected def test_sall(): expr = Basic(1, 2) expected = Basic(2, 3) brl = sall(inc) assert list(brl(expr)) == [expected] expr = Basic(1, 2, Basic(3, 4)) expected = Basic(2, 3, Basic(3, 4)) brl = sall(do_one(inc, identity)) assert list(brl(expr)) == [expected]
true
true
f72c73b22f0837188e5fc58d0e9f23032e5dba90
2,695
py
Python
data/p4VQE/R4/benchmark/startQiskit_QC277.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p4VQE/R4/benchmark/startQiskit_QC277.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p4VQE/R4/benchmark/startQiskit_QC277.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
# qubit number=3 # total number=15 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def make_circuit(n:int) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.cx(input_qubit[0],input_qubit[2]) # number=9 prog.x(input_qubit[2]) # number=10 prog.h(input_qubit[2]) # number=12 prog.cz(input_qubit[0],input_qubit[2]) # number=13 prog.h(input_qubit[2]) # number=14 prog.h(input_qubit[3]) # number=4 prog.y(input_qubit[3]) # number=5 for edge in E: k = edge[0] l = edge[1] prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1]) prog.p(gamma, k) prog.p(gamma, l) prog.rx(2 * beta, range(len(V))) prog.cx(input_qubit[1],input_qubit[0]) # number=7 prog.cx(input_qubit[1],input_qubit[0]) # number=8 # circuit end return prog if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * ( 1 + np.cos(4 * a_gamma) ** 2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot =5600 writefile = open("../data/startQiskit_QC277.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_5_yorktown") circuit1 = transpile(prog, FakeYorktown()) circuit1.measure_all() prog = circuit1 info = execute(prog,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
28.072917
118
0.636735
import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def make_circuit(n:int) -> QuantumCircuit: input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) prog.h(input_qubit[1]) prog.h(input_qubit[2]) prog.cx(input_qubit[0],input_qubit[2]) prog.x(input_qubit[2]) prog.h(input_qubit[2]) prog.cz(input_qubit[0],input_qubit[2]) prog.h(input_qubit[2]) prog.h(input_qubit[3]) prog.y(input_qubit[3]) for edge in E: k = edge[0] l = edge[1] prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1]) prog.p(gamma, k) prog.p(gamma, l) prog.rx(2 * beta, range(len(V))) prog.cx(input_qubit[1],input_qubit[0]) prog.cx(input_qubit[1],input_qubit[0]) return prog if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * ( 1 + np.cos(4 * a_gamma) ** 2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot =5600 writefile = open("../data/startQiskit_QC277.csv", "w") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_5_yorktown") circuit1 = transpile(prog, FakeYorktown()) circuit1.measure_all() prog = circuit1 info = execute(prog,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
true
true
f72c757fb6a92103d778c73856fcee6786544a37
6,342
py
Python
test/test_conventions.py
takluyver/xray
80c30ae343a2171c541da0387fed3926004030a7
[ "Apache-2.0" ]
null
null
null
test/test_conventions.py
takluyver/xray
80c30ae343a2171c541da0387fed3926004030a7
[ "Apache-2.0" ]
null
null
null
test/test_conventions.py
takluyver/xray
80c30ae343a2171c541da0387fed3926004030a7
[ "Apache-2.0" ]
null
null
null
import numpy as np import pandas as pd from datetime import datetime import warnings from xray import conventions from . import TestCase, requires_netCDF4 class TestMaskedAndScaledArray(TestCase): def test(self): x = conventions.MaskedAndScaledArray(np.arange(3), fill_value=0) self.assertEqual(x.dtype, np.dtype('float')) self.assertEqual(x.shape, (3,)) self.assertEqual(x.size, 3) self.assertEqual(x.ndim, 1) self.assertEqual(len(x), 3) self.assertArrayEqual([np.nan, 1, 2], x) x = conventions.MaskedAndScaledArray(np.arange(3), add_offset=1) self.assertArrayEqual(np.arange(3) + 1, x) x = conventions.MaskedAndScaledArray(np.arange(3), scale_factor=2) self.assertArrayEqual(2 * np.arange(3), x) x = conventions.MaskedAndScaledArray(np.array([-99, -1, 0, 1, 2]), -99, 0.01, 1) expected = np.array([np.nan, 0.99, 1, 1.01, 1.02]) self.assertArrayEqual(expected, x) def test_0d(self): x = conventions.MaskedAndScaledArray(np.array(0), fill_value=0) self.assertTrue(np.isnan(x)) self.assertTrue(np.isnan(x[...])) x = conventions.MaskedAndScaledArray(np.array(0), fill_value=10) self.assertEqual(0, x[...]) class TestCharToStringArray(TestCase): def test(self): array = np.array(list('abc')) actual = conventions.CharToStringArray(array) expected = np.array('abc') self.assertEqual(actual.dtype, expected.dtype) self.assertEqual(actual.shape, expected.shape) self.assertEqual(actual.size, expected.size) self.assertEqual(actual.ndim, expected.ndim) with self.assertRaises(TypeError): len(actual) self.assertArrayEqual(expected, actual) with self.assertRaises(IndexError): actual[:2] self.assertEqual(str(actual), 'abc') array = np.array([list('abc'), list('cdf')]) actual = conventions.CharToStringArray(array) expected = np.array(['abc', 'cdf']) self.assertEqual(actual.dtype, expected.dtype) self.assertEqual(actual.shape, expected.shape) self.assertEqual(actual.size, expected.size) self.assertEqual(actual.ndim, expected.ndim) self.assertEqual(len(actual), len(expected)) self.assertArrayEqual(expected, actual) self.assertArrayEqual(expected[:1], actual[:1]) with self.assertRaises(IndexError): actual[:, :2] class TestDatetime(TestCase): @requires_netCDF4 def test_cf_datetime(self): import netCDF4 as nc4 for num_dates, units in [ (np.arange(100), 'days since 2000-01-01'), (np.arange(100).reshape(10, 10), 'days since 2000-01-01'), (12300 + np.arange(50), 'hours since 1680-01-01 00:00:00'), (10, 'days since 2000-01-01'), ([10], 'days since 2000-01-01'), ([[10]], 'days since 2000-01-01'), ([10, 10], 'days since 2000-01-01'), (0, 'days since 1000-01-01'), ([0], 'days since 1000-01-01'), ([[0]], 'days since 1000-01-01'), (np.arange(20), 'days since 1000-01-01'), (np.arange(0, 100000, 10000), 'days since 1900-01-01') ]: for calendar in ['standard', 'gregorian', 'proleptic_gregorian']: expected = nc4.num2date(num_dates, units, calendar) actual = conventions.decode_cf_datetime(num_dates, units, calendar) if (isinstance(actual, np.ndarray) and np.issubdtype(actual.dtype, np.datetime64)): self.assertEqual(actual.dtype, np.dtype('M8[ns]')) # For some reason, numpy 1.8 does not compare ns precision # datetime64 arrays as equal to arrays of datetime objects, # but it works for us precision. Thus, convert to us # precision for the actual array equal comparison... actual_cmp = actual.astype('M8[us]') else: actual_cmp = actual self.assertArrayEqual(expected, actual_cmp) encoded, _, _ = conventions.encode_cf_datetime(actual, units, calendar) self.assertArrayEqual(num_dates, np.around(encoded)) if (hasattr(num_dates, 'ndim') and num_dates.ndim == 1 and '1000' not in units): # verify that wrapping with a pandas.Index works # note that it *does not* currently work to even put # non-datetime64 compatible dates into a pandas.Index :( encoded, _, _ = conventions.encode_cf_datetime( pd.Index(actual), units, calendar) self.assertArrayEqual(num_dates, np.around(encoded)) @requires_netCDF4 def test_cf_datetime_nan(self): for num_dates, units, expected_list in [ ([np.nan], 'days since 2000-01-01', ['NaT']), ([np.nan, 0], 'days since 2000-01-01', ['NaT', '2000-01-01T00:00:00Z']), ([np.nan, 0, 1], 'days since 2000-01-01', ['NaT', '2000-01-01T00:00:00Z', '2000-01-02T00:00:00Z']), ]: with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'All-NaN') actual = conventions.decode_cf_datetime(num_dates, units) expected = np.array(expected_list, dtype='datetime64[ns]') self.assertArrayEqual(expected, actual) def test_guess_time_units(self): for dates, expected in [(pd.date_range('1900-01-01', periods=5), 'days since 1900-01-01 00:00:00'), (pd.date_range('1900-01-01 12:00:00', freq='H', periods=2), 'hours since 1900-01-01 12:00:00'), (['1900-01-01', '1900-01-02', '1900-01-02 00:00:01'], 'seconds since 1900-01-01 00:00:00')]: self.assertEquals(expected, conventions.guess_time_units(dates))
46.291971
88
0.564018
import numpy as np import pandas as pd from datetime import datetime import warnings from xray import conventions from . import TestCase, requires_netCDF4 class TestMaskedAndScaledArray(TestCase): def test(self): x = conventions.MaskedAndScaledArray(np.arange(3), fill_value=0) self.assertEqual(x.dtype, np.dtype('float')) self.assertEqual(x.shape, (3,)) self.assertEqual(x.size, 3) self.assertEqual(x.ndim, 1) self.assertEqual(len(x), 3) self.assertArrayEqual([np.nan, 1, 2], x) x = conventions.MaskedAndScaledArray(np.arange(3), add_offset=1) self.assertArrayEqual(np.arange(3) + 1, x) x = conventions.MaskedAndScaledArray(np.arange(3), scale_factor=2) self.assertArrayEqual(2 * np.arange(3), x) x = conventions.MaskedAndScaledArray(np.array([-99, -1, 0, 1, 2]), -99, 0.01, 1) expected = np.array([np.nan, 0.99, 1, 1.01, 1.02]) self.assertArrayEqual(expected, x) def test_0d(self): x = conventions.MaskedAndScaledArray(np.array(0), fill_value=0) self.assertTrue(np.isnan(x)) self.assertTrue(np.isnan(x[...])) x = conventions.MaskedAndScaledArray(np.array(0), fill_value=10) self.assertEqual(0, x[...]) class TestCharToStringArray(TestCase): def test(self): array = np.array(list('abc')) actual = conventions.CharToStringArray(array) expected = np.array('abc') self.assertEqual(actual.dtype, expected.dtype) self.assertEqual(actual.shape, expected.shape) self.assertEqual(actual.size, expected.size) self.assertEqual(actual.ndim, expected.ndim) with self.assertRaises(TypeError): len(actual) self.assertArrayEqual(expected, actual) with self.assertRaises(IndexError): actual[:2] self.assertEqual(str(actual), 'abc') array = np.array([list('abc'), list('cdf')]) actual = conventions.CharToStringArray(array) expected = np.array(['abc', 'cdf']) self.assertEqual(actual.dtype, expected.dtype) self.assertEqual(actual.shape, expected.shape) self.assertEqual(actual.size, expected.size) self.assertEqual(actual.ndim, expected.ndim) self.assertEqual(len(actual), len(expected)) self.assertArrayEqual(expected, actual) self.assertArrayEqual(expected[:1], actual[:1]) with self.assertRaises(IndexError): actual[:, :2] class TestDatetime(TestCase): @requires_netCDF4 def test_cf_datetime(self): import netCDF4 as nc4 for num_dates, units in [ (np.arange(100), 'days since 2000-01-01'), (np.arange(100).reshape(10, 10), 'days since 2000-01-01'), (12300 + np.arange(50), 'hours since 1680-01-01 00:00:00'), (10, 'days since 2000-01-01'), ([10], 'days since 2000-01-01'), ([[10]], 'days since 2000-01-01'), ([10, 10], 'days since 2000-01-01'), (0, 'days since 1000-01-01'), ([0], 'days since 1000-01-01'), ([[0]], 'days since 1000-01-01'), (np.arange(20), 'days since 1000-01-01'), (np.arange(0, 100000, 10000), 'days since 1900-01-01') ]: for calendar in ['standard', 'gregorian', 'proleptic_gregorian']: expected = nc4.num2date(num_dates, units, calendar) actual = conventions.decode_cf_datetime(num_dates, units, calendar) if (isinstance(actual, np.ndarray) and np.issubdtype(actual.dtype, np.datetime64)): self.assertEqual(actual.dtype, np.dtype('M8[ns]')) actual_cmp = actual.astype('M8[us]') else: actual_cmp = actual self.assertArrayEqual(expected, actual_cmp) encoded, _, _ = conventions.encode_cf_datetime(actual, units, calendar) self.assertArrayEqual(num_dates, np.around(encoded)) if (hasattr(num_dates, 'ndim') and num_dates.ndim == 1 and '1000' not in units): encoded, _, _ = conventions.encode_cf_datetime( pd.Index(actual), units, calendar) self.assertArrayEqual(num_dates, np.around(encoded)) @requires_netCDF4 def test_cf_datetime_nan(self): for num_dates, units, expected_list in [ ([np.nan], 'days since 2000-01-01', ['NaT']), ([np.nan, 0], 'days since 2000-01-01', ['NaT', '2000-01-01T00:00:00Z']), ([np.nan, 0, 1], 'days since 2000-01-01', ['NaT', '2000-01-01T00:00:00Z', '2000-01-02T00:00:00Z']), ]: with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'All-NaN') actual = conventions.decode_cf_datetime(num_dates, units) expected = np.array(expected_list, dtype='datetime64[ns]') self.assertArrayEqual(expected, actual) def test_guess_time_units(self): for dates, expected in [(pd.date_range('1900-01-01', periods=5), 'days since 1900-01-01 00:00:00'), (pd.date_range('1900-01-01 12:00:00', freq='H', periods=2), 'hours since 1900-01-01 12:00:00'), (['1900-01-01', '1900-01-02', '1900-01-02 00:00:01'], 'seconds since 1900-01-01 00:00:00')]: self.assertEquals(expected, conventions.guess_time_units(dates))
true
true
f72c7674672d02999eb1ca6e63915c7fe5ac8ab5
57
py
Python
Exp2/Strategy/StrategyManager.py
inventivejon/INPROLA-Python
8aab11a868b37a64c46e6287bf358b5b05673a28
[ "Apache-2.0" ]
null
null
null
Exp2/Strategy/StrategyManager.py
inventivejon/INPROLA-Python
8aab11a868b37a64c46e6287bf358b5b05673a28
[ "Apache-2.0" ]
null
null
null
Exp2/Strategy/StrategyManager.py
inventivejon/INPROLA-Python
8aab11a868b37a64c46e6287bf358b5b05673a28
[ "Apache-2.0" ]
null
null
null
class StrategyManager(): def __init__(): pass
19
24
0.614035
class StrategyManager(): def __init__(): pass
true
true
f72c7888070e1278b4c5a0b55319ce31c0795378
23,442
py
Python
SprityBird/spritybird/python3.5/lib/python3.5/site-packages/sympy/printing/octave.py
MobileAnalytics/iPython-Framework
da0e598308c067cd5c5290a6364b3ffaf2d2418f
[ "MIT" ]
4
2018-07-04T17:20:12.000Z
2019-07-14T18:07:25.000Z
SprityBird/spritybird/python3.5/lib/python3.5/site-packages/sympy/printing/octave.py
MobileAnalytics/iPython-Framework
da0e598308c067cd5c5290a6364b3ffaf2d2418f
[ "MIT" ]
null
null
null
SprityBird/spritybird/python3.5/lib/python3.5/site-packages/sympy/printing/octave.py
MobileAnalytics/iPython-Framework
da0e598308c067cd5c5290a6364b3ffaf2d2418f
[ "MIT" ]
1
2018-09-03T03:02:06.000Z
2018-09-03T03:02:06.000Z
""" Octave (and Matlab) code printer The `OctaveCodePrinter` converts SymPy expressions into Octave expressions. It uses a subset of the Octave language for Matlab compatibility. A complete code generator, which uses `octave_code` extensively, can be found in `sympy.utilities.codegen`. The `codegen` module can be used to generate complete source code files. """ from __future__ import print_function, division from sympy.core import Mul, Pow, S, Rational from sympy.core.compatibility import string_types, range from sympy.core.mul import _keep_coeff from sympy.codegen.ast import Assignment from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence from re import search # List of known functions. First, those that have the same name in # SymPy and Octave. This is almost certainly incomplete! known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "acot", "atan", "atan2", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "csch", "sech", "asinh", "acosh", "atanh", "acoth", "asech", "acsch", "erfc", "erfi", "erf", "erfinv", "erfcinv", "besseli", "besselj", "besselk", "bessely", "exp", "factorial", "floor", "fresnelc", "fresnels", "gamma", "log", "polylog", "sign", "zeta"] # These functions have different names ("Sympy": "Octave"), more # generally a mapping to (argument_conditions, octave_function). known_fcns_src2 = { "Abs": "abs", "ceiling": "ceil", "Chi": "coshint", "Ci": "cosint", "conjugate": "conj", "DiracDelta": "dirac", "Heaviside": "heaviside", "laguerre": "laguerreL", "li": "logint", "loggamma": "gammaln", "polygamma": "psi", "Shi": "sinhint", "Si": "sinint", } class OctaveCodePrinter(CodePrinter): """ A printer to convert expressions to strings of Octave/Matlab code. """ printmethod = "_octave" language = "Octave" _operators = { 'and': '&', 'or': '|', 'not': '~', } _default_settings = { 'order': None, 'full_prec': 'auto', 'precision': 16, 'user_functions': {}, 'human': True, 'contract': True, 'inline': True, } # Note: contract is for expressing tensors as loops (if True), or just # assignment (if False). FIXME: this should be looked a more carefully # for Octave. def __init__(self, settings={}): super(OctaveCodePrinter, self).__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) self.known_functions.update(dict(known_fcns_src2)) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "% {0}".format(text) def _declare_number_const(self, name, value): return "{0} = {1};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): # Octave uses Fortran order (column-major) rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: # Octave arrays start at 1 and end at dimension var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("for %s = %s:%s" % (var, start, stop)) close_lines.append("end") return open_lines, close_lines def _print_Mul(self, expr): # print complex numbers nicely in Octave if (expr.is_number and expr.is_imaginary and expr.as_coeff_Mul()[0].is_integer): return "%si" % self._print(-S.ImaginaryUnit*expr) # cribbed from str.py prec = precedence(expr) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator for item in args: if (item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative): if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) for x in b] # from here it differs from str.py to deal with "*" and ".*" def multjoin(a, a_str): # here we probably are assuming the constants will come first r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i-1].is_number else '.*' r = r + mulsym + a_str[i] return r if len(b) == 0: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return sign + multjoin(a, a_str) + divsym + b_str[0] else: divsym = '/' if all([bi.is_number for bi in b]) else './' return (sign + multjoin(a, a_str) + divsym + "(%s)" % multjoin(b, b_str)) def _print_Pow(self, expr): powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^' PREC = precedence(expr) if expr.exp == S.Half: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if expr.exp == -S.Half: sym = '/' if expr.base.is_number else './' return "1" + sym + "sqrt(%s)" % self._print(expr.base) if expr.exp == -S.One: sym = '/' if expr.base.is_number else './' return "1" + sym + "%s" % self.parenthesize(expr.base, PREC) return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_Pi(self, expr): return 'pi' def _print_ImaginaryUnit(self, expr): return "1i" def _print_Exp1(self, expr): return "exp(1)" def _print_GoldenRatio(self, expr): # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)? #return self._print((1+sqrt(S(5)))/2) return "(1+sqrt(5))/2" def _print_NumberSymbol(self, expr): if self._settings["inline"]: return self._print(expr.evalf(self._settings["precision"])) else: # assign to a variable, perhaps more readable for longer program return super(OctaveCodePrinter, self)._print_NumberSymbol(expr) def _print_Assignment(self, expr): from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase # Copied from codeprinter, but remove special MatrixSymbol treatment lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): # Here we modify Piecewise so each expression is now # an Assignment, and then continue on the print. expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Infinity(self, expr): return 'inf' def _print_NegativeInfinity(self, expr): return '-inf' def _print_NaN(self, expr): return 'NaN' def _print_list(self, expr): return '{' + ', '.join(self._print(a) for a in expr) + '}' _print_tuple = _print_list _print_Tuple = _print_list def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return str(expr).lower() # Could generate quadrature code for definite Integrals? #_print_Integral = _print_not_supported def _print_MatrixBase(self, A): # Handle zero dimensions: if (A.rows, A.cols) == (0, 0): return '[]' elif A.rows == 0 or A.cols == 0: return 'zeros(%s, %s)' % (A.rows, A.cols) elif (A.rows, A.cols) == (1, 1): # Octave does not distinguish between scalars and 1x1 matrices return self._print(A[0, 0]) elif A.rows == 1: return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ') elif A.cols == 1: # note .table would unnecessarily equispace the rows return "[%s]" % "; ".join([self._print(a) for a in A]) return "[%s]" % A.table(self, rowstart='', rowend='', rowsep=';\n', colsep=' ') def _print_SparseMatrix(self, A): from sympy.matrices import Matrix L = A.col_list(); # make row vectors of the indices and entries I = Matrix([[k[0] + 1 for k in L]]) J = Matrix([[k[1] + 1 for k in L]]) AIJ = Matrix([[k[2] for k in L]]) return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) # FIXME: Str/CodePrinter could define each of these to call the _print # method from higher up the class hierarchy (see _print_NumberSymbol). # Then subclasses like us would not need to repeat all this. _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ _print_MatrixBase _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_SparseMatrix def _print_MatrixElement(self, expr): return self._print(expr.parent) + '(%s, %s)'%(expr.i+1, expr.j+1) def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 h = x[1] step = x[2] lstr = self._print(l) hstr = 'end' if h == lim else self._print(h) if step == 1: if l == 1 and h == lim: return ':' if l == h: return lstr else: return lstr + ':' + hstr else: return ':'.join((lstr, self._print(step), hstr)) return (self._print(expr.parent) + '(' + strslice(expr.rowslice, expr.parent.shape[0]) + ', ' + strslice(expr.colslice, expr.parent.shape[1]) + ')') def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Identity(self, expr): return "eye(%s)" % self._print(expr.shape[0]) def _print_uppergamma(self, expr): return "gammainc(%s, %s, 'upper')" % (self._print(expr.args[1]), self._print(expr.args[0])) def _print_lowergamma(self, expr): return "gammainc(%s, %s, 'lower')" % (self._print(expr.args[1]), self._print(expr.args[0])) def _print_sinc(self, expr): #Note: Divide by pi because Octave implements normalized sinc function. return "sinc(%s)" % self._print(expr.args[0]/S.Pi) def _print_hankel1(self, expr): return "besselh(%s, 1, %s)" % (self._print(expr.order), self._print(expr.argument)) def _print_hankel2(self, expr): return "besselh(%s, 2, %s)" % (self._print(expr.order), self._print(expr.argument)) # Note: as of 2015, Octave doesn't have spherical Bessel functions def _print_jn(self, expr): from sympy.functions import sqrt, besselj x = expr.argument expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) return self._print(expr2) def _print_yn(self, expr): from sympy.functions import sqrt, bessely x = expr.argument expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) return self._print(expr2) def _print_airyai(self, expr): return "airy(0, %s)" % self._print(expr.args[0]) def _print_airyaiprime(self, expr): return "airy(1, %s)" % self._print(expr.args[0]) def _print_airybi(self, expr): return "airy(2, %s)" % self._print(expr.args[0]) def _print_airybiprime(self, expr): return "airy(3, %s)" % self._print(expr.args[0]) def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if self._settings["inline"]: # Express each (cond, expr) pair in a nested Horner form: # (condition) .* (expr) + (not cond) .* (<others>) # Expressions that result in multiple statements won't work here. ecpairs = ["({0}).*({1}) + (~({0})).*(".format (self._print(c), self._print(e)) for e, c in expr.args[:-1]] elast = "%s" % self._print(expr.args[-1].expr) pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs) # Note: current need these outer brackets for 2*pw. Would be # nicer to teach parenthesize() to do this for us when needed! return "(" + pw + ")" else: for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s)" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("elseif (%s)" % self._print(c)) code0 = self._print(e) lines.append(code0) if i == len(expr.args) - 1: lines.append("end") return "\n".join(lines) def indent_code(self, code): """Accepts a string of code or a list of code lines""" # code mostly copied from ccode if isinstance(code, string_types): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') dec_regex = ('^end$', '^elseif ', '^else$') # pre-strip left-space from the code code = [ line.lstrip(' \t') for line in code ] increase = [ int(any([search(re, line) for re in inc_regex])) for line in code ] decrease = [ int(any([search(re, line) for re in dec_regex])) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line == '' or line == '\n': pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def octave_code(expr, assign_to=None, **settings): r"""Converts `expr` to a string of Octave (or Matlab) code. The string uses a subset of the Octave language for Matlab compatibility. Parameters ========== expr : Expr A sympy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x' >>> from sympy import Rational, ceiling, Abs >>> x, y, tau = symbols("x, y, tau") >>> octave_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau.^(7/2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its very common in Octave to write "vectorized" code. It is harmless if the values are scalars. >>> octave_code(sin(pi*x*y), assign_to="s") 's = sin(pi*x.*y);' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> octave_code(3*pi*A**3) '(3*pi)*A^3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> octave_code(x**2*y*A**3) '(x.^2.*y)*A^3' Matrices are supported using Octave inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimenions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 sin(x) ceil(x)];' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> octave_code(pw, assign_to=tau) 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Octave function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_octave_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx, ccode >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));' """ return OctaveCodePrinter(settings).doprint(expr, assign_to) def print_octave_code(expr, **settings): """Prints the Octave (or Matlab) representation of the given expression. See `octave_code` for the meaning of the optional arguments. """ print(octave_code(expr, **settings))
35.789313
80
0.569533
from __future__ import print_function, division from sympy.core import Mul, Pow, S, Rational from sympy.core.compatibility import string_types, range from sympy.core.mul import _keep_coeff from sympy.codegen.ast import Assignment from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence from re import search known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "acot", "atan", "atan2", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "csch", "sech", "asinh", "acosh", "atanh", "acoth", "asech", "acsch", "erfc", "erfi", "erf", "erfinv", "erfcinv", "besseli", "besselj", "besselk", "bessely", "exp", "factorial", "floor", "fresnelc", "fresnels", "gamma", "log", "polylog", "sign", "zeta"] known_fcns_src2 = { "Abs": "abs", "ceiling": "ceil", "Chi": "coshint", "Ci": "cosint", "conjugate": "conj", "DiracDelta": "dirac", "Heaviside": "heaviside", "laguerre": "laguerreL", "li": "logint", "loggamma": "gammaln", "polygamma": "psi", "Shi": "sinhint", "Si": "sinint", } class OctaveCodePrinter(CodePrinter): printmethod = "_octave" language = "Octave" _operators = { 'and': '&', 'or': '|', 'not': '~', } _default_settings = { 'order': None, 'full_prec': 'auto', 'precision': 16, 'user_functions': {}, 'human': True, 'contract': True, 'inline': True, } def __init__(self, settings={}): super(OctaveCodePrinter, self).__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) self.known_functions.update(dict(known_fcns_src2)) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "% {0}".format(text) def _declare_number_const(self, name, value): return "{0} = {1};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("for %s = %s:%s" % (var, start, stop)) close_lines.append("end") return open_lines, close_lines def _print_Mul(self, expr): if (expr.is_number and expr.is_imaginary and expr.as_coeff_Mul()[0].is_integer): return "%si" % self._print(-S.ImaginaryUnit*expr) prec = precedence(expr) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] b = [] if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: args = Mul.make_args(expr) for item in args: if (item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative): if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) for x in b] def multjoin(a, a_str): r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i-1].is_number else '.*' r = r + mulsym + a_str[i] return r if len(b) == 0: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return sign + multjoin(a, a_str) + divsym + b_str[0] else: divsym = '/' if all([bi.is_number for bi in b]) else './' return (sign + multjoin(a, a_str) + divsym + "(%s)" % multjoin(b, b_str)) def _print_Pow(self, expr): powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^' PREC = precedence(expr) if expr.exp == S.Half: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if expr.exp == -S.Half: sym = '/' if expr.base.is_number else './' return "1" + sym + "sqrt(%s)" % self._print(expr.base) if expr.exp == -S.One: sym = '/' if expr.base.is_number else './' return "1" + sym + "%s" % self.parenthesize(expr.base, PREC) return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_Pi(self, expr): return 'pi' def _print_ImaginaryUnit(self, expr): return "1i" def _print_Exp1(self, expr): return "exp(1)" def _print_GoldenRatio(self, expr): return "(1+sqrt(5))/2" def _print_NumberSymbol(self, expr): if self._settings["inline"]: return self._print(expr.evalf(self._settings["precision"])) else: return super(OctaveCodePrinter, self)._print_NumberSymbol(expr) def _print_Assignment(self, expr): from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase lhs = expr.lhs rhs = expr.rhs if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Infinity(self, expr): return 'inf' def _print_NegativeInfinity(self, expr): return '-inf' def _print_NaN(self, expr): return 'NaN' def _print_list(self, expr): return '{' + ', '.join(self._print(a) for a in expr) + '}' _print_tuple = _print_list _print_Tuple = _print_list def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return str(expr).lower() def _print_MatrixBase(self, A): if (A.rows, A.cols) == (0, 0): return '[]' elif A.rows == 0 or A.cols == 0: return 'zeros(%s, %s)' % (A.rows, A.cols) elif (A.rows, A.cols) == (1, 1): return self._print(A[0, 0]) elif A.rows == 1: return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ') elif A.cols == 1: return "[%s]" % "; ".join([self._print(a) for a in A]) return "[%s]" % A.table(self, rowstart='', rowend='', rowsep=';\n', colsep=' ') def _print_SparseMatrix(self, A): from sympy.matrices import Matrix L = A.col_list(); I = Matrix([[k[0] + 1 for k in L]]) J = Matrix([[k[1] + 1 for k in L]]) AIJ = Matrix([[k[2] for k in L]]) return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ _print_MatrixBase _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_SparseMatrix def _print_MatrixElement(self, expr): return self._print(expr.parent) + '(%s, %s)'%(expr.i+1, expr.j+1) def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 h = x[1] step = x[2] lstr = self._print(l) hstr = 'end' if h == lim else self._print(h) if step == 1: if l == 1 and h == lim: return ':' if l == h: return lstr else: return lstr + ':' + hstr else: return ':'.join((lstr, self._print(step), hstr)) return (self._print(expr.parent) + '(' + strslice(expr.rowslice, expr.parent.shape[0]) + ', ' + strslice(expr.colslice, expr.parent.shape[1]) + ')') def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Identity(self, expr): return "eye(%s)" % self._print(expr.shape[0]) def _print_uppergamma(self, expr): return "gammainc(%s, %s, 'upper')" % (self._print(expr.args[1]), self._print(expr.args[0])) def _print_lowergamma(self, expr): return "gammainc(%s, %s, 'lower')" % (self._print(expr.args[1]), self._print(expr.args[0])) def _print_sinc(self, expr): return "sinc(%s)" % self._print(expr.args[0]/S.Pi) def _print_hankel1(self, expr): return "besselh(%s, 1, %s)" % (self._print(expr.order), self._print(expr.argument)) def _print_hankel2(self, expr): return "besselh(%s, 2, %s)" % (self._print(expr.order), self._print(expr.argument)) def _print_jn(self, expr): from sympy.functions import sqrt, besselj x = expr.argument expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) return self._print(expr2) def _print_yn(self, expr): from sympy.functions import sqrt, bessely x = expr.argument expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) return self._print(expr2) def _print_airyai(self, expr): return "airy(0, %s)" % self._print(expr.args[0]) def _print_airyaiprime(self, expr): return "airy(1, %s)" % self._print(expr.args[0]) def _print_airybi(self, expr): return "airy(2, %s)" % self._print(expr.args[0]) def _print_airybiprime(self, expr): return "airy(3, %s)" % self._print(expr.args[0]) def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if self._settings["inline"]: # Express each (cond, expr) pair in a nested Horner form: # (condition) .* (expr) + (not cond) .* (<others>) # Expressions that result in multiple statements won't work here. ecpairs = ["({0}).*({1}) + (~({0})).*(".format (self._print(c), self._print(e)) for e, c in expr.args[:-1]] elast = "%s" % self._print(expr.args[-1].expr) pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs) return "(" + pw + ")" else: for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s)" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("elseif (%s)" % self._print(c)) code0 = self._print(e) lines.append(code0) if i == len(expr.args) - 1: lines.append("end") return "\n".join(lines) def indent_code(self, code): if isinstance(code, string_types): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') dec_regex = ('^end$', '^elseif ', '^else$') code = [ line.lstrip(' \t') for line in code ] increase = [ int(any([search(re, line) for re in inc_regex])) for line in code ] decrease = [ int(any([search(re, line) for re in dec_regex])) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line == '' or line == '\n': pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def octave_code(expr, assign_to=None, **settings): return OctaveCodePrinter(settings).doprint(expr, assign_to) def print_octave_code(expr, **settings): print(octave_code(expr, **settings))
true
true
f72c79f3f9a9af03ac560d30164899d30e36c861
692
py
Python
src/examples/animations/AnimationGif.py
Gabvaztor/tensorflowCode
e206ea4544552b87c2d43274cea3182f6b385a87
[ "Apache-2.0" ]
4
2019-12-14T08:06:18.000Z
2020-09-12T10:09:31.000Z
src/examples/animations/AnimationGif.py
Gabvaztor/tensorflowCode
e206ea4544552b87c2d43274cea3182f6b385a87
[ "Apache-2.0" ]
null
null
null
src/examples/animations/AnimationGif.py
Gabvaztor/tensorflowCode
e206ea4544552b87c2d43274cea3182f6b385a87
[ "Apache-2.0" ]
2
2020-09-12T10:10:07.000Z
2021-09-15T11:58:37.000Z
#IMPORTAMOS LIBRERIAS. import numpy as np import matplotlib.pyplot as plt import animatplot as amp #INTRODUCIMOS DATOS. x = np.linspace(0, 1, 50) t = np.linspace(0, 1, 20) X, T = np.meshgrid(x, t) Y = np.zeros(int(51*(X+T))) #CREAMOS OBJETO "timeline". timeline = amp.Timeline(t, units='s', fps=60) #GENERAMOS ANIMACIÓN. block = amp.blocks.Line(X, Y, marker=".", linestyle="-", color="r") anim = amp.Animation([block],timeline) #DEFINICIÓN DE ETIQUETAS PARA TITULO Y EJES. plt.title("Sine Wave") plt.xlabel("x") plt.ylabel("y") #GUARDAMOS ANIMACIÓN. #anim.save_gif('graph_anim.gif') #INTRODUCIMOS LÍNEA DE TIEMPO #Y BOTÓN PAUSE/PLAY anim.controls() #REPRESENTAMOS GRÁFICA. plt.show()
20.352941
67
0.710983
import numpy as np import matplotlib.pyplot as plt import animatplot as amp x = np.linspace(0, 1, 50) t = np.linspace(0, 1, 20) X, T = np.meshgrid(x, t) Y = np.zeros(int(51*(X+T))) timeline = amp.Timeline(t, units='s', fps=60) block = amp.blocks.Line(X, Y, marker=".", linestyle="-", color="r") anim = amp.Animation([block],timeline) plt.title("Sine Wave") plt.xlabel("x") plt.ylabel("y") anim.controls() plt.show()
true
true
f72c7b00779b23f24e5f6b86d0f4c382d11780f4
4,931
py
Python
sdks/python/apache_beam/runners/worker/log_handler.py
dxichen/beam
d02b859cb37e3c9f565785e93384905f1078b409
[ "Apache-2.0", "BSD-3-Clause" ]
2
2018-12-08T05:19:04.000Z
2018-12-08T05:19:07.000Z
sdks/python/apache_beam/runners/worker/log_handler.py
dxichen/beam
d02b859cb37e3c9f565785e93384905f1078b409
[ "Apache-2.0", "BSD-3-Clause" ]
10
2016-03-21T22:50:43.000Z
2016-07-12T16:59:21.000Z
sdks/python/apache_beam/runners/worker/log_handler.py
swegner/incubator-beam
5466ac0b8819625b1d0ada3577c1fc103797f9a2
[ "Apache-2.0", "BSD-3-Clause" ]
1
2018-11-23T11:49:03.000Z
2018-11-23T11:49:03.000Z
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Beam fn API log handler.""" from __future__ import absolute_import from __future__ import print_function import logging import math import queue import sys import threading from builtins import range import grpc from apache_beam.portability.api import beam_fn_api_pb2 from apache_beam.portability.api import beam_fn_api_pb2_grpc from apache_beam.runners.worker.worker_id_interceptor import WorkerIdInterceptor # This module is experimental. No backwards-compatibility guarantees. class FnApiLogRecordHandler(logging.Handler): """A handler that writes log records to the fn API.""" # Maximum number of log entries in a single stream request. _MAX_BATCH_SIZE = 1000 # Used to indicate the end of stream. _FINISHED = object() # Size of the queue used to buffer messages. Once full, messages will be # dropped. If the average log size is 1KB this may use up to 10MB of memory. _QUEUE_SIZE = 10000 # Mapping from logging levels to LogEntry levels. LOG_LEVEL_MAP = { logging.FATAL: beam_fn_api_pb2.LogEntry.Severity.CRITICAL, logging.ERROR: beam_fn_api_pb2.LogEntry.Severity.ERROR, logging.WARNING: beam_fn_api_pb2.LogEntry.Severity.WARN, logging.INFO: beam_fn_api_pb2.LogEntry.Severity.INFO, logging.DEBUG: beam_fn_api_pb2.LogEntry.Severity.DEBUG } def __init__(self, log_service_descriptor): super(FnApiLogRecordHandler, self).__init__() self._dropped_logs = 0 self._log_entry_queue = queue.Queue(maxsize=self._QUEUE_SIZE) ch = grpc.insecure_channel(log_service_descriptor.url) # Make sure the channel is ready to avoid [BEAM-4649] grpc.channel_ready_future(ch).result(timeout=60) self._log_channel = grpc.intercept_channel(ch, WorkerIdInterceptor()) self._logging_stub = beam_fn_api_pb2_grpc.BeamFnLoggingStub( self._log_channel) self._reader = threading.Thread( target=lambda: self._read_log_control_messages(), name='read_log_control_messages') self._reader.daemon = True self._reader.start() def connect(self): return self._logging_stub.Logging(self._write_log_entries()) def emit(self, record): log_entry = beam_fn_api_pb2.LogEntry() log_entry.severity = self.LOG_LEVEL_MAP[record.levelno] log_entry.message = self.format(record) log_entry.thread = record.threadName log_entry.log_location = record.module + '.' + record.funcName (fraction, seconds) = math.modf(record.created) nanoseconds = 1e9 * fraction log_entry.timestamp.seconds = int(seconds) log_entry.timestamp.nanos = int(nanoseconds) try: self._log_entry_queue.put(log_entry, block=False) except queue.Full: self._dropped_logs += 1 def close(self): """Flush out all existing log entries and unregister this handler.""" # Acquiring the handler lock ensures ``emit`` is not run until the lock is # released. self.acquire() self._log_entry_queue.put(self._FINISHED, timeout=5) # wait on server to close. self._reader.join() self.release() # Unregister this handler. super(FnApiLogRecordHandler, self).close() def _write_log_entries(self): done = False while not done: log_entries = [self._log_entry_queue.get()] try: for _ in range(self._MAX_BATCH_SIZE): log_entries.append(self._log_entry_queue.get_nowait()) except queue.Empty: pass if log_entries[-1] is self._FINISHED: done = True log_entries.pop() if log_entries: yield beam_fn_api_pb2.LogEntry.List(log_entries=log_entries) def _read_log_control_messages(self): while True: log_control_iterator = self.connect() if self._dropped_logs > 0: logging.warn("Dropped %d logs while logging client disconnected", self._dropped_logs) self._dropped_logs = 0 try: for _ in log_control_iterator: # TODO(vikasrk): Handle control messages. pass # iterator is closed return except Exception as ex: print("Logging client failed: {}... resetting".format(ex), file=sys.stderr)
35.47482
80
0.724599
from __future__ import absolute_import from __future__ import print_function import logging import math import queue import sys import threading from builtins import range import grpc from apache_beam.portability.api import beam_fn_api_pb2 from apache_beam.portability.api import beam_fn_api_pb2_grpc from apache_beam.runners.worker.worker_id_interceptor import WorkerIdInterceptor class FnApiLogRecordHandler(logging.Handler): _MAX_BATCH_SIZE = 1000 _FINISHED = object() _QUEUE_SIZE = 10000 LOG_LEVEL_MAP = { logging.FATAL: beam_fn_api_pb2.LogEntry.Severity.CRITICAL, logging.ERROR: beam_fn_api_pb2.LogEntry.Severity.ERROR, logging.WARNING: beam_fn_api_pb2.LogEntry.Severity.WARN, logging.INFO: beam_fn_api_pb2.LogEntry.Severity.INFO, logging.DEBUG: beam_fn_api_pb2.LogEntry.Severity.DEBUG } def __init__(self, log_service_descriptor): super(FnApiLogRecordHandler, self).__init__() self._dropped_logs = 0 self._log_entry_queue = queue.Queue(maxsize=self._QUEUE_SIZE) ch = grpc.insecure_channel(log_service_descriptor.url) grpc.channel_ready_future(ch).result(timeout=60) self._log_channel = grpc.intercept_channel(ch, WorkerIdInterceptor()) self._logging_stub = beam_fn_api_pb2_grpc.BeamFnLoggingStub( self._log_channel) self._reader = threading.Thread( target=lambda: self._read_log_control_messages(), name='read_log_control_messages') self._reader.daemon = True self._reader.start() def connect(self): return self._logging_stub.Logging(self._write_log_entries()) def emit(self, record): log_entry = beam_fn_api_pb2.LogEntry() log_entry.severity = self.LOG_LEVEL_MAP[record.levelno] log_entry.message = self.format(record) log_entry.thread = record.threadName log_entry.log_location = record.module + '.' + record.funcName (fraction, seconds) = math.modf(record.created) nanoseconds = 1e9 * fraction log_entry.timestamp.seconds = int(seconds) log_entry.timestamp.nanos = int(nanoseconds) try: self._log_entry_queue.put(log_entry, block=False) except queue.Full: self._dropped_logs += 1 def close(self): self.acquire() self._log_entry_queue.put(self._FINISHED, timeout=5) self._reader.join() self.release() super(FnApiLogRecordHandler, self).close() def _write_log_entries(self): done = False while not done: log_entries = [self._log_entry_queue.get()] try: for _ in range(self._MAX_BATCH_SIZE): log_entries.append(self._log_entry_queue.get_nowait()) except queue.Empty: pass if log_entries[-1] is self._FINISHED: done = True log_entries.pop() if log_entries: yield beam_fn_api_pb2.LogEntry.List(log_entries=log_entries) def _read_log_control_messages(self): while True: log_control_iterator = self.connect() if self._dropped_logs > 0: logging.warn("Dropped %d logs while logging client disconnected", self._dropped_logs) self._dropped_logs = 0 try: for _ in log_control_iterator: pass return except Exception as ex: print("Logging client failed: {}... resetting".format(ex), file=sys.stderr)
true
true
f72c7be318686bd9cb0fbc1cd36a0d2e3f43d059
823
py
Python
time_extract.py
jianantian/entity_recognizer
bcd02c4f46ec290a7710f7cefef66e17dc97a020
[ "MIT" ]
null
null
null
time_extract.py
jianantian/entity_recognizer
bcd02c4f46ec290a7710f7cefef66e17dc97a020
[ "MIT" ]
2
2018-07-02T06:18:32.000Z
2020-07-08T03:15:53.000Z
time_extract.py
jianantian/entity_recognizer
bcd02c4f46ec290a7710f7cefef66e17dc97a020
[ "MIT" ]
null
null
null
def find_exact_time(text): """从文本中发现确切表述的时间, 如2012-09-03 2014-07- 2014-07 2015年08月下旬 2015年08月 2015年9月17日, 并不提取表示时间段的词语, 如三月前等""" import re #匹配具体时间点, 如2012-09-03, 2014-07-, 2014-07, 2015年08月下旬, 2015年08月, 2015年9月17日, 03年, 2009年 time_re_1 = r'\d{2,4}[-年](?:\d{1,2})?[-月]?(?:\d{1,2})?(?:日|号|下旬|上旬|上旬|初|末|中)?(?![前后内余])' #匹配以病历时间为基准的时间段: 病程 14月余, 病史 30余年, 半个月前, 1个月前, 20年前, 病程一年半 #这里的时间可能并不全是以病历时间为基准, 如手术后6日 #可能需要分一分类 time_re_2 = r'(?:病(?:史|程))?(?<![\d年月周日-])(?:[1-9]\d?|[一二两三四五六七八九十半])(?:十)?[余多几]?[个]?[年月周日天](?![-期年月周日\d])[前余内]?' #匹配以病历时间为基准的时间段, 但不是用数字表示: 今, 当日 time_re_3 = r'[前今昨明次同本去当上][天日月周年]?' #匹配以该文字之前最近的时间点为基准的时间段: 3天后 tmie_re_4 = r'(?:(?:[1-9]\d?|[一二两三四五六七八九十半])(?:十)?[余多几]?[个]?[天日月周年])后' return re.finditer(time_re, text) def
39.190476
117
0.579587
def find_exact_time(text): """从文本中发现确切表述的时间, 如2012-09-03 2014-07- 2014-07 2015年08月下旬 2015年08月 2015年9月17日, 并不提取表示时间段的词语, 如三月前等""" import re time_re_1 = r'\d{2,4}[-年](?:\d{1,2})?[-月]?(?:\d{1,2})?(?:日|号|下旬|上旬|上旬|初|末|中)?(?![前后内余])' time_re_2 = r'(?:病(?:史|程))?(?<![\d年月周日-])(?:[1-9]\d?|[一二两三四五六七八九十半])(?:十)?[余多几]?[个]?[年月周日天](?![-期年月周日\d])[前余内]?' time_re_3 = r'[前今昨明次同本去当上][天日月周年]?' tmie_re_4 = r'(?:(?:[1-9]\d?|[一二两三四五六七八九十半])(?:十)?[余多几]?[个]?[天日月周年])后' return re.finditer(time_re, text) def
false
true
f72c7bed0beea334637a18a2edf4a3137820bc39
6,213
py
Python
sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_percentile_source_target_operations.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_percentile_source_target_operations.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
226
2019-07-24T07:57:21.000Z
2019-10-15T01:07:24.000Z
sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_percentile_source_target_operations.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
2
2020-05-21T22:51:22.000Z
2020-05-26T20:53:01.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class PercentileSourceTargetOperations(object): """PercentileSourceTargetOperations operations. You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: The API version to use for this operation. Constant value: "2020-03-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2020-03-01" self.config = config def list_metrics( self, resource_group_name, account_name, source_region, target_region, filter, custom_headers=None, raw=False, **operation_config): """Retrieves the metrics determined by the given filter for the given account, source and target region. This url is only for PBS and Replication Latency data. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param source_region: Source region from which data is written. Cosmos DB region, with spaces between words and each word capitalized. :type source_region: str :param target_region: Target region to which data is written. Cosmos DB region, with spaces between words and each word capitalized. :type target_region: str :param filter: An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq. :type filter: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of PercentileMetric :rtype: ~azure.mgmt.cosmosdb.models.PercentileMetricPaged[~azure.mgmt.cosmosdb.models.PercentileMetric] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def prepare_request(next_link=None): if not next_link: # Construct URL url = self.list_metrics.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'sourceRegion': self._serialize.url("source_region", source_region, 'str'), 'targetRegion': self._serialize.url("target_region", target_region, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1) query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) return request def internal_paging(next_link=None): request = prepare_request(next_link) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response header_dict = None if raw: header_dict = {} deserialized = models.PercentileMetricPaged(internal_paging, self._deserialize.dependencies, header_dict) return deserialized list_metrics.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sourceRegion/{sourceRegion}/targetRegion/{targetRegion}/percentile/metrics'}
47.792308
242
0.652503
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class PercentileSourceTargetOperations(object): models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2020-03-01" self.config = config def list_metrics( self, resource_group_name, account_name, source_region, target_region, filter, custom_headers=None, raw=False, **operation_config): def prepare_request(next_link=None): if not next_link: url = self.list_metrics.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'sourceRegion': self._serialize.url("source_region", source_region, 'str'), 'targetRegion': self._serialize.url("target_region", target_region, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1) query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') else: url = next_link query_parameters = {} header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters, header_parameters) return request def internal_paging(next_link=None): request = prepare_request(next_link) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response header_dict = None if raw: header_dict = {} deserialized = models.PercentileMetricPaged(internal_paging, self._deserialize.dependencies, header_dict) return deserialized list_metrics.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sourceRegion/{sourceRegion}/targetRegion/{targetRegion}/percentile/metrics'}
true
true
f72c7c71e236df55dac3c772bf1accd371c155c5
586
py
Python
python/sdssdb/__init__.py
albireox/sdssdb
02d165d3a4347e8241aacdbdca0cec86058c8d29
[ "BSD-3-Clause" ]
6
2019-04-10T21:28:44.000Z
2021-03-01T18:39:55.000Z
python/sdssdb/__init__.py
albireox/sdssdb
02d165d3a4347e8241aacdbdca0cec86058c8d29
[ "BSD-3-Clause" ]
44
2018-10-31T17:48:20.000Z
2022-01-27T20:52:26.000Z
python/sdssdb/__init__.py
albireox/sdssdb
02d165d3a4347e8241aacdbdca0cec86058c8d29
[ "BSD-3-Clause" ]
2
2021-07-13T17:09:43.000Z
2021-07-13T19:33:18.000Z
# encoding: utf-8 import warnings from sdsstools import get_config, get_logger, get_package_version warnings.filterwarnings( 'ignore', '.*Skipped unsupported reflection of expression-based index .*q3c.*') NAME = 'sdssdb' __version__ = get_package_version(path=__file__, package_name=NAME) log = get_logger(NAME) # This looks for user configuration in the usual places (including # ~/.config/sdss/sdssdb.yml and ~/.sdssdb/sdssdb.yml). config = get_config(NAME) from .connection import PeeweeDatabaseConnection # noqa from .connection import SQLADatabaseConnection # noqa
24.416667
83
0.776451
import warnings from sdsstools import get_config, get_logger, get_package_version warnings.filterwarnings( 'ignore', '.*Skipped unsupported reflection of expression-based index .*q3c.*') NAME = 'sdssdb' __version__ = get_package_version(path=__file__, package_name=NAME) log = get_logger(NAME) config = get_config(NAME) from .connection import PeeweeDatabaseConnection from .connection import SQLADatabaseConnection
true
true
f72c7c8922dfe217f75499b4645d20bbcc563d6b
768
py
Python
saltapi/loader.py
techdragon/salt-api
e1ea6dd89bca61a7b8e885efcbc818faea33ea51
[ "Apache-2.0" ]
1
2019-06-27T13:05:14.000Z
2019-06-27T13:05:14.000Z
saltapi/loader.py
techdragon/salt-api
e1ea6dd89bca61a7b8e885efcbc818faea33ea51
[ "Apache-2.0" ]
null
null
null
saltapi/loader.py
techdragon/salt-api
e1ea6dd89bca61a7b8e885efcbc818faea33ea51
[ "Apache-2.0" ]
null
null
null
''' The salt api module loader interface ''' # Import python libs import os # Import Salt libs import salt.loader import saltapi def netapi(opts): ''' Return the network api functions ''' load = salt.loader._create_loader( opts, 'netapi', 'netapi', base_path=os.path.dirname(saltapi.__file__) ) return load.gen_functions() def runner(opts): ''' Load the runners, this function bypasses the issue with the altered basepath ''' load = salt.loader._create_loader( opts, 'runners', 'runner', ext_type_dirs='runner_dirs', base_path=os.path.dirname(salt.__file__) ) return load.gen_functions()
20.756757
71
0.580729
import os import salt.loader import saltapi def netapi(opts): load = salt.loader._create_loader( opts, 'netapi', 'netapi', base_path=os.path.dirname(saltapi.__file__) ) return load.gen_functions() def runner(opts): load = salt.loader._create_loader( opts, 'runners', 'runner', ext_type_dirs='runner_dirs', base_path=os.path.dirname(salt.__file__) ) return load.gen_functions()
true
true
f72c7ca68f363a382646aaf1c7a8b8116abf92d5
51,548
py
Python
Lib/test/test_compile.py
emontnemery/cpython
99fcf1505218464c489d419d4500f126b6d6dc28
[ "0BSD" ]
18
2017-09-21T18:22:31.000Z
2022-02-22T19:40:01.000Z
Lib/test/test_compile.py
emontnemery/cpython
99fcf1505218464c489d419d4500f126b6d6dc28
[ "0BSD" ]
25
2020-04-16T17:21:30.000Z
2022-03-01T05:00:45.000Z
Lib/test/test_compile.py
emontnemery/cpython
99fcf1505218464c489d419d4500f126b6d6dc28
[ "0BSD" ]
8
2018-08-31T07:49:21.000Z
2020-11-21T21:31:48.000Z
import dis import math import os import unittest import sys import ast import _ast import tempfile import types import textwrap from test import support from test.support import script_helper, requires_debug_ranges from test.support.os_helper import FakePath class TestSpecifics(unittest.TestCase): def compile_single(self, source): compile(source, "<single>", "single") def assertInvalidSingle(self, source): self.assertRaises(SyntaxError, self.compile_single, source) def test_no_ending_newline(self): compile("hi", "<test>", "exec") compile("hi\r", "<test>", "exec") def test_empty(self): compile("", "<test>", "exec") def test_other_newlines(self): compile("\r\n", "<test>", "exec") compile("\r", "<test>", "exec") compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec") compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec") def test_debug_assignment(self): # catch assignments to __debug__ self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single') import builtins prev = builtins.__debug__ setattr(builtins, '__debug__', 'sure') self.assertEqual(__debug__, prev) setattr(builtins, '__debug__', prev) def test_argument_handling(self): # detect duplicate positional and keyword arguments self.assertRaises(SyntaxError, eval, 'lambda a,a:0') self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0') self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0') self.assertRaises(SyntaxError, exec, 'def f(a, a): pass') self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass') self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1') def test_syntax_error(self): self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec") def test_none_keyword_arg(self): self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec") def test_duplicate_global_local(self): self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1') def test_exec_with_general_mapping_for_locals(self): class M: "Test mapping interface versus possible calls from eval()." def __getitem__(self, key): if key == 'a': return 12 raise KeyError def __setitem__(self, key, value): self.results = (key, value) def keys(self): return list('xyz') m = M() g = globals() exec('z = a', g, m) self.assertEqual(m.results, ('z', 12)) try: exec('z = b', g, m) except NameError: pass else: self.fail('Did not detect a KeyError') exec('z = dir()', g, m) self.assertEqual(m.results, ('z', list('xyz'))) exec('z = globals()', g, m) self.assertEqual(m.results, ('z', g)) exec('z = locals()', g, m) self.assertEqual(m.results, ('z', m)) self.assertRaises(TypeError, exec, 'z = b', m) class A: "Non-mapping" pass m = A() self.assertRaises(TypeError, exec, 'z = a', g, m) # Verify that dict subclasses work as well class D(dict): def __getitem__(self, key): if key == 'a': return 12 return dict.__getitem__(self, key) d = D() exec('z = a', g, d) self.assertEqual(d['z'], 12) def test_extended_arg(self): longexpr = 'x = x or ' + '-x' * 2500 g = {} code = ''' def f(x): %s %s %s %s %s %s %s %s %s %s # the expressions above have no effect, x == argument while x: x -= 1 # EXTENDED_ARG/JUMP_ABSOLUTE here return x ''' % ((longexpr,)*10) exec(code, g) self.assertEqual(g['f'](5), 0) def test_argument_order(self): self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass') def test_float_literals(self): # testing bad float literals self.assertRaises(SyntaxError, eval, "2e") self.assertRaises(SyntaxError, eval, "2.0e+") self.assertRaises(SyntaxError, eval, "1e-") self.assertRaises(SyntaxError, eval, "3-4e/21") def test_indentation(self): # testing compile() of indented block w/o trailing newline" s = """ if 1: if 2: pass""" compile(s, "<string>", "exec") # This test is probably specific to CPython and may not generalize # to other implementations. We are trying to ensure that when # the first line of code starts after 256, correct line numbers # in tracebacks are still produced. def test_leading_newlines(self): s256 = "".join(["\n"] * 256 + ["spam"]) co = compile(s256, 'fn', 'exec') self.assertEqual(co.co_firstlineno, 1) self.assertEqual(list(co.co_lines()), [(0, 8, 257)]) def test_literals_with_leading_zeroes(self): for arg in ["077787", "0xj", "0x.", "0e", "090000000000000", "080000000000000", "000000000000009", "000000000000008", "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2", "0b101j", "0o153j", "0b100e1", "0o777e1", "0777", "000777", "000000000000007"]: self.assertRaises(SyntaxError, eval, arg) self.assertEqual(eval("0xff"), 255) self.assertEqual(eval("0777."), 777) self.assertEqual(eval("0777.0"), 777) self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777) self.assertEqual(eval("0777e1"), 7770) self.assertEqual(eval("0e0"), 0) self.assertEqual(eval("0000e-012"), 0) self.assertEqual(eval("09.5"), 9.5) self.assertEqual(eval("0777j"), 777j) self.assertEqual(eval("000"), 0) self.assertEqual(eval("00j"), 0j) self.assertEqual(eval("00.0"), 0) self.assertEqual(eval("0e3"), 0) self.assertEqual(eval("090000000000000."), 90000000000000.) self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.) self.assertEqual(eval("090000000000000e0"), 90000000000000.) self.assertEqual(eval("090000000000000e-0"), 90000000000000.) self.assertEqual(eval("090000000000000j"), 90000000000000j) self.assertEqual(eval("000000000000008."), 8.) self.assertEqual(eval("000000000000009."), 9.) self.assertEqual(eval("0b101010"), 42) self.assertEqual(eval("-0b000000000010"), -2) self.assertEqual(eval("0o777"), 511) self.assertEqual(eval("-0o0000010"), -8) def test_unary_minus(self): # Verify treatment of unary minus on negative numbers SF bug #660455 if sys.maxsize == 2147483647: # 32-bit machine all_one_bits = '0xffffffff' self.assertEqual(eval(all_one_bits), 4294967295) self.assertEqual(eval("-" + all_one_bits), -4294967295) elif sys.maxsize == 9223372036854775807: # 64-bit machine all_one_bits = '0xffffffffffffffff' self.assertEqual(eval(all_one_bits), 18446744073709551615) self.assertEqual(eval("-" + all_one_bits), -18446744073709551615) else: self.fail("How many bits *does* this machine have???") # Verify treatment of constant folding on -(sys.maxsize+1) # i.e. -2147483648 on 32 bit platforms. Should return int. self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int) self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int) if sys.maxsize == 9223372036854775807: def test_32_63_bit_values(self): a = +4294967296 # 1 << 32 b = -4294967296 # 1 << 32 c = +281474976710656 # 1 << 48 d = -281474976710656 # 1 << 48 e = +4611686018427387904 # 1 << 62 f = -4611686018427387904 # 1 << 62 g = +9223372036854775807 # 1 << 63 - 1 h = -9223372036854775807 # 1 << 63 - 1 for variable in self.test_32_63_bit_values.__code__.co_consts: if variable is not None: self.assertIsInstance(variable, int) def test_sequence_unpacking_error(self): # Verify sequence packing/unpacking with "or". SF bug #757818 i,j = (1, -1) or (-1, 1) self.assertEqual(i, 1) self.assertEqual(j, -1) def test_none_assignment(self): stmts = [ 'None = 0', 'None += 0', '__builtins__.None = 0', 'def None(): pass', 'class None: pass', '(a, None) = 0, 0', 'for None in range(10): pass', 'def f(None): pass', 'import None', 'import x as None', 'from x import None', 'from x import y as None' ] for stmt in stmts: stmt += "\n" self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single') self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec') def test_import(self): succeed = [ 'import sys', 'import os, sys', 'import os as bar', 'import os.path as bar', 'from __future__ import nested_scopes, generators', 'from __future__ import (nested_scopes,\ngenerators)', 'from __future__ import (nested_scopes,\ngenerators,)', 'from sys import stdin, stderr, stdout', 'from sys import (stdin, stderr,\nstdout)', 'from sys import (stdin, stderr,\nstdout,)', 'from sys import (stdin\n, stderr, stdout)', 'from sys import (stdin\n, stderr, stdout,)', 'from sys import stdin as si, stdout as so, stderr as se', 'from sys import (stdin as si, stdout as so, stderr as se)', 'from sys import (stdin as si, stdout as so, stderr as se,)', ] fail = [ 'import (os, sys)', 'import (os), (sys)', 'import ((os), (sys))', 'import (sys', 'import sys)', 'import (os,)', 'import os As bar', 'import os.path a bar', 'from sys import stdin As stdout', 'from sys import stdin a stdout', 'from (sys) import stdin', 'from __future__ import (nested_scopes', 'from __future__ import nested_scopes)', 'from __future__ import nested_scopes,\ngenerators', 'from sys import (stdin', 'from sys import stdin)', 'from sys import stdin, stdout,\nstderr', 'from sys import stdin si', 'from sys import stdin,', 'from sys import (*)', 'from sys import (stdin,, stdout, stderr)', 'from sys import (stdin, stdout),', ] for stmt in succeed: compile(stmt, 'tmp', 'exec') for stmt in fail: self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec') def test_for_distinct_code_objects(self): # SF bug 1048870 def f(): f1 = lambda x=1: x f2 = lambda x=2: x return f1, f2 f1, f2 = f() self.assertNotEqual(id(f1.__code__), id(f2.__code__)) def test_lambda_doc(self): l = lambda: "foo" self.assertIsNone(l.__doc__) def test_encoding(self): code = b'# -*- coding: badencoding -*-\npass\n' self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec') code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n' compile(code, 'tmp', 'exec') self.assertEqual(eval(code), '\xc2\xa4') code = '"\xc2\xa4"\n' self.assertEqual(eval(code), '\xc2\xa4') code = b'"\xc2\xa4"\n' self.assertEqual(eval(code), '\xa4') code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n' self.assertEqual(eval(code), '\xc2\xa4') code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n' self.assertEqual(eval(code), '\xa4') code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n' self.assertEqual(eval(code), '\xc2\u20ac') code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n' self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4') code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n' self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4') def test_subscripts(self): # SF bug 1448804 # Class to make testing subscript results easy class str_map(object): def __init__(self): self.data = {} def __getitem__(self, key): return self.data[str(key)] def __setitem__(self, key, value): self.data[str(key)] = value def __delitem__(self, key): del self.data[str(key)] def __contains__(self, key): return str(key) in self.data d = str_map() # Index d[1] = 1 self.assertEqual(d[1], 1) d[1] += 1 self.assertEqual(d[1], 2) del d[1] self.assertNotIn(1, d) # Tuple of indices d[1, 1] = 1 self.assertEqual(d[1, 1], 1) d[1, 1] += 1 self.assertEqual(d[1, 1], 2) del d[1, 1] self.assertNotIn((1, 1), d) # Simple slice d[1:2] = 1 self.assertEqual(d[1:2], 1) d[1:2] += 1 self.assertEqual(d[1:2], 2) del d[1:2] self.assertNotIn(slice(1, 2), d) # Tuple of simple slices d[1:2, 1:2] = 1 self.assertEqual(d[1:2, 1:2], 1) d[1:2, 1:2] += 1 self.assertEqual(d[1:2, 1:2], 2) del d[1:2, 1:2] self.assertNotIn((slice(1, 2), slice(1, 2)), d) # Extended slice d[1:2:3] = 1 self.assertEqual(d[1:2:3], 1) d[1:2:3] += 1 self.assertEqual(d[1:2:3], 2) del d[1:2:3] self.assertNotIn(slice(1, 2, 3), d) # Tuple of extended slices d[1:2:3, 1:2:3] = 1 self.assertEqual(d[1:2:3, 1:2:3], 1) d[1:2:3, 1:2:3] += 1 self.assertEqual(d[1:2:3, 1:2:3], 2) del d[1:2:3, 1:2:3] self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d) # Ellipsis d[...] = 1 self.assertEqual(d[...], 1) d[...] += 1 self.assertEqual(d[...], 2) del d[...] self.assertNotIn(Ellipsis, d) # Tuple of Ellipses d[..., ...] = 1 self.assertEqual(d[..., ...], 1) d[..., ...] += 1 self.assertEqual(d[..., ...], 2) del d[..., ...] self.assertNotIn((Ellipsis, Ellipsis), d) def test_annotation_limit(self): # more than 255 annotations, should compile ok s = "def f(%s): pass" s %= ', '.join('a%d:%d' % (i,i) for i in range(300)) compile(s, '?', 'exec') def test_mangling(self): class A: def f(): __mangled = 1 __not_mangled__ = 2 import __mangled_mod import __package__.module self.assertIn("_A__mangled", A.f.__code__.co_varnames) self.assertIn("__not_mangled__", A.f.__code__.co_varnames) self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames) self.assertIn("__package__", A.f.__code__.co_varnames) def test_compile_ast(self): fname = __file__ if fname.lower().endswith('pyc'): fname = fname[:-1] with open(fname, encoding='utf-8') as f: fcontents = f.read() sample_code = [ ['<assign>', 'x = 5'], ['<ifblock>', """if True:\n pass\n"""], ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""], ['<deffunc>', """def foo():\n pass\nfoo()\n"""], [fname, fcontents], ] for fname, code in sample_code: co1 = compile(code, '%s1' % fname, 'exec') ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST) self.assertTrue(type(ast) == _ast.Module) co2 = compile(ast, '%s3' % fname, 'exec') self.assertEqual(co1, co2) # the code object's filename comes from the second compilation step self.assertEqual(co2.co_filename, '%s3' % fname) # raise exception when node type doesn't match with compile mode co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) self.assertRaises(TypeError, compile, co1, '<ast>', 'eval') # raise exception when node type is no start node self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec') # raise exception when node has invalid children ast = _ast.Module() ast.body = [_ast.BoolOp()] self.assertRaises(TypeError, compile, ast, '<ast>', 'exec') def test_dict_evaluation_order(self): i = 0 def f(): nonlocal i i += 1 return i d = {f(): f(), f(): f()} self.assertEqual(d, {1: 2, 3: 4}) def test_compile_filename(self): for filename in 'file.py', b'file.py': code = compile('pass', filename, 'exec') self.assertEqual(code.co_filename, 'file.py') for filename in bytearray(b'file.py'), memoryview(b'file.py'): with self.assertWarns(DeprecationWarning): code = compile('pass', filename, 'exec') self.assertEqual(code.co_filename, 'file.py') self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec') @support.cpython_only def test_same_filename_used(self): s = """def f(): pass\ndef g(): pass""" c = compile(s, "myfile", "exec") for obj in c.co_consts: if isinstance(obj, types.CodeType): self.assertIs(obj.co_filename, c.co_filename) def test_single_statement(self): self.compile_single("1 + 2") self.compile_single("\n1 + 2") self.compile_single("1 + 2\n") self.compile_single("1 + 2\n\n") self.compile_single("1 + 2\t\t\n") self.compile_single("1 + 2\t\t\n ") self.compile_single("1 + 2 # one plus two") self.compile_single("1; 2") self.compile_single("import sys; sys") self.compile_single("def f():\n pass") self.compile_single("while False:\n pass") self.compile_single("if x:\n f(x)") self.compile_single("if x:\n f(x)\nelse:\n g(x)") self.compile_single("class T:\n pass") def test_bad_single_statement(self): self.assertInvalidSingle('1\n2') self.assertInvalidSingle('def f(): pass') self.assertInvalidSingle('a = 13\nb = 187') self.assertInvalidSingle('del x\ndel y') self.assertInvalidSingle('f()\ng()') self.assertInvalidSingle('f()\n# blah\nblah()') self.assertInvalidSingle('f()\nxy # blah\nblah()') self.assertInvalidSingle('x = 5 # comment\nx = 6\n') def test_particularly_evil_undecodable(self): # Issue 24022 src = b'0000\x00\n00000000000\n\x00\n\x9e\n' with tempfile.TemporaryDirectory() as tmpd: fn = os.path.join(tmpd, "bad.py") with open(fn, "wb") as fp: fp.write(src) res = script_helper.run_python_until_end(fn)[0] self.assertIn(b"Non-UTF-8", res.err) def test_yet_more_evil_still_undecodable(self): # Issue #25388 src = b"#\x00\n#\xfd\n" with tempfile.TemporaryDirectory() as tmpd: fn = os.path.join(tmpd, "bad.py") with open(fn, "wb") as fp: fp.write(src) res = script_helper.run_python_until_end(fn)[0] self.assertIn(b"Non-UTF-8", res.err) @support.cpython_only def test_compiler_recursion_limit(self): # Expected limit is sys.getrecursionlimit() * the scaling factor # in symtable.c (currently 3) # We expect to fail *at* that limit, because we use up some of # the stack depth limit in the test suite code # So we check the expected limit and 75% of that # XXX (ncoghlan): duplicating the scaling factor here is a little # ugly. Perhaps it should be exposed somewhere... fail_depth = sys.getrecursionlimit() * 3 crash_depth = sys.getrecursionlimit() * 300 success_depth = int(fail_depth * 0.75) def check_limit(prefix, repeated, mode="single"): expect_ok = prefix + repeated * success_depth compile(expect_ok, '<test>', mode) for depth in (fail_depth, crash_depth): broken = prefix + repeated * depth details = "Compiling ({!r} + {!r} * {})".format( prefix, repeated, depth) with self.assertRaises(RecursionError, msg=details): compile(broken, '<test>', mode) check_limit("a", "()") check_limit("a", ".b") check_limit("a", "[0]") check_limit("a", "*a") # XXX Crashes in the parser. # check_limit("a", " if a else a") # check_limit("if a: pass", "\nelif a: pass", mode="exec") def test_null_terminated(self): # The source code is null-terminated internally, but bytes-like # objects are accepted, which could be not terminated. with self.assertRaisesRegex(ValueError, "cannot contain null"): compile("123\x00", "<dummy>", "eval") with self.assertRaisesRegex(ValueError, "cannot contain null"): compile(memoryview(b"123\x00"), "<dummy>", "eval") code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval") self.assertEqual(eval(code), 23) code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval") self.assertEqual(eval(code), 23) code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval") self.assertEqual(eval(code), 23) # Also test when eval() and exec() do the compilation step self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23) namespace = dict() exec(memoryview(b"ax = 123")[1:-1], namespace) self.assertEqual(namespace['x'], 12) def check_constant(self, func, expected): for const in func.__code__.co_consts: if repr(const) == repr(expected): break else: self.fail("unable to find constant %r in %r" % (expected, func.__code__.co_consts)) # Merging equal constants is not a strict requirement for the Python # semantics, it's a more an implementation detail. @support.cpython_only def test_merge_constants(self): # Issue #25843: compile() must merge constants which are equal # and have the same type. def check_same_constant(const): ns = {} code = "f1, f2 = lambda: %r, lambda: %r" % (const, const) exec(code, ns) f1 = ns['f1'] f2 = ns['f2'] self.assertIs(f1.__code__, f2.__code__) self.check_constant(f1, const) self.assertEqual(repr(f1()), repr(const)) check_same_constant(None) check_same_constant(0) check_same_constant(0.0) check_same_constant(b'abc') check_same_constant('abc') # Note: "lambda: ..." emits "LOAD_CONST Ellipsis", # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis" f1, f2 = lambda: ..., lambda: ... self.assertIs(f1.__code__, f2.__code__) self.check_constant(f1, Ellipsis) self.assertEqual(repr(f1()), repr(Ellipsis)) # Merge constants in tuple or frozenset f1, f2 = lambda: "not a name", lambda: ("not a name",) f3 = lambda x: x in {("not a name",)} self.assertIs(f1.__code__.co_consts[1], f2.__code__.co_consts[1][0]) self.assertIs(next(iter(f3.__code__.co_consts[1])), f2.__code__.co_consts[1]) # {0} is converted to a constant frozenset({0}) by the peephole # optimizer f1, f2 = lambda x: x in {0}, lambda x: x in {0} self.assertIs(f1.__code__, f2.__code__) self.check_constant(f1, frozenset({0})) self.assertTrue(f1(0)) # Merging equal co_linetable and co_code is not a strict requirement # for the Python semantics, it's a more an implementation detail. @support.cpython_only def test_merge_code_attrs(self): # See https://bugs.python.org/issue42217 f1 = lambda x: x.y.z f2 = lambda a: a.b.c self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable) self.assertIs(f1.__code__.co_code, f2.__code__.co_code) # Stripping unused constants is not a strict requirement for the # Python semantics, it's a more an implementation detail. @support.cpython_only def test_strip_unused_consts(self): # Python 3.10rc1 appended None to co_consts when None is not used # at all. See bpo-45056. def f1(): "docstring" return 42 self.assertEqual(f1.__code__.co_consts, ("docstring", 42)) # This is a regression test for a CPython specific peephole optimizer # implementation bug present in a few releases. It's assertion verifies # that peephole optimization was actually done though that isn't an # indication of the bugs presence or not (crashing is). @support.cpython_only def test_peephole_opt_unreachable_code_array_access_in_bounds(self): """Regression test for issue35193 when run under clang msan.""" def unused_code_at_end(): return 3 raise RuntimeError("unreachable") # The above function definition will trigger the out of bounds # bug in the peephole optimizer as it scans opcodes past the # RETURN_VALUE opcode. This does not always crash an interpreter. # When you build with the clang memory sanitizer it reliably aborts. self.assertEqual( 'RETURN_VALUE', list(dis.get_instructions(unused_code_at_end))[-1].opname) def test_dont_merge_constants(self): # Issue #25843: compile() must not merge constants which are equal # but have a different type. def check_different_constants(const1, const2): ns = {} exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns) f1 = ns['f1'] f2 = ns['f2'] self.assertIsNot(f1.__code__, f2.__code__) self.assertNotEqual(f1.__code__, f2.__code__) self.check_constant(f1, const1) self.check_constant(f2, const2) self.assertEqual(repr(f1()), repr(const1)) self.assertEqual(repr(f2()), repr(const2)) check_different_constants(0, 0.0) check_different_constants(+0.0, -0.0) check_different_constants((0,), (0.0,)) check_different_constants('a', b'a') check_different_constants(('a',), (b'a',)) # check_different_constants() cannot be used because repr(-0j) is # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign. f1, f2 = lambda: +0.0j, lambda: -0.0j self.assertIsNot(f1.__code__, f2.__code__) self.check_constant(f1, +0.0j) self.check_constant(f2, -0.0j) self.assertEqual(repr(f1()), repr(+0.0j)) self.assertEqual(repr(f2()), repr(-0.0j)) # {0} is converted to a constant frozenset({0}) by the peephole # optimizer f1, f2 = lambda x: x in {0}, lambda x: x in {0.0} self.assertIsNot(f1.__code__, f2.__code__) self.check_constant(f1, frozenset({0})) self.check_constant(f2, frozenset({0.0})) self.assertTrue(f1(0)) self.assertTrue(f2(0.0)) def test_path_like_objects(self): # An implicit test for PyUnicode_FSDecoder(). compile("42", FakePath("test_compile_pathlike"), "single") def test_stack_overflow(self): # bpo-31113: Stack overflow when compile a long sequence of # complex statements. compile("if a: b\n" * 200000, "<dummy>", "exec") # Multiple users rely on the fact that CPython does not generate # bytecode for dead code blocks. See bpo-37500 for more context. @support.cpython_only def test_dead_blocks_do_not_generate_bytecode(self): def unused_block_if(): if 0: return 42 def unused_block_while(): while 0: return 42 def unused_block_if_else(): if 1: return None else: return 42 def unused_block_while_else(): while 1: return None else: return 42 funcs = [unused_block_if, unused_block_while, unused_block_if_else, unused_block_while_else] for func in funcs: opcodes = list(dis.get_instructions(func)) self.assertLessEqual(len(opcodes), 3) self.assertEqual('LOAD_CONST', opcodes[-2].opname) self.assertEqual(None, opcodes[-2].argval) self.assertEqual('RETURN_VALUE', opcodes[-1].opname) def test_false_while_loop(self): def break_in_while(): while False: break def continue_in_while(): while False: continue funcs = [break_in_while, continue_in_while] # Check that we did not raise but we also don't generate bytecode for func in funcs: opcodes = list(dis.get_instructions(func)) self.assertEqual(2, len(opcodes)) self.assertEqual('LOAD_CONST', opcodes[0].opname) self.assertEqual(None, opcodes[0].argval) self.assertEqual('RETURN_VALUE', opcodes[1].opname) def test_consts_in_conditionals(self): def and_true(x): return True and x def and_false(x): return False and x def or_true(x): return True or x def or_false(x): return False or x funcs = [and_true, and_false, or_true, or_false] # Check that condition is removed. for func in funcs: with self.subTest(func=func): opcodes = list(dis.get_instructions(func)) self.assertEqual(2, len(opcodes)) self.assertIn('LOAD_', opcodes[0].opname) self.assertEqual('RETURN_VALUE', opcodes[1].opname) def test_imported_load_method(self): sources = [ """\ import os def foo(): return os.uname() """, """\ import os as operating_system def foo(): return operating_system.uname() """, """\ from os import path def foo(x): return path.join(x) """, """\ from os import path as os_path def foo(x): return os_path.join(x) """ ] for source in sources: namespace = {} exec(textwrap.dedent(source), namespace) func = namespace['foo'] with self.subTest(func=func.__name__): opcodes = list(dis.get_instructions(func)) instructions = [opcode.opname for opcode in opcodes] self.assertNotIn('LOAD_METHOD', instructions) self.assertNotIn('CALL_METHOD', instructions) self.assertIn('LOAD_ATTR', instructions) self.assertIn('CALL_FUNCTION', instructions) def test_lineno_procedure_call(self): def call(): ( print() ) line1 = call.__code__.co_firstlineno + 1 assert line1 not in [line for (_, _, line) in call.__code__.co_lines()] def test_lineno_after_implicit_return(self): TRUE = True # Don't use constant True or False, as compiler will remove test def if1(x): x() if TRUE: pass def if2(x): x() if TRUE: pass else: pass def if3(x): x() if TRUE: pass else: return None def if4(x): x() if not TRUE: pass funcs = [ if1, if2, if3, if4] lastlines = [ 3, 3, 3, 2] frame = None def save_caller_frame(): nonlocal frame frame = sys._getframe(1) for func, lastline in zip(funcs, lastlines, strict=True): with self.subTest(func=func): func(save_caller_frame) self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline) def test_lineno_after_no_code(self): def no_code1(): "doc string" def no_code2(): a: int for func in (no_code1, no_code2): with self.subTest(func=func): code = func.__code__ lines = list(code.co_lines()) self.assertEqual(len(lines), 1) start, end, line = lines[0] self.assertEqual(start, 0) self.assertEqual(end, len(code.co_code)) self.assertEqual(line, code.co_firstlineno) def test_lineno_attribute(self): def load_attr(): return ( o. a ) load_attr_lines = [ 2, 3, 1 ] def load_method(): return ( o. m( 0 ) ) load_method_lines = [ 2, 3, 4, 3, 1 ] def store_attr(): ( o. a ) = ( v ) store_attr_lines = [ 5, 2, 3 ] def aug_store_attr(): ( o. a ) += ( v ) aug_store_attr_lines = [ 2, 3, 5, 1, 3 ] funcs = [ load_attr, load_method, store_attr, aug_store_attr] func_lines = [ load_attr_lines, load_method_lines, store_attr_lines, aug_store_attr_lines] for func, lines in zip(funcs, func_lines, strict=True): with self.subTest(func=func): code_lines = [ line-func.__code__.co_firstlineno for (_, _, line) in func.__code__.co_lines() ] self.assertEqual(lines, code_lines) def test_line_number_genexp(self): def return_genexp(): return (1 for x in y) genexp_lines = [None, 1, 3, 1] genexp_code = return_genexp.__code__.co_consts[1] code_lines = [ None if line is None else line-return_genexp.__code__.co_firstlineno for (_, _, line) in genexp_code.co_lines() ] self.assertEqual(genexp_lines, code_lines) def test_line_number_implicit_return_after_async_for(self): async def test(aseq): async for i in aseq: body expected_lines = [None, 1, 2, 1] code_lines = [ None if line is None else line-test.__code__.co_firstlineno for (_, _, line) in test.__code__.co_lines() ] self.assertEqual(expected_lines, code_lines) def test_big_dict_literal(self): # The compiler has a flushing point in "compiler_dict" that calls compiles # a portion of the dictionary literal when the loop that iterates over the items # reaches 0xFFFF elements but the code was not including the boundary element, # dropping the key at position 0xFFFF. See bpo-41531 for more information dict_size = 0xFFFF + 1 the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}" self.assertEqual(len(eval(the_dict)), dict_size) def test_redundant_jump_in_if_else_break(self): # Check if bytecode containing jumps that simply point to the next line # is generated around if-else-break style structures. See bpo-42615. def if_else_break(): val = 1 while True: if val > 0: val -= 1 else: break val = -1 INSTR_SIZE = 2 HANDLED_JUMPS = ( 'POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', ) for line, instr in enumerate(dis.Bytecode(if_else_break)): if instr.opname == 'JUMP_FORWARD': self.assertNotEqual(instr.arg, 0) elif instr.opname in HANDLED_JUMPS: self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE) @requires_debug_ranges() class TestSourcePositions(unittest.TestCase): # Ensure that compiled code snippets have correct line and column numbers # in `co_positions()`. def check_positions_against_ast(self, snippet): # Basic check that makes sure each line and column is at least present # in one of the AST nodes of the source code. code = compile(snippet, 'test_compile.py', 'exec') ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST) self.assertTrue(type(ast_tree) == _ast.Module) # Use an AST visitor that notes all the offsets. lines, end_lines, columns, end_columns = set(), set(), set(), set() class SourceOffsetVisitor(ast.NodeVisitor): def generic_visit(self, node): super().generic_visit(node) if not isinstance(node, ast.expr) and not isinstance(node, ast.stmt): return lines.add(node.lineno) end_lines.add(node.end_lineno) columns.add(node.col_offset) end_columns.add(node.end_col_offset) SourceOffsetVisitor().visit(ast_tree) # Check against the positions in the code object. for (line, end_line, col, end_col) in code.co_positions(): # If the offset is not None (indicating missing data), ensure that # it was part of one of the AST nodes. if line is not None: self.assertIn(line, lines) if end_line is not None: self.assertIn(end_line, end_lines) if col is not None: self.assertIn(col, columns) if end_col is not None: self.assertIn(end_col, end_columns) return code, ast_tree def assertOpcodeSourcePositionIs(self, code, opcode, line, end_line, column, end_column, occurrence=1): for instr, position in zip(dis.Bytecode(code), code.co_positions()): if instr.opname == opcode: occurrence -= 1 if not occurrence: self.assertEqual(position[0], line) self.assertEqual(position[1], end_line) self.assertEqual(position[2], column) self.assertEqual(position[3], end_column) return self.fail(f"Opcode {opcode} not found in code") def test_simple_assignment(self): snippet = "x = 1" self.check_positions_against_ast(snippet) def test_compiles_to_extended_op_arg(self): # Make sure we still have valid positions when the code compiles to an # EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after # a bunch of opcodes. snippet = "x = x\n" * 10_000 snippet += ("while x != 0:\n" " x -= 1\n" "while x != 0:\n" " x += 1\n" ) compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=10_000 + 2, end_line=10_000 + 2, column=2, end_column=8, occurrence=1) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=10_000 + 4, end_line=10_000 + 4, column=2, end_column=9, occurrence=2) def test_multiline_expression(self): snippet = """\ f( 1, 2, 3, 4 ) """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION', line=1, end_line=3, column=0, end_column=1) def test_very_long_line_end_offset(self): # Make sure we get None for when the column offset is too large to # store in a byte. long_string = "a" * 1000 snippet = f"g('{long_string}')" compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION', line=1, end_line=1, column=None, end_column=None) def test_complex_single_line_expression(self): snippet = "a - b @ (c * x['key'] + 23)" compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR', line=1, end_line=1, column=13, end_column=21) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=9, end_column=21, occurrence=1) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=9, end_column=26, occurrence=2) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=4, end_column=27, occurrence=3) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=0, end_column=27, occurrence=4) class TestExpressionStackSize(unittest.TestCase): # These tests check that the computed stack size for a code object # stays within reasonable bounds (see issue #21523 for an example # dysfunction). N = 100 def check_stack_size(self, code): # To assert that the alleged stack size is not O(N), we # check that it is smaller than log(N). if isinstance(code, str): code = compile(code, "<foo>", "single") max_size = math.ceil(math.log(len(code.co_code))) self.assertLessEqual(code.co_stacksize, max_size) def test_and(self): self.check_stack_size("x and " * self.N + "x") def test_or(self): self.check_stack_size("x or " * self.N + "x") def test_and_or(self): self.check_stack_size("x and x or " * self.N + "x") def test_chained_comparison(self): self.check_stack_size("x < " * self.N + "x") def test_if_else(self): self.check_stack_size("x if x else " * self.N + "x") def test_binop(self): self.check_stack_size("x + " * self.N + "x") def test_list(self): self.check_stack_size("[" + "x, " * self.N + "x]") def test_tuple(self): self.check_stack_size("(" + "x, " * self.N + "x)") def test_set(self): self.check_stack_size("{" + "x, " * self.N + "x}") def test_dict(self): self.check_stack_size("{" + "x:x, " * self.N + "x:x}") def test_func_args(self): self.check_stack_size("f(" + "x, " * self.N + ")") def test_func_kwargs(self): kwargs = (f'a{i}=x' for i in range(self.N)) self.check_stack_size("f(" + ", ".join(kwargs) + ")") def test_func_args(self): self.check_stack_size("o.m(" + "x, " * self.N + ")") def test_meth_kwargs(self): kwargs = (f'a{i}=x' for i in range(self.N)) self.check_stack_size("o.m(" + ", ".join(kwargs) + ")") def test_func_and(self): code = "def f(x):\n" code += " x and x\n" * self.N self.check_stack_size(code) class TestStackSizeStability(unittest.TestCase): # Check that repeating certain snippets doesn't increase the stack size # beyond what a single snippet requires. def check_stack_size(self, snippet, async_=False): def compile_snippet(i): ns = {} script = """def func():\n""" + i * snippet if async_: script = "async " + script code = compile(script, "<script>", "exec") exec(code, ns, ns) return ns['func'].__code__ sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)] if len(set(sizes)) != 1: import dis, io out = io.StringIO() dis.dis(compile_snippet(1), file=out) self.fail("stack sizes diverge with # of consecutive snippets: " "%s\n%s\n%s" % (sizes, snippet, out.getvalue())) def test_if(self): snippet = """ if x: a """ self.check_stack_size(snippet) def test_if_else(self): snippet = """ if x: a elif y: b else: c """ self.check_stack_size(snippet) def test_try_except_bare(self): snippet = """ try: a except: b """ self.check_stack_size(snippet) def test_try_except_qualified(self): snippet = """ try: a except ImportError: b except: c else: d """ self.check_stack_size(snippet) def test_try_except_as(self): snippet = """ try: a except ImportError as e: b except: c else: d """ self.check_stack_size(snippet) def test_try_finally(self): snippet = """ try: a finally: b """ self.check_stack_size(snippet) def test_with(self): snippet = """ with x as y: a """ self.check_stack_size(snippet) def test_while_else(self): snippet = """ while x: a else: b """ self.check_stack_size(snippet) def test_for(self): snippet = """ for x in y: a """ self.check_stack_size(snippet) def test_for_else(self): snippet = """ for x in y: a else: b """ self.check_stack_size(snippet) def test_for_break_continue(self): snippet = """ for x in y: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_try_finally_block(self): snippet = """ for x in y: try: if z: break elif u: continue else: a finally: f else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_finally_block(self): snippet = """ for x in y: try: t finally: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_except_block(self): snippet = """ for x in y: try: t except: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_with_block(self): snippet = """ for x in y: with c: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_return_inside_try_finally_block(self): snippet = """ try: if z: return else: a finally: f """ self.check_stack_size(snippet) def test_return_inside_finally_block(self): snippet = """ try: t finally: if z: return else: a """ self.check_stack_size(snippet) def test_return_inside_except_block(self): snippet = """ try: t except: if z: return else: a """ self.check_stack_size(snippet) def test_return_inside_with_block(self): snippet = """ with c: if z: return else: a """ self.check_stack_size(snippet) def test_async_with(self): snippet = """ async with x as y: a """ self.check_stack_size(snippet, async_=True) def test_async_for(self): snippet = """ async for x in y: a """ self.check_stack_size(snippet, async_=True) def test_async_for_else(self): snippet = """ async for x in y: a else: b """ self.check_stack_size(snippet, async_=True) def test_for_break_continue_inside_async_with_block(self): snippet = """ for x in y: async with c: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet, async_=True) def test_return_inside_async_with_block(self): snippet = """ async with c: if z: return else: a """ self.check_stack_size(snippet, async_=True) if __name__ == "__main__": unittest.main()
34.782726
95
0.536122
import dis import math import os import unittest import sys import ast import _ast import tempfile import types import textwrap from test import support from test.support import script_helper, requires_debug_ranges from test.support.os_helper import FakePath class TestSpecifics(unittest.TestCase): def compile_single(self, source): compile(source, "<single>", "single") def assertInvalidSingle(self, source): self.assertRaises(SyntaxError, self.compile_single, source) def test_no_ending_newline(self): compile("hi", "<test>", "exec") compile("hi\r", "<test>", "exec") def test_empty(self): compile("", "<test>", "exec") def test_other_newlines(self): compile("\r\n", "<test>", "exec") compile("\r", "<test>", "exec") compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec") compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec") def test_debug_assignment(self): self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single') import builtins prev = builtins.__debug__ setattr(builtins, '__debug__', 'sure') self.assertEqual(__debug__, prev) setattr(builtins, '__debug__', prev) def test_argument_handling(self): self.assertRaises(SyntaxError, eval, 'lambda a,a:0') self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0') self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0') self.assertRaises(SyntaxError, exec, 'def f(a, a): pass') self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass') self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1') def test_syntax_error(self): self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec") def test_none_keyword_arg(self): self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec") def test_duplicate_global_local(self): self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1') def test_exec_with_general_mapping_for_locals(self): class M: def __getitem__(self, key): if key == 'a': return 12 raise KeyError def __setitem__(self, key, value): self.results = (key, value) def keys(self): return list('xyz') m = M() g = globals() exec('z = a', g, m) self.assertEqual(m.results, ('z', 12)) try: exec('z = b', g, m) except NameError: pass else: self.fail('Did not detect a KeyError') exec('z = dir()', g, m) self.assertEqual(m.results, ('z', list('xyz'))) exec('z = globals()', g, m) self.assertEqual(m.results, ('z', g)) exec('z = locals()', g, m) self.assertEqual(m.results, ('z', m)) self.assertRaises(TypeError, exec, 'z = b', m) class A: pass m = A() self.assertRaises(TypeError, exec, 'z = a', g, m) class D(dict): def __getitem__(self, key): if key == 'a': return 12 return dict.__getitem__(self, key) d = D() exec('z = a', g, d) self.assertEqual(d['z'], 12) def test_extended_arg(self): longexpr = 'x = x or ' + '-x' * 2500 g = {} code = ''' def f(x): %s %s %s %s %s %s %s %s %s %s # the expressions above have no effect, x == argument while x: x -= 1 # EXTENDED_ARG/JUMP_ABSOLUTE here return x ''' % ((longexpr,)*10) exec(code, g) self.assertEqual(g['f'](5), 0) def test_argument_order(self): self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass') def test_float_literals(self): self.assertRaises(SyntaxError, eval, "2e") self.assertRaises(SyntaxError, eval, "2.0e+") self.assertRaises(SyntaxError, eval, "1e-") self.assertRaises(SyntaxError, eval, "3-4e/21") def test_indentation(self): s = """ if 1: if 2: pass""" compile(s, "<string>", "exec") # This test is probably specific to CPython and may not generalize # to other implementations. We are trying to ensure that when # the first line of code starts after 256, correct line numbers # in tracebacks are still produced. def test_leading_newlines(self): s256 = "".join(["\n"] * 256 + ["spam"]) co = compile(s256, 'fn', 'exec') self.assertEqual(co.co_firstlineno, 1) self.assertEqual(list(co.co_lines()), [(0, 8, 257)]) def test_literals_with_leading_zeroes(self): for arg in ["077787", "0xj", "0x.", "0e", "090000000000000", "080000000000000", "000000000000009", "000000000000008", "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2", "0b101j", "0o153j", "0b100e1", "0o777e1", "0777", "000777", "000000000000007"]: self.assertRaises(SyntaxError, eval, arg) self.assertEqual(eval("0xff"), 255) self.assertEqual(eval("0777."), 777) self.assertEqual(eval("0777.0"), 777) self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777) self.assertEqual(eval("0777e1"), 7770) self.assertEqual(eval("0e0"), 0) self.assertEqual(eval("0000e-012"), 0) self.assertEqual(eval("09.5"), 9.5) self.assertEqual(eval("0777j"), 777j) self.assertEqual(eval("000"), 0) self.assertEqual(eval("00j"), 0j) self.assertEqual(eval("00.0"), 0) self.assertEqual(eval("0e3"), 0) self.assertEqual(eval("090000000000000."), 90000000000000.) self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.) self.assertEqual(eval("090000000000000e0"), 90000000000000.) self.assertEqual(eval("090000000000000e-0"), 90000000000000.) self.assertEqual(eval("090000000000000j"), 90000000000000j) self.assertEqual(eval("000000000000008."), 8.) self.assertEqual(eval("000000000000009."), 9.) self.assertEqual(eval("0b101010"), 42) self.assertEqual(eval("-0b000000000010"), -2) self.assertEqual(eval("0o777"), 511) self.assertEqual(eval("-0o0000010"), -8) def test_unary_minus(self): # Verify treatment of unary minus on negative numbers SF bug #660455 if sys.maxsize == 2147483647: # 32-bit machine all_one_bits = '0xffffffff' self.assertEqual(eval(all_one_bits), 4294967295) self.assertEqual(eval("-" + all_one_bits), -4294967295) elif sys.maxsize == 9223372036854775807: # 64-bit machine all_one_bits = '0xffffffffffffffff' self.assertEqual(eval(all_one_bits), 18446744073709551615) self.assertEqual(eval("-" + all_one_bits), -18446744073709551615) else: self.fail("How many bits *does* this machine have???") # Verify treatment of constant folding on -(sys.maxsize+1) # i.e. -2147483648 on 32 bit platforms. Should return int. self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int) self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int) if sys.maxsize == 9223372036854775807: def test_32_63_bit_values(self): a = +4294967296 # 1 << 32 b = -4294967296 # 1 << 32 c = +281474976710656 # 1 << 48 d = -281474976710656 # 1 << 48 e = +4611686018427387904 # 1 << 62 f = -4611686018427387904 # 1 << 62 g = +9223372036854775807 # 1 << 63 - 1 h = -9223372036854775807 # 1 << 63 - 1 for variable in self.test_32_63_bit_values.__code__.co_consts: if variable is not None: self.assertIsInstance(variable, int) def test_sequence_unpacking_error(self): # Verify sequence packing/unpacking with "or". SF bug #757818 i,j = (1, -1) or (-1, 1) self.assertEqual(i, 1) self.assertEqual(j, -1) def test_none_assignment(self): stmts = [ 'None = 0', 'None += 0', '__builtins__.None = 0', 'def None(): pass', 'class None: pass', '(a, None) = 0, 0', 'for None in range(10): pass', 'def f(None): pass', 'import None', 'import x as None', 'from x import None', 'from x import y as None' ] for stmt in stmts: stmt += "\n" self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single') self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec') def test_import(self): succeed = [ 'import sys', 'import os, sys', 'import os as bar', 'import os.path as bar', 'from __future__ import nested_scopes, generators', 'from __future__ import (nested_scopes,\ngenerators)', 'from __future__ import (nested_scopes,\ngenerators,)', 'from sys import stdin, stderr, stdout', 'from sys import (stdin, stderr,\nstdout)', 'from sys import (stdin, stderr,\nstdout,)', 'from sys import (stdin\n, stderr, stdout)', 'from sys import (stdin\n, stderr, stdout,)', 'from sys import stdin as si, stdout as so, stderr as se', 'from sys import (stdin as si, stdout as so, stderr as se)', 'from sys import (stdin as si, stdout as so, stderr as se,)', ] fail = [ 'import (os, sys)', 'import (os), (sys)', 'import ((os), (sys))', 'import (sys', 'import sys)', 'import (os,)', 'import os As bar', 'import os.path a bar', 'from sys import stdin As stdout', 'from sys import stdin a stdout', 'from (sys) import stdin', 'from __future__ import (nested_scopes', 'from __future__ import nested_scopes)', 'from __future__ import nested_scopes,\ngenerators', 'from sys import (stdin', 'from sys import stdin)', 'from sys import stdin, stdout,\nstderr', 'from sys import stdin si', 'from sys import stdin,', 'from sys import (*)', 'from sys import (stdin,, stdout, stderr)', 'from sys import (stdin, stdout),', ] for stmt in succeed: compile(stmt, 'tmp', 'exec') for stmt in fail: self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec') def test_for_distinct_code_objects(self): # SF bug 1048870 def f(): f1 = lambda x=1: x f2 = lambda x=2: x return f1, f2 f1, f2 = f() self.assertNotEqual(id(f1.__code__), id(f2.__code__)) def test_lambda_doc(self): l = lambda: "foo" self.assertIsNone(l.__doc__) def test_encoding(self): code = b'# -*- coding: badencoding -*-\npass\n' self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec') code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n' compile(code, 'tmp', 'exec') self.assertEqual(eval(code), '\xc2\xa4') code = '"\xc2\xa4"\n' self.assertEqual(eval(code), '\xc2\xa4') code = b'"\xc2\xa4"\n' self.assertEqual(eval(code), '\xa4') code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n' self.assertEqual(eval(code), '\xc2\xa4') code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n' self.assertEqual(eval(code), '\xa4') code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n' self.assertEqual(eval(code), '\xc2\u20ac') code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n' self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4') code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n' self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4') def test_subscripts(self): # SF bug 1448804 # Class to make testing subscript results easy class str_map(object): def __init__(self): self.data = {} def __getitem__(self, key): return self.data[str(key)] def __setitem__(self, key, value): self.data[str(key)] = value def __delitem__(self, key): del self.data[str(key)] def __contains__(self, key): return str(key) in self.data d = str_map() # Index d[1] = 1 self.assertEqual(d[1], 1) d[1] += 1 self.assertEqual(d[1], 2) del d[1] self.assertNotIn(1, d) # Tuple of indices d[1, 1] = 1 self.assertEqual(d[1, 1], 1) d[1, 1] += 1 self.assertEqual(d[1, 1], 2) del d[1, 1] self.assertNotIn((1, 1), d) # Simple slice d[1:2] = 1 self.assertEqual(d[1:2], 1) d[1:2] += 1 self.assertEqual(d[1:2], 2) del d[1:2] self.assertNotIn(slice(1, 2), d) # Tuple of simple slices d[1:2, 1:2] = 1 self.assertEqual(d[1:2, 1:2], 1) d[1:2, 1:2] += 1 self.assertEqual(d[1:2, 1:2], 2) del d[1:2, 1:2] self.assertNotIn((slice(1, 2), slice(1, 2)), d) # Extended slice d[1:2:3] = 1 self.assertEqual(d[1:2:3], 1) d[1:2:3] += 1 self.assertEqual(d[1:2:3], 2) del d[1:2:3] self.assertNotIn(slice(1, 2, 3), d) # Tuple of extended slices d[1:2:3, 1:2:3] = 1 self.assertEqual(d[1:2:3, 1:2:3], 1) d[1:2:3, 1:2:3] += 1 self.assertEqual(d[1:2:3, 1:2:3], 2) del d[1:2:3, 1:2:3] self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d) # Ellipsis d[...] = 1 self.assertEqual(d[...], 1) d[...] += 1 self.assertEqual(d[...], 2) del d[...] self.assertNotIn(Ellipsis, d) # Tuple of Ellipses d[..., ...] = 1 self.assertEqual(d[..., ...], 1) d[..., ...] += 1 self.assertEqual(d[..., ...], 2) del d[..., ...] self.assertNotIn((Ellipsis, Ellipsis), d) def test_annotation_limit(self): # more than 255 annotations, should compile ok s = "def f(%s): pass" s %= ', '.join('a%d:%d' % (i,i) for i in range(300)) compile(s, '?', 'exec') def test_mangling(self): class A: def f(): __mangled = 1 __not_mangled__ = 2 import __mangled_mod import __package__.module self.assertIn("_A__mangled", A.f.__code__.co_varnames) self.assertIn("__not_mangled__", A.f.__code__.co_varnames) self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames) self.assertIn("__package__", A.f.__code__.co_varnames) def test_compile_ast(self): fname = __file__ if fname.lower().endswith('pyc'): fname = fname[:-1] with open(fname, encoding='utf-8') as f: fcontents = f.read() sample_code = [ ['<assign>', 'x = 5'], ['<ifblock>', """if True:\n pass\n"""], ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""], ['<deffunc>', """def foo():\n pass\nfoo()\n"""], [fname, fcontents], ] for fname, code in sample_code: co1 = compile(code, '%s1' % fname, 'exec') ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST) self.assertTrue(type(ast) == _ast.Module) co2 = compile(ast, '%s3' % fname, 'exec') self.assertEqual(co1, co2) # the code object's filename comes from the second compilation step self.assertEqual(co2.co_filename, '%s3' % fname) # raise exception when node type doesn't match with compile mode co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST) self.assertRaises(TypeError, compile, co1, '<ast>', 'eval') # raise exception when node type is no start node self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec') # raise exception when node has invalid children ast = _ast.Module() ast.body = [_ast.BoolOp()] self.assertRaises(TypeError, compile, ast, '<ast>', 'exec') def test_dict_evaluation_order(self): i = 0 def f(): nonlocal i i += 1 return i d = {f(): f(), f(): f()} self.assertEqual(d, {1: 2, 3: 4}) def test_compile_filename(self): for filename in 'file.py', b'file.py': code = compile('pass', filename, 'exec') self.assertEqual(code.co_filename, 'file.py') for filename in bytearray(b'file.py'), memoryview(b'file.py'): with self.assertWarns(DeprecationWarning): code = compile('pass', filename, 'exec') self.assertEqual(code.co_filename, 'file.py') self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec') @support.cpython_only def test_same_filename_used(self): s = """def f(): pass\ndef g(): pass""" c = compile(s, "myfile", "exec") for obj in c.co_consts: if isinstance(obj, types.CodeType): self.assertIs(obj.co_filename, c.co_filename) def test_single_statement(self): self.compile_single("1 + 2") self.compile_single("\n1 + 2") self.compile_single("1 + 2\n") self.compile_single("1 + 2\n\n") self.compile_single("1 + 2\t\t\n") self.compile_single("1 + 2\t\t\n ") self.compile_single("1 + 2 self.compile_single("1; 2") self.compile_single("import sys; sys") self.compile_single("def f():\n pass") self.compile_single("while False:\n pass") self.compile_single("if x:\n f(x)") self.compile_single("if x:\n f(x)\nelse:\n g(x)") self.compile_single("class T:\n pass") def test_bad_single_statement(self): self.assertInvalidSingle('1\n2') self.assertInvalidSingle('def f(): pass') self.assertInvalidSingle('a = 13\nb = 187') self.assertInvalidSingle('del x\ndel y') self.assertInvalidSingle('f()\ng()') self.assertInvalidSingle('f()\n# blah\nblah()') self.assertInvalidSingle('f()\nxy # blah\nblah()') self.assertInvalidSingle('x = 5 # comment\nx = 6\n') def test_particularly_evil_undecodable(self): # Issue 24022 src = b'0000\x00\n00000000000\n\x00\n\x9e\n' with tempfile.TemporaryDirectory() as tmpd: fn = os.path.join(tmpd, "bad.py") with open(fn, "wb") as fp: fp.write(src) res = script_helper.run_python_until_end(fn)[0] self.assertIn(b"Non-UTF-8", res.err) def test_yet_more_evil_still_undecodable(self): # Issue #25388 src = b" with tempfile.TemporaryDirectory() as tmpd: fn = os.path.join(tmpd, "bad.py") with open(fn, "wb") as fp: fp.write(src) res = script_helper.run_python_until_end(fn)[0] self.assertIn(b"Non-UTF-8", res.err) @support.cpython_only def test_compiler_recursion_limit(self): # Expected limit is sys.getrecursionlimit() * the scaling factor # in symtable.c (currently 3) # We expect to fail *at* that limit, because we use up some of # the stack depth limit in the test suite code # So we check the expected limit and 75% of that # XXX (ncoghlan): duplicating the scaling factor here is a little # ugly. Perhaps it should be exposed somewhere... fail_depth = sys.getrecursionlimit() * 3 crash_depth = sys.getrecursionlimit() * 300 success_depth = int(fail_depth * 0.75) def check_limit(prefix, repeated, mode="single"): expect_ok = prefix + repeated * success_depth compile(expect_ok, '<test>', mode) for depth in (fail_depth, crash_depth): broken = prefix + repeated * depth details = "Compiling ({!r} + {!r} * {})".format( prefix, repeated, depth) with self.assertRaises(RecursionError, msg=details): compile(broken, '<test>', mode) check_limit("a", "()") check_limit("a", ".b") check_limit("a", "[0]") check_limit("a", "*a") # XXX Crashes in the parser. # check_limit("a", " if a else a") # check_limit("if a: pass", "\nelif a: pass", mode="exec") def test_null_terminated(self): # The source code is null-terminated internally, but bytes-like # objects are accepted, which could be not terminated. with self.assertRaisesRegex(ValueError, "cannot contain null"): compile("123\x00", "<dummy>", "eval") with self.assertRaisesRegex(ValueError, "cannot contain null"): compile(memoryview(b"123\x00"), "<dummy>", "eval") code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval") self.assertEqual(eval(code), 23) code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval") self.assertEqual(eval(code), 23) code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval") self.assertEqual(eval(code), 23) # Also test when eval() and exec() do the compilation step self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23) namespace = dict() exec(memoryview(b"ax = 123")[1:-1], namespace) self.assertEqual(namespace['x'], 12) def check_constant(self, func, expected): for const in func.__code__.co_consts: if repr(const) == repr(expected): break else: self.fail("unable to find constant %r in %r" % (expected, func.__code__.co_consts)) # Merging equal constants is not a strict requirement for the Python # semantics, it's a more an implementation detail. @support.cpython_only def test_merge_constants(self): # Issue #25843: compile() must merge constants which are equal # and have the same type. def check_same_constant(const): ns = {} code = "f1, f2 = lambda: %r, lambda: %r" % (const, const) exec(code, ns) f1 = ns['f1'] f2 = ns['f2'] self.assertIs(f1.__code__, f2.__code__) self.check_constant(f1, const) self.assertEqual(repr(f1()), repr(const)) check_same_constant(None) check_same_constant(0) check_same_constant(0.0) check_same_constant(b'abc') check_same_constant('abc') # Note: "lambda: ..." emits "LOAD_CONST Ellipsis", # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis" f1, f2 = lambda: ..., lambda: ... self.assertIs(f1.__code__, f2.__code__) self.check_constant(f1, Ellipsis) self.assertEqual(repr(f1()), repr(Ellipsis)) # Merge constants in tuple or frozenset f1, f2 = lambda: "not a name", lambda: ("not a name",) f3 = lambda x: x in {("not a name",)} self.assertIs(f1.__code__.co_consts[1], f2.__code__.co_consts[1][0]) self.assertIs(next(iter(f3.__code__.co_consts[1])), f2.__code__.co_consts[1]) # {0} is converted to a constant frozenset({0}) by the peephole # optimizer f1, f2 = lambda x: x in {0}, lambda x: x in {0} self.assertIs(f1.__code__, f2.__code__) self.check_constant(f1, frozenset({0})) self.assertTrue(f1(0)) # Merging equal co_linetable and co_code is not a strict requirement # for the Python semantics, it's a more an implementation detail. @support.cpython_only def test_merge_code_attrs(self): # See https://bugs.python.org/issue42217 f1 = lambda x: x.y.z f2 = lambda a: a.b.c self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable) self.assertIs(f1.__code__.co_code, f2.__code__.co_code) # Stripping unused constants is not a strict requirement for the # Python semantics, it's a more an implementation detail. @support.cpython_only def test_strip_unused_consts(self): # Python 3.10rc1 appended None to co_consts when None is not used # at all. See bpo-45056. def f1(): return 42 self.assertEqual(f1.__code__.co_consts, ("docstring", 42)) # This is a regression test for a CPython specific peephole optimizer # implementation bug present in a few releases. It's assertion verifies # that peephole optimization was actually done though that isn't an # indication of the bugs presence or not (crashing is). @support.cpython_only def test_peephole_opt_unreachable_code_array_access_in_bounds(self): def unused_code_at_end(): return 3 raise RuntimeError("unreachable") # The above function definition will trigger the out of bounds # bug in the peephole optimizer as it scans opcodes past the # RETURN_VALUE opcode. This does not always crash an interpreter. # When you build with the clang memory sanitizer it reliably aborts. self.assertEqual( 'RETURN_VALUE', list(dis.get_instructions(unused_code_at_end))[-1].opname) def test_dont_merge_constants(self): # Issue #25843: compile() must not merge constants which are equal # but have a different type. def check_different_constants(const1, const2): ns = {} exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns) f1 = ns['f1'] f2 = ns['f2'] self.assertIsNot(f1.__code__, f2.__code__) self.assertNotEqual(f1.__code__, f2.__code__) self.check_constant(f1, const1) self.check_constant(f2, const2) self.assertEqual(repr(f1()), repr(const1)) self.assertEqual(repr(f2()), repr(const2)) check_different_constants(0, 0.0) check_different_constants(+0.0, -0.0) check_different_constants((0,), (0.0,)) check_different_constants('a', b'a') check_different_constants(('a',), (b'a',)) # check_different_constants() cannot be used because repr(-0j) is # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign. f1, f2 = lambda: +0.0j, lambda: -0.0j self.assertIsNot(f1.__code__, f2.__code__) self.check_constant(f1, +0.0j) self.check_constant(f2, -0.0j) self.assertEqual(repr(f1()), repr(+0.0j)) self.assertEqual(repr(f2()), repr(-0.0j)) # {0} is converted to a constant frozenset({0}) by the peephole # optimizer f1, f2 = lambda x: x in {0}, lambda x: x in {0.0} self.assertIsNot(f1.__code__, f2.__code__) self.check_constant(f1, frozenset({0})) self.check_constant(f2, frozenset({0.0})) self.assertTrue(f1(0)) self.assertTrue(f2(0.0)) def test_path_like_objects(self): # An implicit test for PyUnicode_FSDecoder(). compile("42", FakePath("test_compile_pathlike"), "single") def test_stack_overflow(self): # bpo-31113: Stack overflow when compile a long sequence of # complex statements. compile("if a: b\n" * 200000, "<dummy>", "exec") # Multiple users rely on the fact that CPython does not generate # bytecode for dead code blocks. See bpo-37500 for more context. @support.cpython_only def test_dead_blocks_do_not_generate_bytecode(self): def unused_block_if(): if 0: return 42 def unused_block_while(): while 0: return 42 def unused_block_if_else(): if 1: return None else: return 42 def unused_block_while_else(): while 1: return None else: return 42 funcs = [unused_block_if, unused_block_while, unused_block_if_else, unused_block_while_else] for func in funcs: opcodes = list(dis.get_instructions(func)) self.assertLessEqual(len(opcodes), 3) self.assertEqual('LOAD_CONST', opcodes[-2].opname) self.assertEqual(None, opcodes[-2].argval) self.assertEqual('RETURN_VALUE', opcodes[-1].opname) def test_false_while_loop(self): def break_in_while(): while False: break def continue_in_while(): while False: continue funcs = [break_in_while, continue_in_while] # Check that we did not raise but we also don't generate bytecode for func in funcs: opcodes = list(dis.get_instructions(func)) self.assertEqual(2, len(opcodes)) self.assertEqual('LOAD_CONST', opcodes[0].opname) self.assertEqual(None, opcodes[0].argval) self.assertEqual('RETURN_VALUE', opcodes[1].opname) def test_consts_in_conditionals(self): def and_true(x): return True and x def and_false(x): return False and x def or_true(x): return True or x def or_false(x): return False or x funcs = [and_true, and_false, or_true, or_false] # Check that condition is removed. for func in funcs: with self.subTest(func=func): opcodes = list(dis.get_instructions(func)) self.assertEqual(2, len(opcodes)) self.assertIn('LOAD_', opcodes[0].opname) self.assertEqual('RETURN_VALUE', opcodes[1].opname) def test_imported_load_method(self): sources = [ """\ import os def foo(): return os.uname() """, """\ import os as operating_system def foo(): return operating_system.uname() """, """\ from os import path def foo(x): return path.join(x) """, """\ from os import path as os_path def foo(x): return os_path.join(x) """ ] for source in sources: namespace = {} exec(textwrap.dedent(source), namespace) func = namespace['foo'] with self.subTest(func=func.__name__): opcodes = list(dis.get_instructions(func)) instructions = [opcode.opname for opcode in opcodes] self.assertNotIn('LOAD_METHOD', instructions) self.assertNotIn('CALL_METHOD', instructions) self.assertIn('LOAD_ATTR', instructions) self.assertIn('CALL_FUNCTION', instructions) def test_lineno_procedure_call(self): def call(): ( print() ) line1 = call.__code__.co_firstlineno + 1 assert line1 not in [line for (_, _, line) in call.__code__.co_lines()] def test_lineno_after_implicit_return(self): TRUE = True # Don't use constant True or False, as compiler will remove test def if1(x): x() if TRUE: pass def if2(x): x() if TRUE: pass else: pass def if3(x): x() if TRUE: pass else: return None def if4(x): x() if not TRUE: pass funcs = [ if1, if2, if3, if4] lastlines = [ 3, 3, 3, 2] frame = None def save_caller_frame(): nonlocal frame frame = sys._getframe(1) for func, lastline in zip(funcs, lastlines, strict=True): with self.subTest(func=func): func(save_caller_frame) self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline) def test_lineno_after_no_code(self): def no_code1(): def no_code2(): a: int for func in (no_code1, no_code2): with self.subTest(func=func): code = func.__code__ lines = list(code.co_lines()) self.assertEqual(len(lines), 1) start, end, line = lines[0] self.assertEqual(start, 0) self.assertEqual(end, len(code.co_code)) self.assertEqual(line, code.co_firstlineno) def test_lineno_attribute(self): def load_attr(): return ( o. a ) load_attr_lines = [ 2, 3, 1 ] def load_method(): return ( o. m( 0 ) ) load_method_lines = [ 2, 3, 4, 3, 1 ] def store_attr(): ( o. a ) = ( v ) store_attr_lines = [ 5, 2, 3 ] def aug_store_attr(): ( o. a ) += ( v ) aug_store_attr_lines = [ 2, 3, 5, 1, 3 ] funcs = [ load_attr, load_method, store_attr, aug_store_attr] func_lines = [ load_attr_lines, load_method_lines, store_attr_lines, aug_store_attr_lines] for func, lines in zip(funcs, func_lines, strict=True): with self.subTest(func=func): code_lines = [ line-func.__code__.co_firstlineno for (_, _, line) in func.__code__.co_lines() ] self.assertEqual(lines, code_lines) def test_line_number_genexp(self): def return_genexp(): return (1 for x in y) genexp_lines = [None, 1, 3, 1] genexp_code = return_genexp.__code__.co_consts[1] code_lines = [ None if line is None else line-return_genexp.__code__.co_firstlineno for (_, _, line) in genexp_code.co_lines() ] self.assertEqual(genexp_lines, code_lines) def test_line_number_implicit_return_after_async_for(self): async def test(aseq): async for i in aseq: body expected_lines = [None, 1, 2, 1] code_lines = [ None if line is None else line-test.__code__.co_firstlineno for (_, _, line) in test.__code__.co_lines() ] self.assertEqual(expected_lines, code_lines) def test_big_dict_literal(self): # The compiler has a flushing point in "compiler_dict" that calls compiles # a portion of the dictionary literal when the loop that iterates over the items # reaches 0xFFFF elements but the code was not including the boundary element, # dropping the key at position 0xFFFF. See bpo-41531 for more information dict_size = 0xFFFF + 1 the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}" self.assertEqual(len(eval(the_dict)), dict_size) def test_redundant_jump_in_if_else_break(self): # Check if bytecode containing jumps that simply point to the next line # is generated around if-else-break style structures. See bpo-42615. def if_else_break(): val = 1 while True: if val > 0: val -= 1 else: break val = -1 INSTR_SIZE = 2 HANDLED_JUMPS = ( 'POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', ) for line, instr in enumerate(dis.Bytecode(if_else_break)): if instr.opname == 'JUMP_FORWARD': self.assertNotEqual(instr.arg, 0) elif instr.opname in HANDLED_JUMPS: self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE) @requires_debug_ranges() class TestSourcePositions(unittest.TestCase): # Ensure that compiled code snippets have correct line and column numbers # in `co_positions()`. def check_positions_against_ast(self, snippet): # Basic check that makes sure each line and column is at least present # in one of the AST nodes of the source code. code = compile(snippet, 'test_compile.py', 'exec') ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST) self.assertTrue(type(ast_tree) == _ast.Module) # Use an AST visitor that notes all the offsets. lines, end_lines, columns, end_columns = set(), set(), set(), set() class SourceOffsetVisitor(ast.NodeVisitor): def generic_visit(self, node): super().generic_visit(node) if not isinstance(node, ast.expr) and not isinstance(node, ast.stmt): return lines.add(node.lineno) end_lines.add(node.end_lineno) columns.add(node.col_offset) end_columns.add(node.end_col_offset) SourceOffsetVisitor().visit(ast_tree) # Check against the positions in the code object. for (line, end_line, col, end_col) in code.co_positions(): # If the offset is not None (indicating missing data), ensure that # it was part of one of the AST nodes. if line is not None: self.assertIn(line, lines) if end_line is not None: self.assertIn(end_line, end_lines) if col is not None: self.assertIn(col, columns) if end_col is not None: self.assertIn(end_col, end_columns) return code, ast_tree def assertOpcodeSourcePositionIs(self, code, opcode, line, end_line, column, end_column, occurrence=1): for instr, position in zip(dis.Bytecode(code), code.co_positions()): if instr.opname == opcode: occurrence -= 1 if not occurrence: self.assertEqual(position[0], line) self.assertEqual(position[1], end_line) self.assertEqual(position[2], column) self.assertEqual(position[3], end_column) return self.fail(f"Opcode {opcode} not found in code") def test_simple_assignment(self): snippet = "x = 1" self.check_positions_against_ast(snippet) def test_compiles_to_extended_op_arg(self): # Make sure we still have valid positions when the code compiles to an # EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after # a bunch of opcodes. snippet = "x = x\n" * 10_000 snippet += ("while x != 0:\n" " x -= 1\n" "while x != 0:\n" " x += 1\n" ) compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=10_000 + 2, end_line=10_000 + 2, column=2, end_column=8, occurrence=1) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=10_000 + 4, end_line=10_000 + 4, column=2, end_column=9, occurrence=2) def test_multiline_expression(self): snippet = """\ f( 1, 2, 3, 4 ) """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION', line=1, end_line=3, column=0, end_column=1) def test_very_long_line_end_offset(self): # Make sure we get None for when the column offset is too large to # store in a byte. long_string = "a" * 1000 snippet = f"g('{long_string}')" compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION', line=1, end_line=1, column=None, end_column=None) def test_complex_single_line_expression(self): snippet = "a - b @ (c * x['key'] + 23)" compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR', line=1, end_line=1, column=13, end_column=21) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=9, end_column=21, occurrence=1) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=9, end_column=26, occurrence=2) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=4, end_column=27, occurrence=3) self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP', line=1, end_line=1, column=0, end_column=27, occurrence=4) class TestExpressionStackSize(unittest.TestCase): # These tests check that the computed stack size for a code object # stays within reasonable bounds (see issue #21523 for an example # dysfunction). N = 100 def check_stack_size(self, code): # To assert that the alleged stack size is not O(N), we # check that it is smaller than log(N). if isinstance(code, str): code = compile(code, "<foo>", "single") max_size = math.ceil(math.log(len(code.co_code))) self.assertLessEqual(code.co_stacksize, max_size) def test_and(self): self.check_stack_size("x and " * self.N + "x") def test_or(self): self.check_stack_size("x or " * self.N + "x") def test_and_or(self): self.check_stack_size("x and x or " * self.N + "x") def test_chained_comparison(self): self.check_stack_size("x < " * self.N + "x") def test_if_else(self): self.check_stack_size("x if x else " * self.N + "x") def test_binop(self): self.check_stack_size("x + " * self.N + "x") def test_list(self): self.check_stack_size("[" + "x, " * self.N + "x]") def test_tuple(self): self.check_stack_size("(" + "x, " * self.N + "x)") def test_set(self): self.check_stack_size("{" + "x, " * self.N + "x}") def test_dict(self): self.check_stack_size("{" + "x:x, " * self.N + "x:x}") def test_func_args(self): self.check_stack_size("f(" + "x, " * self.N + ")") def test_func_kwargs(self): kwargs = (f'a{i}=x' for i in range(self.N)) self.check_stack_size("f(" + ", ".join(kwargs) + ")") def test_func_args(self): self.check_stack_size("o.m(" + "x, " * self.N + ")") def test_meth_kwargs(self): kwargs = (f'a{i}=x' for i in range(self.N)) self.check_stack_size("o.m(" + ", ".join(kwargs) + ")") def test_func_and(self): code = "def f(x):\n" code += " x and x\n" * self.N self.check_stack_size(code) class TestStackSizeStability(unittest.TestCase): # Check that repeating certain snippets doesn't increase the stack size # beyond what a single snippet requires. def check_stack_size(self, snippet, async_=False): def compile_snippet(i): ns = {} script = """def func():\n""" + i * snippet if async_: script = "async " + script code = compile(script, "<script>", "exec") exec(code, ns, ns) return ns['func'].__code__ sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)] if len(set(sizes)) != 1: import dis, io out = io.StringIO() dis.dis(compile_snippet(1), file=out) self.fail("stack sizes diverge with "%s\n%s\n%s" % (sizes, snippet, out.getvalue())) def test_if(self): snippet = """ if x: a """ self.check_stack_size(snippet) def test_if_else(self): snippet = """ if x: a elif y: b else: c """ self.check_stack_size(snippet) def test_try_except_bare(self): snippet = """ try: a except: b """ self.check_stack_size(snippet) def test_try_except_qualified(self): snippet = """ try: a except ImportError: b except: c else: d """ self.check_stack_size(snippet) def test_try_except_as(self): snippet = """ try: a except ImportError as e: b except: c else: d """ self.check_stack_size(snippet) def test_try_finally(self): snippet = """ try: a finally: b """ self.check_stack_size(snippet) def test_with(self): snippet = """ with x as y: a """ self.check_stack_size(snippet) def test_while_else(self): snippet = """ while x: a else: b """ self.check_stack_size(snippet) def test_for(self): snippet = """ for x in y: a """ self.check_stack_size(snippet) def test_for_else(self): snippet = """ for x in y: a else: b """ self.check_stack_size(snippet) def test_for_break_continue(self): snippet = """ for x in y: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_try_finally_block(self): snippet = """ for x in y: try: if z: break elif u: continue else: a finally: f else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_finally_block(self): snippet = """ for x in y: try: t finally: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_except_block(self): snippet = """ for x in y: try: t except: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_for_break_continue_inside_with_block(self): snippet = """ for x in y: with c: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet) def test_return_inside_try_finally_block(self): snippet = """ try: if z: return else: a finally: f """ self.check_stack_size(snippet) def test_return_inside_finally_block(self): snippet = """ try: t finally: if z: return else: a """ self.check_stack_size(snippet) def test_return_inside_except_block(self): snippet = """ try: t except: if z: return else: a """ self.check_stack_size(snippet) def test_return_inside_with_block(self): snippet = """ with c: if z: return else: a """ self.check_stack_size(snippet) def test_async_with(self): snippet = """ async with x as y: a """ self.check_stack_size(snippet, async_=True) def test_async_for(self): snippet = """ async for x in y: a """ self.check_stack_size(snippet, async_=True) def test_async_for_else(self): snippet = """ async for x in y: a else: b """ self.check_stack_size(snippet, async_=True) def test_for_break_continue_inside_async_with_block(self): snippet = """ for x in y: async with c: if z: break elif u: continue else: a else: b """ self.check_stack_size(snippet, async_=True) def test_return_inside_async_with_block(self): snippet = """ async with c: if z: return else: a """ self.check_stack_size(snippet, async_=True) if __name__ == "__main__": unittest.main()
true
true
f72c7e77f2ce593a9f65d35942b6d6d6225b5155
1,001
py
Python
audiovisual_stream.py
yagguc/deep_impression
ad45d6640cdb46ff68dd44d8055b53ac57f3d342
[ "MIT" ]
36
2016-11-10T08:05:08.000Z
2022-03-25T12:55:55.000Z
audiovisual_stream.py
yagguc/deep_impression
ad45d6640cdb46ff68dd44d8055b53ac57f3d342
[ "MIT" ]
5
2018-01-04T02:03:21.000Z
2022-03-13T13:04:56.000Z
audiovisual_stream.py
yagguc/deep_impression
ad45d6640cdb46ff68dd44d8055b53ac57f3d342
[ "MIT" ]
24
2016-09-26T01:41:31.000Z
2022-03-07T08:16:58.000Z
import auditory_stream import chainer import visual_stream ### MODEL ### class ResNet18(chainer.Chain): def __init__(self): super(ResNet18, self).__init__( aud = auditory_stream.ResNet18(), vis = visual_stream.ResNet18(), fc = chainer.links.Linear(512, 5, initialW = chainer.initializers.HeNormal()) ) def __call__(self, x): h = [self.aud(True, chainer.Variable(chainer.cuda.to_gpu(x[0]), True)), chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][:256]), True)), 0), 0)] for i in xrange(256, x[1].shape[0], 256): h[1] += chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][i : i + 256]), True)), 0), 0) h[1] /= x[1].shape[0] return chainer.cuda.to_cpu(((chainer.functions.tanh(self.fc(chainer.functions.concat(h))) + 1) / 2).data[0]) ### MODEL ###
41.708333
212
0.621379
import auditory_stream import chainer import visual_stream ): def __init__(self): super(ResNet18, self).__init__( aud = auditory_stream.ResNet18(), vis = visual_stream.ResNet18(), fc = chainer.links.Linear(512, 5, initialW = chainer.initializers.HeNormal()) ) def __call__(self, x): h = [self.aud(True, chainer.Variable(chainer.cuda.to_gpu(x[0]), True)), chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][:256]), True)), 0), 0)] for i in xrange(256, x[1].shape[0], 256): h[1] += chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][i : i + 256]), True)), 0), 0) h[1] /= x[1].shape[0] return chainer.cuda.to_cpu(((chainer.functions.tanh(self.fc(chainer.functions.concat(h))) + 1) / 2).data[0])
true
true
f72c7eba9adcee72dd6bb67f5e168999469e292c
1,058
py
Python
XXBDailyFresh/apps/user/urls.py
sixTiger/XXBDailyFresh
5c6976eff8e073f79b50e7829e10332ccd8df43d
[ "MIT" ]
null
null
null
XXBDailyFresh/apps/user/urls.py
sixTiger/XXBDailyFresh
5c6976eff8e073f79b50e7829e10332ccd8df43d
[ "MIT" ]
null
null
null
XXBDailyFresh/apps/user/urls.py
sixTiger/XXBDailyFresh
5c6976eff8e073f79b50e7829e10332ccd8df43d
[ "MIT" ]
null
null
null
"""XXBDailyFresh URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ # url(r'^register$', RegisterView.as_view(), name='register'), # 注册 # url(r'^active/(?P<token>.*)$', ActiveView.as_view(), name='active'), # 用户激活 # url(r'^login$', LoginView.as_view(), name='login'), # 登录 from django.urls import path from apps.user.views import RegisterView urlpatterns = [ path('register/', RegisterView.as_view(), name='register'), # 首页 # path('', views.index, name='index'), # 首页 ]
39.185185
81
0.680529
.urls import path from apps.user.views import RegisterView urlpatterns = [ path('register/', RegisterView.as_view(), name='register'),
true
true
f72c7fa8536014c7a70bc5bf40a892ab8804afca
4,820
py
Python
Tsukihime/nscript_parser.py
Samyuth/LomandoCrawler
2d6bc7bd79678b78ac7c30e88b72127134e99b91
[ "MIT" ]
null
null
null
Tsukihime/nscript_parser.py
Samyuth/LomandoCrawler
2d6bc7bd79678b78ac7c30e88b72127134e99b91
[ "MIT" ]
1
2022-03-31T09:40:48.000Z
2022-03-31T09:44:48.000Z
Tsukihime/nscript_parser.py
Samyuth/LomandoCrawler
2d6bc7bd79678b78ac7c30e88b72127134e99b91
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Wed Mar 16 02:05:23 2022 @author: Sagi """ ''' Sample choice node text: ;-BLOCK------------------------------------------------------------------------- *f20 # Label gosub *regard_update !sd if %sceneskip==1 && %1020==1 skip 4 gosub *s20 mov %1020,1 skip 9 `You have already viewed this scene. `Would you like to skip? br selgosub `1. Skip`, *skip20, `2. Don't skip`, *s20 skip 3 *skip20 return ;gosub *s20 select `1. There's only a few minutes until homeroom. I have to head there right away.`, *f21, `2. || I'm curious, so I'll go take a look.`, *f22 ''' import re from Graph import * class TextNode(): def __init__(self, label=None, text=None, children=None): if label is not None: self.label = label else: self.label = None if text is not None: self.text = text else: self.text = "" if children is not None: self.children = children else: self.children = [] def get_text(self): if self.text: return self.text else: return None def get_label(self): if self.label: return self.label else: return None def add_text(self, text): self.text += text def change_label(self, label): self.label = label def add_children(self, children): self.children += children class ChoiceNode(TextNode): def add_choices(self, choices): self.choices = choices def get_choices(self): if self.choices: return self.choices else: return None class TsukihimeNode(TextNode): def get_labels(self, string): return re.findall("\*.*(?=,)|\*.*(?=\s)|\*.*", string) def parse_text(self): if self.text is None: print("No text to parse") return -1 line_ctr = 0 lines = self.text.splitlines() no_lines = len(lines) while (line_ctr < no_lines): if lines[line_ctr].find("select") != -1: children = [] while (line_ctr < no_lines and re.search("`[0-9].*`", lines[line_ctr])): children += self.get_labels(lines[line_ctr]) line_ctr += 1 self.add_children(children) elif lines[line_ctr].find("goto") != -1: self.add_children(self.get_labels(lines[line_ctr])) line_ctr += 1 class NscriptParser(Graph): # method to parse the script def parse(self): nscript = open("./nsdec/NSDEC/result.txt", encoding="cp932") line = nscript.readline() header = open("./parsed_texts/header.txt", "w", encoding="cp932") remaining = open("./parsed_texts/remaining.txt", "w", encoding="cp932") choices = open("./parsed_texts/choices.txt", "w", encoding="cp932") choice_nodes = [] nodes = [] nodes_present = False while (line and line.strip() != "*start"): header.writelines(line) line = nscript.readline() while (line and line.strip() != "; $Id: 4.txt 1282 2006-08-04 18:12:29Z chendo $"): if re.match("\*f.*", line): nodes_present = True choice_nodes.append(TsukihimeNode(text="")) if nodes_present: choice_nodes[-1].add_text(line) if re.match("^\*f", line): choice_nodes[-1].change_label(line.strip()) choices.writelines(line) line = nscript.readline() while (line): if re.match("^\*", line): nodes.append(TextNode(line)) remaining.writelines(line) line = nscript.readline() nscript.close() header.close() remaining.close() choices.close() choice_nodes = list(filter(lambda x: x.get_label() is not None, choice_nodes)) for node in choice_nodes: node.parse_text() for node in choice_nodes: self.graph.add_node(node.label) for child in node.children: if child not in self.graph: self.graph.add_node(child) self.graph.add_edge(node.label, child) return choice_nodes if __name__ == "__main__": parser = NscriptParser() choice_nodes = parser.parse() leveled_tree = parser.get_leveled_tree() output = parser.output_tree_sideways() with open("ouput.txt", "w") as outfile: outfile.write(output) #parser.plot() #parser.plot_pretty()
27.542857
94
0.527386
import re from Graph import * class TextNode(): def __init__(self, label=None, text=None, children=None): if label is not None: self.label = label else: self.label = None if text is not None: self.text = text else: self.text = "" if children is not None: self.children = children else: self.children = [] def get_text(self): if self.text: return self.text else: return None def get_label(self): if self.label: return self.label else: return None def add_text(self, text): self.text += text def change_label(self, label): self.label = label def add_children(self, children): self.children += children class ChoiceNode(TextNode): def add_choices(self, choices): self.choices = choices def get_choices(self): if self.choices: return self.choices else: return None class TsukihimeNode(TextNode): def get_labels(self, string): return re.findall("\*.*(?=,)|\*.*(?=\s)|\*.*", string) def parse_text(self): if self.text is None: print("No text to parse") return -1 line_ctr = 0 lines = self.text.splitlines() no_lines = len(lines) while (line_ctr < no_lines): if lines[line_ctr].find("select") != -1: children = [] while (line_ctr < no_lines and re.search("`[0-9].*`", lines[line_ctr])): children += self.get_labels(lines[line_ctr]) line_ctr += 1 self.add_children(children) elif lines[line_ctr].find("goto") != -1: self.add_children(self.get_labels(lines[line_ctr])) line_ctr += 1 class NscriptParser(Graph): def parse(self): nscript = open("./nsdec/NSDEC/result.txt", encoding="cp932") line = nscript.readline() header = open("./parsed_texts/header.txt", "w", encoding="cp932") remaining = open("./parsed_texts/remaining.txt", "w", encoding="cp932") choices = open("./parsed_texts/choices.txt", "w", encoding="cp932") choice_nodes = [] nodes = [] nodes_present = False while (line and line.strip() != "*start"): header.writelines(line) line = nscript.readline() while (line and line.strip() != "; $Id: 4.txt 1282 2006-08-04 18:12:29Z chendo $"): if re.match("\*f.*", line): nodes_present = True choice_nodes.append(TsukihimeNode(text="")) if nodes_present: choice_nodes[-1].add_text(line) if re.match("^\*f", line): choice_nodes[-1].change_label(line.strip()) choices.writelines(line) line = nscript.readline() while (line): if re.match("^\*", line): nodes.append(TextNode(line)) remaining.writelines(line) line = nscript.readline() nscript.close() header.close() remaining.close() choices.close() choice_nodes = list(filter(lambda x: x.get_label() is not None, choice_nodes)) for node in choice_nodes: node.parse_text() for node in choice_nodes: self.graph.add_node(node.label) for child in node.children: if child not in self.graph: self.graph.add_node(child) self.graph.add_edge(node.label, child) return choice_nodes if __name__ == "__main__": parser = NscriptParser() choice_nodes = parser.parse() leveled_tree = parser.get_leveled_tree() output = parser.output_tree_sideways() with open("ouput.txt", "w") as outfile: outfile.write(output)
true
true
f72c801333b8f88f7e05b48145bad8b1ff95ff41
2,251
py
Python
analyse_play.py
illume/eyestabs
9ce717743a6a4fe7b561c68599e9352da3acf080
[ "Unlicense" ]
null
null
null
analyse_play.py
illume/eyestabs
9ce717743a6a4fe7b561c68599e9352da3acf080
[ "Unlicense" ]
null
null
null
analyse_play.py
illume/eyestabs
9ce717743a6a4fe7b561c68599e9352da3acf080
[ "Unlicense" ]
null
null
null
################################################################################ # STD LIBS import sys # 3RD PARTY LIBS import numpy import pyaudio import analyse # USER LIBS import notes import timing from constants import * ################################################################################ # These values will probably need to be tweaked for each guitar # note must be at least this to be counted # The higher the less chance "noise" will be detected as notes but means notes # must be played hard MINIMUM_VOLUME = -13 # The range is 0dB for the maximally loud sounds down to -40dB for silence. # Typical very loud sounds are -1dB and typical silence is -36dB. # note must be X decibels louder than previous to count as new note ATTACK_THRESHOLD = 1.5 # X midi notes, semitones OCTAVE_CORRECTION = 12 # Analyse X samples at a time SAMPLE_SIZE = 1024 ################################################################################ def main(): pyaud = pyaudio.PyAudio() stream = pyaud.open ( format = pyaudio.paInt16, channels = 2, rate = 44100, input_device_index = 1, input = True ) last_note = last_vol = last_time = 0 while True: t = timing.get_time() rawsamps = stream.read(SAMPLE_SIZE) samps = numpy.fromstring(rawsamps, dtype=numpy.int16) event = '' midi_note = analyse.musical_detect_pitch(samps, min_note=28.0) if midi_note: midi_note += OCTAVE_CORRECTION latest_note = notes.midi_to_note(midi_note) latest_vol = analyse.loudness(samps) attacked = latest_vol - last_vol > ATTACK_THRESHOLD if latest_note != last_note or attacked: if latest_vol > MINIMUM_VOLUME: event = {'note':latest_note, 'time': t} last_time = t last_note = latest_note last_vol = latest_vol elif last_note: last_note = None print event sys.stdout.flush() if __name__ == '__main__': main()
25.292135
81
0.524656
false
true
f72c80155df71399c41c13f3793341aca06db318
2,677
py
Python
plugins/cylance_protect/unit_test/test_update_agent.py
lukaszlaszuk/insightconnect-plugins
8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892
[ "MIT" ]
46
2019-06-05T20:47:58.000Z
2022-03-29T10:18:01.000Z
plugins/cylance_protect/unit_test/test_update_agent.py
lukaszlaszuk/insightconnect-plugins
8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892
[ "MIT" ]
386
2019-06-07T20:20:39.000Z
2022-03-30T17:35:01.000Z
plugins/cylance_protect/unit_test/test_update_agent.py
lukaszlaszuk/insightconnect-plugins
8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892
[ "MIT" ]
43
2019-07-09T14:13:58.000Z
2022-03-28T12:04:46.000Z
import sys import os sys.path.append(os.path.abspath("../")) from unittest import TestCase from icon_cylance_protect.connection.connection import Connection from icon_cylance_protect.actions.update_agent import UpdateAgent import json import logging class TestUpdateAgent(TestCase): def test_integration_update_agent(self): """ TODO: Implement assertions at the end of this test case This is an integration test that will connect to the services your plugin uses. It should be used as the basis for tests below that can run independent of a "live" connection. This test assumes a normal plugin structure with a /tests directory. In that /tests directory should be json samples that contain all the data needed to run this test. To generate samples run: icon-plugin generate samples """ log = logging.getLogger("Test") test_conn = Connection() test_action = UpdateAgent() test_conn.logger = log test_action.logger = log try: with open("../tests/update_agent.json") as file: test_json = json.loads(file.read()).get("body") connection_params = test_json.get("connection") action_params = test_json.get("input") except Exception as e: message = """ Could not find or read sample tests from /tests directory An exception here likely means you didn't fill out your samples correctly in the /tests directory Please use 'icon-plugin generate samples', and fill out the resulting test files in the /tests directory """ self.fail(message) test_conn.connect(connection_params) test_action.connection = test_conn results = test_action.run(action_params) # TODO: Remove this line self.fail("Unimplemented test case") # TODO: The following assert should be updated to look for data from your action # For example: self.assertEquals({"success": True}, results) self.assertEquals({}, results) def test_update_agent(self): """ TODO: Implement test cases here Here you can mock the connection with data returned from the above integration test. For information on mocking and unit testing please go here: https://docs.google.com/document/d/1PifePDG1-mBcmNYE8dULwGxJimiRBrax5BIDG_0TFQI/edit?usp=sharing You can either create a formal Mock for this, or you can create a fake connection class to pass to your action for testing. """ self.fail("Unimplemented Test Case")
36.671233
116
0.668285
import sys import os sys.path.append(os.path.abspath("../")) from unittest import TestCase from icon_cylance_protect.connection.connection import Connection from icon_cylance_protect.actions.update_agent import UpdateAgent import json import logging class TestUpdateAgent(TestCase): def test_integration_update_agent(self): log = logging.getLogger("Test") test_conn = Connection() test_action = UpdateAgent() test_conn.logger = log test_action.logger = log try: with open("../tests/update_agent.json") as file: test_json = json.loads(file.read()).get("body") connection_params = test_json.get("connection") action_params = test_json.get("input") except Exception as e: message = """ Could not find or read sample tests from /tests directory An exception here likely means you didn't fill out your samples correctly in the /tests directory Please use 'icon-plugin generate samples', and fill out the resulting test files in the /tests directory """ self.fail(message) test_conn.connect(connection_params) test_action.connection = test_conn results = test_action.run(action_params) # TODO: Remove this line self.fail("Unimplemented test case") # TODO: The following assert should be updated to look for data from your action # For example: self.assertEquals({"success": True}, results) self.assertEquals({}, results) def test_update_agent(self): self.fail("Unimplemented Test Case")
true
true
f72c80b9bc4510e5476205c3adf1bfd5dea678af
1,931
py
Python
model-optimizer/extensions/front/onnx/detectionoutput_ext.py
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
2
2020-11-18T14:14:06.000Z
2020-11-28T04:55:57.000Z
model-optimizer/extensions/front/onnx/detectionoutput_ext.py
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
30
2020-11-13T11:44:07.000Z
2022-02-21T13:03:16.000Z
model-optimizer/extensions/front/onnx/detectionoutput_ext.py
mmakridi/openvino
769bb7709597c14debdaa356dd60c5a78bdfa97e
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
""" Copyright (C) 2018-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from math import log import numpy as np from extensions.ops.detectionoutput_onnx import ExperimentalDetectronDetectionOutput from mo.front.extractor import FrontExtractorOp from mo.front.onnx.extractors.utils import onnx_attr class ExperimentalDetectronDetectionOutputFrontExtractor(FrontExtractorOp): op = 'ExperimentalDetectronDetectionOutput' enabled = True @classmethod def extract(cls, node): attrs = dict(class_agnostic_box_regression=onnx_attr(node, 'class_agnostic_box_regression', 'i', 0), max_detections_per_image=onnx_attr(node, 'max_detections_per_image', 'i', 100), nms_threshold=onnx_attr(node, 'nms_threshold', 'f', 0.5), num_classes=onnx_attr(node, 'num_classes', 'i', 81), post_nms_count=onnx_attr(node, 'post_nms_count', 'i', 2000), score_threshold=onnx_attr(node, 'score_threshold', 'f', 0.05), max_delta_log_wh=onnx_attr(node, 'max_delta_log_wh', 'f', log(1000. / 16.)), deltas_weights=np.array(onnx_attr(node, 'deltas_weights', 'floats', [10., 10., 5., 5.]), dtype=np.float32) ) ExperimentalDetectronDetectionOutput.update_node_stat(node, attrs) return cls.enabled
43.886364
109
0.684619
from math import log import numpy as np from extensions.ops.detectionoutput_onnx import ExperimentalDetectronDetectionOutput from mo.front.extractor import FrontExtractorOp from mo.front.onnx.extractors.utils import onnx_attr class ExperimentalDetectronDetectionOutputFrontExtractor(FrontExtractorOp): op = 'ExperimentalDetectronDetectionOutput' enabled = True @classmethod def extract(cls, node): attrs = dict(class_agnostic_box_regression=onnx_attr(node, 'class_agnostic_box_regression', 'i', 0), max_detections_per_image=onnx_attr(node, 'max_detections_per_image', 'i', 100), nms_threshold=onnx_attr(node, 'nms_threshold', 'f', 0.5), num_classes=onnx_attr(node, 'num_classes', 'i', 81), post_nms_count=onnx_attr(node, 'post_nms_count', 'i', 2000), score_threshold=onnx_attr(node, 'score_threshold', 'f', 0.05), max_delta_log_wh=onnx_attr(node, 'max_delta_log_wh', 'f', log(1000. / 16.)), deltas_weights=np.array(onnx_attr(node, 'deltas_weights', 'floats', [10., 10., 5., 5.]), dtype=np.float32) ) ExperimentalDetectronDetectionOutput.update_node_stat(node, attrs) return cls.enabled
true
true
f72c811a9b903e14fbd5d11e5e45b9449c6237b3
2,159
py
Python
test/chemistry/test_driver_gaussian_extra.py
hushaohan/aqua
8512bc6ce246a8b3cca1e5edb1703b6885aa7c5d
[ "Apache-2.0" ]
2
2020-06-29T16:08:12.000Z
2020-08-07T22:42:13.000Z
test/chemistry/test_driver_gaussian_extra.py
hushaohan/aqua
8512bc6ce246a8b3cca1e5edb1703b6885aa7c5d
[ "Apache-2.0" ]
null
null
null
test/chemistry/test_driver_gaussian_extra.py
hushaohan/aqua
8512bc6ce246a8b3cca1e5edb1703b6885aa7c5d
[ "Apache-2.0" ]
1
2022-01-25T07:09:10.000Z
2022-01-25T07:09:10.000Z
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test Driver Gaussian internals - does not require Gaussian installed """ import unittest from test.chemistry import QiskitChemistryTestCase from qiskit.chemistry.drivers import GaussianDriver # We need to have an instance so we can test function but constructor calls # an internal method to check G16 installed. We need to replace that with # the following dummy for things to work and we do it for each test so the # class ends up as it was def _check_valid(): pass class TestDriverGaussianExtra(QiskitChemistryTestCase): """Gaussian Driver extra tests for driver specifics, errors etc """ def setUp(self): super().setUp() self.good_check = GaussianDriver._check_valid GaussianDriver._check_valid = _check_valid # We can now create a driver without the installed (check valid) test failing def tearDown(self): GaussianDriver._check_valid = self.good_check def test_cfg_augment(self): """ test input configuration augmentation """ cfg = '# rhf/sto-3g scf(conventional)\n\n' \ 'h2 molecule\n\n0 1\nH 0.0 0.0 0.0\nH 0.0 0.0 0.735\n\n' g16 = GaussianDriver(cfg) aug_cfg = g16._augment_config("mymatfile.mat", cfg) expected = '# rhf/sto-3g scf(conventional)\n' \ '# Window=Full Int=NoRaff Symm=(NoInt,None)' \ ' output=(matrix,i4labels,mo2el) tran=full\n\n' \ 'h2 molecule\n\n0 1\nH 0.0 0.0 0.0\nH 0.0 0.0 0.735' \ '\n\nmymatfile.mat\n\n' self.assertEqual(aug_cfg, expected) if __name__ == '__main__': unittest.main()
36.59322
85
0.672534
import unittest from test.chemistry import QiskitChemistryTestCase from qiskit.chemistry.drivers import GaussianDriver def _check_valid(): pass class TestDriverGaussianExtra(QiskitChemistryTestCase): def setUp(self): super().setUp() self.good_check = GaussianDriver._check_valid GaussianDriver._check_valid = _check_valid def tearDown(self): GaussianDriver._check_valid = self.good_check def test_cfg_augment(self): cfg = '# rhf/sto-3g scf(conventional)\n\n' \ 'h2 molecule\n\n0 1\nH 0.0 0.0 0.0\nH 0.0 0.0 0.735\n\n' g16 = GaussianDriver(cfg) aug_cfg = g16._augment_config("mymatfile.mat", cfg) expected = '# rhf/sto-3g scf(conventional)\n' \ '# Window=Full Int=NoRaff Symm=(NoInt,None)' \ ' output=(matrix,i4labels,mo2el) tran=full\n\n' \ 'h2 molecule\n\n0 1\nH 0.0 0.0 0.0\nH 0.0 0.0 0.735' \ '\n\nmymatfile.mat\n\n' self.assertEqual(aug_cfg, expected) if __name__ == '__main__': unittest.main()
true
true
f72c82f4acdaefe35bcc5d195dbe520974fda99d
1,269
py
Python
qiskit_nature/algorithms/excited_states_solvers/__init__.py
divshacker/qiskit-nature
08f6dcec5e4ac8c08f5b84e764ee78cc3d12facb
[ "Apache-2.0" ]
132
2021-01-28T14:51:11.000Z
2022-03-25T21:10:47.000Z
qiskit_nature/algorithms/excited_states_solvers/__init__.py
divshacker/qiskit-nature
08f6dcec5e4ac8c08f5b84e764ee78cc3d12facb
[ "Apache-2.0" ]
449
2021-01-28T19:57:43.000Z
2022-03-31T17:01:50.000Z
qiskit_nature/algorithms/excited_states_solvers/__init__.py
divshacker/qiskit-nature
08f6dcec5e4ac8c08f5b84e764ee78cc3d12facb
[ "Apache-2.0" ]
109
2021-01-28T13:17:46.000Z
2022-03-30T23:53:39.000Z
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Excited State Solving Algorithms (:mod:`qiskit_nature.algorithms.excited_states_solvers`) ========================================================================================= .. currentmodule:: qiskit_nature.algorithms.excited_states_solvers .. autosummary:: :toctree: ../stubs/ eigensolver_factories .. autosummary:: :toctree: ../stubs/ :nosignatures: ExcitedStatesEigensolver QEOM """ from .excited_states_solver import ExcitedStatesSolver from .qeom import QEOM from .eigensolver_factories import EigensolverFactory, NumPyEigensolverFactory from .excited_states_eigensolver import ExcitedStatesEigensolver __all__ = [ "ExcitedStatesSolver", "ExcitedStatesEigensolver", "EigensolverFactory", "NumPyEigensolverFactory", "QEOM", ]
28.840909
89
0.711584
from .excited_states_solver import ExcitedStatesSolver from .qeom import QEOM from .eigensolver_factories import EigensolverFactory, NumPyEigensolverFactory from .excited_states_eigensolver import ExcitedStatesEigensolver __all__ = [ "ExcitedStatesSolver", "ExcitedStatesEigensolver", "EigensolverFactory", "NumPyEigensolverFactory", "QEOM", ]
true
true
f72c838e66c47527c0a178012ed8acbdbcfe18e4
827
gyp
Python
ui/aura_extra/aura_extra.gyp
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/aura_extra/aura_extra.gyp
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/aura_extra/aura_extra.gyp
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { # GN version: //ui/aura_extra 'target_name': 'aura_extra', 'type': '<(component)', 'dependencies': [ '../../base/base.gyp:base', '../../skia/skia.gyp:skia', '../aura/aura.gyp:aura', '../base/ui_base.gyp:ui_base', '../events/events.gyp:events', '../gfx/gfx.gyp:gfx', '../gfx/gfx.gyp:gfx_geometry', ], 'defines': [ 'AURA_EXTRA_IMPLEMENTATION', ], 'sources': [ 'aura_extra_export.h', 'image_window_delegate.cc', 'image_window_delegate.h', ], }, ], }
24.323529
72
0.53688
{ 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'aura_extra', 'type': '<(component)', 'dependencies': [ '../../base/base.gyp:base', '../../skia/skia.gyp:skia', '../aura/aura.gyp:aura', '../base/ui_base.gyp:ui_base', '../events/events.gyp:events', '../gfx/gfx.gyp:gfx', '../gfx/gfx.gyp:gfx_geometry', ], 'defines': [ 'AURA_EXTRA_IMPLEMENTATION', ], 'sources': [ 'aura_extra_export.h', 'image_window_delegate.cc', 'image_window_delegate.h', ], }, ], }
true
true
f72c844451481add20eff334fb82624c5d7efbe7
1,662
py
Python
lab-05-1-logistic_regression.py
KANG91/Deep_Learning
e3e9de769ab835215d0ebeee79ff869afbe64ebf
[ "MIT" ]
null
null
null
lab-05-1-logistic_regression.py
KANG91/Deep_Learning
e3e9de769ab835215d0ebeee79ff869afbe64ebf
[ "MIT" ]
null
null
null
lab-05-1-logistic_regression.py
KANG91/Deep_Learning
e3e9de769ab835215d0ebeee79ff869afbe64ebf
[ "MIT" ]
null
null
null
# Lab 5 Logistic Regression Classifier import tensorflow as tf tf.set_random_seed(777) # for reproducibility x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]] y_data = [[0], [0], [0], [1], [1], [1]] # placeholders for a tensor that will be always fed. X = tf.placeholder(tf.float32, shape=[None, 2]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([2, 1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') # Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W))) hypothesis = tf.sigmoid(tf.matmul(X, W) + b) # Cost function cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis)) train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) # Accuracy computation # True if hypothesis>0.5 else False predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32) accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32)) # Launch graph with tf.Session() as sess: # Initialize TensorFlow variables sess.run(tf.global_variables_initializer()) feed = {X: x_data, Y: y_data} for step in range(10001): sess.run(train, feed_dict=feed) if step % 200 == 0: print(step, sess.run(cost, feed_dict=feed), sess.run(W)) # Accuracy report h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict=feed) print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a) ''' Hypothesis: [[ 0.03074029] [ 0.15884677] [ 0.30486736] [ 0.78138196] [ 0.93957496] [ 0.98016882]] Correct (Y): [[ 0.] [ 0.] [ 0.] [ 1.] [ 1.] [ 1.]] Accuracy: 1.0 '''
28.169492
76
0.628159
import tensorflow as tf tf.set_random_seed(777) x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]] y_data = [[0], [0], [0], [1], [1], [1]] X = tf.placeholder(tf.float32, shape=[None, 2]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([2, 1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') hypothesis = tf.sigmoid(tf.matmul(X, W) + b) cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis)) train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32) accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) feed = {X: x_data, Y: y_data} for step in range(10001): sess.run(train, feed_dict=feed) if step % 200 == 0: print(step, sess.run(cost, feed_dict=feed), sess.run(W)) h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict=feed) print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)
true
true
f72c8477a6936f3991993793141885a0bb21af12
4,436
py
Python
tests/unit/models/physics/MeniscusTest.py
edgargmartinez/OpenPNM
c68745993b3e9895f53938164a9cf6305500748e
[ "MIT" ]
3
2019-07-05T22:07:21.000Z
2019-07-05T22:07:30.000Z
tests/unit/models/physics/MeniscusTest.py
edgargmartinez/OpenPNM
c68745993b3e9895f53938164a9cf6305500748e
[ "MIT" ]
null
null
null
tests/unit/models/physics/MeniscusTest.py
edgargmartinez/OpenPNM
c68745993b3e9895f53938164a9cf6305500748e
[ "MIT" ]
null
null
null
import openpnm as op import openpnm.models.physics as pm import scipy as sp class MeniscusTest: def setup_class(self): sp.random.seed(1) self.net = op.network.Cubic(shape=[5, 1, 5], spacing=5e-5) self.geo = op.geometry.StickAndBall(network=self.net, pores=self.net.pores(), throats=self.net.throats()) self.phase = op.phases.Water(network=self.net) self.phys = op.physics.Standard(network=self.net, phase=self.phase, geometry=self.geo) def test_toroidal_touch(self): phys = self.phys r_tor = 1e-6 self.geo['throat.touch_length'] = 2e-6 phys.add_model(propname='throat.tor_max', model=pm.meniscus.purcell, mode='max', r_toroid=r_tor) phys.add_model(propname='throat.tor_touch', model=pm.meniscus.purcell, mode='touch', r_toroid=r_tor) assert sp.any(phys['throat.tor_touch'] < phys['throat.tor_max']) def test_sinusoidal_touch(self): phys = self.phys self.geo['throat.amplitude'] = 5e-6 self.geo['throat.touch_length'] = 1e-6 phys.add_model(propname='throat.sin_pressure_max', model=pm.meniscus.sinusoidal, mode='max') phys.add_model(propname='throat.sin_pressure_touch', model=pm.meniscus.sinusoidal, mode='touch') h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 assert sp.any((phys['throat.sin_pressure_touch'] < phys['throat.sin_pressure_max'])) def test_sinusoidal(self): phys = self.phys self.geo['throat.amplitude'] = 5e-6 phys.add_model(propname='throat.sin_pressure', model=pm.meniscus.sinusoidal, mode='max') phys.add_model(propname='throat.sin_meniscus', model=pm.meniscus.sinusoidal, mode='men', target_Pc=5000) h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 def test_toroidal(self): phys = self.phys r_tor = 1e-6 phys.add_model(propname='throat.purcell_pressure', model=pm.capillary_pressure.purcell, r_toroid=r_tor) phys.add_model(propname='throat.tor_pressure', model=pm.meniscus.purcell, mode='max', r_toroid=r_tor, num_points=1000) phys.add_model(propname='throat.tor_meniscus', model=pm.meniscus.purcell, mode='men', r_toroid=r_tor, target_Pc=5000) a = sp.around(phys['throat.purcell_pressure'], 10) b = sp.around(phys['throat.tor_pressure'], 10) assert sp.allclose(a, b) h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 def test_general_toroidal(self): phys = self.phys r_tor = 1e-6 phys.add_model(propname='throat.purcell_pressure', model=pm.capillary_pressure.purcell, r_toroid=r_tor) phys['throat.scale_a'] = r_tor phys['throat.scale_b'] = r_tor phys.add_model(propname='throat.general_pressure', model=pm.meniscus.general_toroidal, mode='max', num_points=1000) a = sp.around(phys['throat.purcell_pressure'], 10) b = sp.around(phys['throat.general_pressure'], 10) assert sp.allclose(a, b) h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 if __name__ == '__main__': t = MeniscusTest() self = t t.setup_class() for item in t.__dir__(): if item.startswith('test'): print('running test: '+item) t.__getattribute__(item)()
37.277311
72
0.511046
import openpnm as op import openpnm.models.physics as pm import scipy as sp class MeniscusTest: def setup_class(self): sp.random.seed(1) self.net = op.network.Cubic(shape=[5, 1, 5], spacing=5e-5) self.geo = op.geometry.StickAndBall(network=self.net, pores=self.net.pores(), throats=self.net.throats()) self.phase = op.phases.Water(network=self.net) self.phys = op.physics.Standard(network=self.net, phase=self.phase, geometry=self.geo) def test_toroidal_touch(self): phys = self.phys r_tor = 1e-6 self.geo['throat.touch_length'] = 2e-6 phys.add_model(propname='throat.tor_max', model=pm.meniscus.purcell, mode='max', r_toroid=r_tor) phys.add_model(propname='throat.tor_touch', model=pm.meniscus.purcell, mode='touch', r_toroid=r_tor) assert sp.any(phys['throat.tor_touch'] < phys['throat.tor_max']) def test_sinusoidal_touch(self): phys = self.phys self.geo['throat.amplitude'] = 5e-6 self.geo['throat.touch_length'] = 1e-6 phys.add_model(propname='throat.sin_pressure_max', model=pm.meniscus.sinusoidal, mode='max') phys.add_model(propname='throat.sin_pressure_touch', model=pm.meniscus.sinusoidal, mode='touch') h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 assert sp.any((phys['throat.sin_pressure_touch'] < phys['throat.sin_pressure_max'])) def test_sinusoidal(self): phys = self.phys self.geo['throat.amplitude'] = 5e-6 phys.add_model(propname='throat.sin_pressure', model=pm.meniscus.sinusoidal, mode='max') phys.add_model(propname='throat.sin_meniscus', model=pm.meniscus.sinusoidal, mode='men', target_Pc=5000) h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 def test_toroidal(self): phys = self.phys r_tor = 1e-6 phys.add_model(propname='throat.purcell_pressure', model=pm.capillary_pressure.purcell, r_toroid=r_tor) phys.add_model(propname='throat.tor_pressure', model=pm.meniscus.purcell, mode='max', r_toroid=r_tor, num_points=1000) phys.add_model(propname='throat.tor_meniscus', model=pm.meniscus.purcell, mode='men', r_toroid=r_tor, target_Pc=5000) a = sp.around(phys['throat.purcell_pressure'], 10) b = sp.around(phys['throat.tor_pressure'], 10) assert sp.allclose(a, b) h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 def test_general_toroidal(self): phys = self.phys r_tor = 1e-6 phys.add_model(propname='throat.purcell_pressure', model=pm.capillary_pressure.purcell, r_toroid=r_tor) phys['throat.scale_a'] = r_tor phys['throat.scale_b'] = r_tor phys.add_model(propname='throat.general_pressure', model=pm.meniscus.general_toroidal, mode='max', num_points=1000) a = sp.around(phys['throat.purcell_pressure'], 10) b = sp.around(phys['throat.general_pressure'], 10) assert sp.allclose(a, b) h = phys.check_data_health() for check in h.values(): if len(check) > 0: assert 1 == 2 if __name__ == '__main__': t = MeniscusTest() self = t t.setup_class() for item in t.__dir__(): if item.startswith('test'): print('running test: '+item) t.__getattribute__(item)()
true
true
f72c85576b8389695f555dc9f2032aaaf2f1f2df
19,881
py
Python
plugins/modules/oci_network_drg.py
LaudateCorpus1/oci-ansible-collection
2b1cd87b4d652a97c1ca752cfc4fdc4bdb37a7e7
[ "Apache-2.0" ]
null
null
null
plugins/modules/oci_network_drg.py
LaudateCorpus1/oci-ansible-collection
2b1cd87b4d652a97c1ca752cfc4fdc4bdb37a7e7
[ "Apache-2.0" ]
null
null
null
plugins/modules/oci_network_drg.py
LaudateCorpus1/oci-ansible-collection
2b1cd87b4d652a97c1ca752cfc4fdc4bdb37a7e7
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_network_drg short_description: Manage a Drg resource in Oracle Cloud Infrastructure description: - This module allows the user to create, update and delete a Drg resource in Oracle Cloud Infrastructure - For I(state=present), creates a new dynamic routing gateway (DRG) in the specified compartment. For more information, see L(Dynamic Routing Gateways (DRGs),https://docs.cloud.oracle.com/iaas/Content/Network/Tasks/managingDRGs.htm). - For the purposes of access control, you must provide the L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment where you want the DRG to reside. Notice that the DRG doesn't have to be in the same compartment as the VCN, the DRG attachment, or other Networking Service components. If you're not sure which compartment to use, put the DRG in the same compartment as the VCN. For more information about compartments and access control, see L(Overview of the IAM Service,https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/overview.htm). For information about OCIDs, see L(Resource Identifiers,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm). - "You may optionally specify a *display name* for the DRG, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information." - "This resource has the following action operations in the M(oracle.oci.oci_network_drg_actions) module: change_compartment, get_all_drg_attachments, upgrade." version_added: "2.9.0" author: Oracle (@oracle) options: compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment to contain the DRG. - Required for create using I(state=present). - Required for update when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set. - Required for delete when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set. type: str defined_tags: description: - Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`" - This parameter is updatable. type: dict display_name: description: - A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. - Required for create, update, delete when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set. - This parameter is updatable when C(OCI_USE_NAME_AS_IDENTIFIER) is not set. type: str aliases: ["name"] freeform_tags: description: - Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Department\\": \\"Finance\\"}`" - This parameter is updatable. type: dict drg_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the DRG. - Required for update using I(state=present) when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is not set. - Required for delete using I(state=absent) when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is not set. type: str aliases: ["id"] default_drg_route_tables: description: - "" - This parameter is updatable. type: dict suboptions: vcn: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VCN on creation. - This parameter is updatable. type: str ipsec_tunnel: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table assigned to DRG attachments of type IPSEC_TUNNEL on creation. - This parameter is updatable. type: str virtual_circuit: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VIRTUAL_CIRCUIT on creation. - This parameter is updatable. type: str remote_peering_connection: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type REMOTE_PEERING_CONNECTION on creation. - This parameter is updatable. type: str state: description: - The state of the Drg. - Use I(state=present) to create or update a Drg. - Use I(state=absent) to delete a Drg. type: str required: false default: 'present' choices: ["present", "absent"] extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_creatable_resource, oracle.oci.oracle_wait_options ] """ EXAMPLES = """ - name: Create drg oci_network_drg: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" # optional defined_tags: {'Operations': {'CostCenter': 'US'}} display_name: display_name_example freeform_tags: {'Department': 'Finance'} - name: Update drg oci_network_drg: # required drg_id: "ocid1.drg.oc1..xxxxxxEXAMPLExxxxxx" # optional defined_tags: {'Operations': {'CostCenter': 'US'}} display_name: display_name_example freeform_tags: {'Department': 'Finance'} default_drg_route_tables: # optional vcn: vcn_example ipsec_tunnel: ipsec_tunnel_example virtual_circuit: virtual_circuit_example remote_peering_connection: remote_peering_connection_example - name: Update drg using name (when environment variable OCI_USE_NAME_AS_IDENTIFIER is set) oci_network_drg: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" display_name: display_name_example # optional defined_tags: {'Operations': {'CostCenter': 'US'}} freeform_tags: {'Department': 'Finance'} default_drg_route_tables: # optional vcn: vcn_example ipsec_tunnel: ipsec_tunnel_example virtual_circuit: virtual_circuit_example remote_peering_connection: remote_peering_connection_example - name: Delete drg oci_network_drg: # required drg_id: "ocid1.drg.oc1..xxxxxxEXAMPLExxxxxx" state: absent - name: Delete drg using name (when environment variable OCI_USE_NAME_AS_IDENTIFIER is set) oci_network_drg: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" display_name: display_name_example state: absent """ RETURN = """ drg: description: - Details of the Drg resource acted upon by the current operation returned: on success type: complex contains: compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment containing the DRG. returned: on success type: str sample: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" defined_tags: description: - Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`" returned: on success type: dict sample: {'Operations': {'CostCenter': 'US'}} display_name: description: - A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. returned: on success type: str sample: display_name_example freeform_tags: description: - Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Department\\": \\"Finance\\"}`" returned: on success type: dict sample: {'Department': 'Finance'} id: description: - The DRG's Oracle ID (L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm)). returned: on success type: str sample: "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx" lifecycle_state: description: - The DRG's current state. returned: on success type: str sample: PROVISIONING time_created: description: - The date and time the DRG was created, in the format defined by L(RFC3339,https://tools.ietf.org/html/rfc3339). - "Example: `2016-08-25T21:10:29.600Z`" returned: on success type: str sample: "2013-10-20T19:20:30+01:00" default_drg_route_tables: description: - "" returned: on success type: complex contains: vcn: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VCN on creation. returned: on success type: str sample: vcn_example ipsec_tunnel: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table assigned to DRG attachments of type IPSEC_TUNNEL on creation. returned: on success type: str sample: ipsec_tunnel_example virtual_circuit: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VIRTUAL_CIRCUIT on creation. returned: on success type: str sample: virtual_circuit_example remote_peering_connection: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type REMOTE_PEERING_CONNECTION on creation. returned: on success type: str sample: remote_peering_connection_example default_export_drg_route_distribution_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of this DRG's default export route distribution for the DRG attachments. returned: on success type: str sample: "ocid1.defaultexportdrgroutedistribution.oc1..xxxxxxEXAMPLExxxxxx" sample: { "compartment_id": "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx", "defined_tags": {'Operations': {'CostCenter': 'US'}}, "display_name": "display_name_example", "freeform_tags": {'Department': 'Finance'}, "id": "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx", "lifecycle_state": "PROVISIONING", "time_created": "2013-10-20T19:20:30+01:00", "default_drg_route_tables": { "vcn": "vcn_example", "ipsec_tunnel": "ipsec_tunnel_example", "virtual_circuit": "virtual_circuit_example", "remote_peering_connection": "remote_peering_connection_example" }, "default_export_drg_route_distribution_id": "ocid1.defaultexportdrgroutedistribution.oc1..xxxxxxEXAMPLExxxxxx" } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import ( oci_common_utils, oci_wait_utils, ) from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceHelperBase, get_custom_class, ) try: from oci.core import VirtualNetworkClient from oci.core.models import CreateDrgDetails from oci.core.models import UpdateDrgDetails HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class DrgHelperGen(OCIResourceHelperBase): """Supported operations: create, update, get, list and delete""" def get_possible_entity_types(self): return super(DrgHelperGen, self).get_possible_entity_types() + [ "drg", "drgs", "coredrg", "coredrgs", "drgresource", "drgsresource", "core", ] def get_module_resource_id_param(self): return "drg_id" def get_module_resource_id(self): return self.module.params.get("drg_id") def get_get_fn(self): return self.client.get_drg def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_drg, drg_id=self.module.params.get("drg_id"), ) def get_required_kwargs_for_list(self): required_list_method_params = [ "compartment_id", ] return dict( (param, self.module.params[param]) for param in required_list_method_params ) def get_optional_kwargs_for_list(self): return dict() def list_resources(self): required_kwargs = self.get_required_kwargs_for_list() optional_kwargs = self.get_optional_kwargs_for_list() kwargs = oci_common_utils.merge_dicts(required_kwargs, optional_kwargs) return oci_common_utils.list_all_resources(self.client.list_drgs, **kwargs) def get_create_model_class(self): return CreateDrgDetails def create_resource(self): create_details = self.get_create_model() return oci_wait_utils.call_and_wait( call_fn=self.client.create_drg, call_fn_args=(), call_fn_kwargs=dict(create_drg_details=create_details,), waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY, operation=oci_common_utils.CREATE_OPERATION_KEY, waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_wait_for_states_for_operation( oci_common_utils.CREATE_OPERATION_KEY, ), ) def get_update_model_class(self): return UpdateDrgDetails def update_resource(self): update_details = self.get_update_model() return oci_wait_utils.call_and_wait( call_fn=self.client.update_drg, call_fn_args=(), call_fn_kwargs=dict( drg_id=self.module.params.get("drg_id"), update_drg_details=update_details, ), waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY, operation=oci_common_utils.UPDATE_OPERATION_KEY, waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_wait_for_states_for_operation( oci_common_utils.UPDATE_OPERATION_KEY, ), ) def delete_resource(self): return oci_wait_utils.call_and_wait( call_fn=self.client.delete_drg, call_fn_args=(), call_fn_kwargs=dict(drg_id=self.module.params.get("drg_id"),), waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY, operation=oci_common_utils.DELETE_OPERATION_KEY, waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_wait_for_states_for_operation( oci_common_utils.DELETE_OPERATION_KEY, ), ) DrgHelperCustom = get_custom_class("DrgHelperCustom") class ResourceHelper(DrgHelperCustom, DrgHelperGen): pass def main(): module_args = oci_common_utils.get_common_arg_spec( supports_create=True, supports_wait=True ) module_args.update( dict( compartment_id=dict(type="str"), defined_tags=dict(type="dict"), display_name=dict(aliases=["name"], type="str"), freeform_tags=dict(type="dict"), drg_id=dict(aliases=["id"], type="str"), default_drg_route_tables=dict( type="dict", options=dict( vcn=dict(type="str"), ipsec_tunnel=dict(type="str"), virtual_circuit=dict(type="str"), remote_peering_connection=dict(type="str"), ), ), state=dict(type="str", default="present", choices=["present", "absent"]), ) ) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_helper = ResourceHelper( module=module, resource_type="drg", service_client_class=VirtualNetworkClient, namespace="core", ) result = dict(changed=False) if resource_helper.is_delete_using_name(): result = resource_helper.delete_using_name() elif resource_helper.is_delete(): result = resource_helper.delete() elif resource_helper.is_update_using_name(): result = resource_helper.update_using_name() elif resource_helper.is_update(): result = resource_helper.update() elif resource_helper.is_create(): result = resource_helper.create() module.exit_json(**result) if __name__ == "__main__": main()
41.076446
160
0.632866
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_network_drg short_description: Manage a Drg resource in Oracle Cloud Infrastructure description: - This module allows the user to create, update and delete a Drg resource in Oracle Cloud Infrastructure - For I(state=present), creates a new dynamic routing gateway (DRG) in the specified compartment. For more information, see L(Dynamic Routing Gateways (DRGs),https://docs.cloud.oracle.com/iaas/Content/Network/Tasks/managingDRGs.htm). - For the purposes of access control, you must provide the L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment where you want the DRG to reside. Notice that the DRG doesn't have to be in the same compartment as the VCN, the DRG attachment, or other Networking Service components. If you're not sure which compartment to use, put the DRG in the same compartment as the VCN. For more information about compartments and access control, see L(Overview of the IAM Service,https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/overview.htm). For information about OCIDs, see L(Resource Identifiers,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm). - "You may optionally specify a *display name* for the DRG, otherwise a default is provided. It does not have to be unique, and you can change it. Avoid entering confidential information." - "This resource has the following action operations in the M(oracle.oci.oci_network_drg_actions) module: change_compartment, get_all_drg_attachments, upgrade." version_added: "2.9.0" author: Oracle (@oracle) options: compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment to contain the DRG. - Required for create using I(state=present). - Required for update when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set. - Required for delete when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set. type: str defined_tags: description: - Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`" - This parameter is updatable. type: dict display_name: description: - A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. - Required for create, update, delete when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set. - This parameter is updatable when C(OCI_USE_NAME_AS_IDENTIFIER) is not set. type: str aliases: ["name"] freeform_tags: description: - Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Department\\": \\"Finance\\"}`" - This parameter is updatable. type: dict drg_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the DRG. - Required for update using I(state=present) when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is not set. - Required for delete using I(state=absent) when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is not set. type: str aliases: ["id"] default_drg_route_tables: description: - "" - This parameter is updatable. type: dict suboptions: vcn: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VCN on creation. - This parameter is updatable. type: str ipsec_tunnel: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table assigned to DRG attachments of type IPSEC_TUNNEL on creation. - This parameter is updatable. type: str virtual_circuit: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VIRTUAL_CIRCUIT on creation. - This parameter is updatable. type: str remote_peering_connection: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type REMOTE_PEERING_CONNECTION on creation. - This parameter is updatable. type: str state: description: - The state of the Drg. - Use I(state=present) to create or update a Drg. - Use I(state=absent) to delete a Drg. type: str required: false default: 'present' choices: ["present", "absent"] extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_creatable_resource, oracle.oci.oracle_wait_options ] """ EXAMPLES = """ - name: Create drg oci_network_drg: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" # optional defined_tags: {'Operations': {'CostCenter': 'US'}} display_name: display_name_example freeform_tags: {'Department': 'Finance'} - name: Update drg oci_network_drg: # required drg_id: "ocid1.drg.oc1..xxxxxxEXAMPLExxxxxx" # optional defined_tags: {'Operations': {'CostCenter': 'US'}} display_name: display_name_example freeform_tags: {'Department': 'Finance'} default_drg_route_tables: # optional vcn: vcn_example ipsec_tunnel: ipsec_tunnel_example virtual_circuit: virtual_circuit_example remote_peering_connection: remote_peering_connection_example - name: Update drg using name (when environment variable OCI_USE_NAME_AS_IDENTIFIER is set) oci_network_drg: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" display_name: display_name_example # optional defined_tags: {'Operations': {'CostCenter': 'US'}} freeform_tags: {'Department': 'Finance'} default_drg_route_tables: # optional vcn: vcn_example ipsec_tunnel: ipsec_tunnel_example virtual_circuit: virtual_circuit_example remote_peering_connection: remote_peering_connection_example - name: Delete drg oci_network_drg: # required drg_id: "ocid1.drg.oc1..xxxxxxEXAMPLExxxxxx" state: absent - name: Delete drg using name (when environment variable OCI_USE_NAME_AS_IDENTIFIER is set) oci_network_drg: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" display_name: display_name_example state: absent """ RETURN = """ drg: description: - Details of the Drg resource acted upon by the current operation returned: on success type: complex contains: compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment containing the DRG. returned: on success type: str sample: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" defined_tags: description: - Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`" returned: on success type: dict sample: {'Operations': {'CostCenter': 'US'}} display_name: description: - A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. returned: on success type: str sample: display_name_example freeform_tags: description: - Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Department\\": \\"Finance\\"}`" returned: on success type: dict sample: {'Department': 'Finance'} id: description: - The DRG's Oracle ID (L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm)). returned: on success type: str sample: "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx" lifecycle_state: description: - The DRG's current state. returned: on success type: str sample: PROVISIONING time_created: description: - The date and time the DRG was created, in the format defined by L(RFC3339,https://tools.ietf.org/html/rfc3339). - "Example: `2016-08-25T21:10:29.600Z`" returned: on success type: str sample: "2013-10-20T19:20:30+01:00" default_drg_route_tables: description: - "" returned: on success type: complex contains: vcn: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VCN on creation. returned: on success type: str sample: vcn_example ipsec_tunnel: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table assigned to DRG attachments of type IPSEC_TUNNEL on creation. returned: on success type: str sample: ipsec_tunnel_example virtual_circuit: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type VIRTUAL_CIRCUIT on creation. returned: on success type: str sample: virtual_circuit_example remote_peering_connection: description: - The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the default DRG route table to be assigned to DRG attachments of type REMOTE_PEERING_CONNECTION on creation. returned: on success type: str sample: remote_peering_connection_example default_export_drg_route_distribution_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of this DRG's default export route distribution for the DRG attachments. returned: on success type: str sample: "ocid1.defaultexportdrgroutedistribution.oc1..xxxxxxEXAMPLExxxxxx" sample: { "compartment_id": "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx", "defined_tags": {'Operations': {'CostCenter': 'US'}}, "display_name": "display_name_example", "freeform_tags": {'Department': 'Finance'}, "id": "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx", "lifecycle_state": "PROVISIONING", "time_created": "2013-10-20T19:20:30+01:00", "default_drg_route_tables": { "vcn": "vcn_example", "ipsec_tunnel": "ipsec_tunnel_example", "virtual_circuit": "virtual_circuit_example", "remote_peering_connection": "remote_peering_connection_example" }, "default_export_drg_route_distribution_id": "ocid1.defaultexportdrgroutedistribution.oc1..xxxxxxEXAMPLExxxxxx" } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import ( oci_common_utils, oci_wait_utils, ) from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceHelperBase, get_custom_class, ) try: from oci.core import VirtualNetworkClient from oci.core.models import CreateDrgDetails from oci.core.models import UpdateDrgDetails HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class DrgHelperGen(OCIResourceHelperBase): def get_possible_entity_types(self): return super(DrgHelperGen, self).get_possible_entity_types() + [ "drg", "drgs", "coredrg", "coredrgs", "drgresource", "drgsresource", "core", ] def get_module_resource_id_param(self): return "drg_id" def get_module_resource_id(self): return self.module.params.get("drg_id") def get_get_fn(self): return self.client.get_drg def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_drg, drg_id=self.module.params.get("drg_id"), ) def get_required_kwargs_for_list(self): required_list_method_params = [ "compartment_id", ] return dict( (param, self.module.params[param]) for param in required_list_method_params ) def get_optional_kwargs_for_list(self): return dict() def list_resources(self): required_kwargs = self.get_required_kwargs_for_list() optional_kwargs = self.get_optional_kwargs_for_list() kwargs = oci_common_utils.merge_dicts(required_kwargs, optional_kwargs) return oci_common_utils.list_all_resources(self.client.list_drgs, **kwargs) def get_create_model_class(self): return CreateDrgDetails def create_resource(self): create_details = self.get_create_model() return oci_wait_utils.call_and_wait( call_fn=self.client.create_drg, call_fn_args=(), call_fn_kwargs=dict(create_drg_details=create_details,), waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY, operation=oci_common_utils.CREATE_OPERATION_KEY, waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_wait_for_states_for_operation( oci_common_utils.CREATE_OPERATION_KEY, ), ) def get_update_model_class(self): return UpdateDrgDetails def update_resource(self): update_details = self.get_update_model() return oci_wait_utils.call_and_wait( call_fn=self.client.update_drg, call_fn_args=(), call_fn_kwargs=dict( drg_id=self.module.params.get("drg_id"), update_drg_details=update_details, ), waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY, operation=oci_common_utils.UPDATE_OPERATION_KEY, waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_wait_for_states_for_operation( oci_common_utils.UPDATE_OPERATION_KEY, ), ) def delete_resource(self): return oci_wait_utils.call_and_wait( call_fn=self.client.delete_drg, call_fn_args=(), call_fn_kwargs=dict(drg_id=self.module.params.get("drg_id"),), waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY, operation=oci_common_utils.DELETE_OPERATION_KEY, waiter_client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_wait_for_states_for_operation( oci_common_utils.DELETE_OPERATION_KEY, ), ) DrgHelperCustom = get_custom_class("DrgHelperCustom") class ResourceHelper(DrgHelperCustom, DrgHelperGen): pass def main(): module_args = oci_common_utils.get_common_arg_spec( supports_create=True, supports_wait=True ) module_args.update( dict( compartment_id=dict(type="str"), defined_tags=dict(type="dict"), display_name=dict(aliases=["name"], type="str"), freeform_tags=dict(type="dict"), drg_id=dict(aliases=["id"], type="str"), default_drg_route_tables=dict( type="dict", options=dict( vcn=dict(type="str"), ipsec_tunnel=dict(type="str"), virtual_circuit=dict(type="str"), remote_peering_connection=dict(type="str"), ), ), state=dict(type="str", default="present", choices=["present", "absent"]), ) ) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_helper = ResourceHelper( module=module, resource_type="drg", service_client_class=VirtualNetworkClient, namespace="core", ) result = dict(changed=False) if resource_helper.is_delete_using_name(): result = resource_helper.delete_using_name() elif resource_helper.is_delete(): result = resource_helper.delete() elif resource_helper.is_update_using_name(): result = resource_helper.update_using_name() elif resource_helper.is_update(): result = resource_helper.update() elif resource_helper.is_create(): result = resource_helper.create() module.exit_json(**result) if __name__ == "__main__": main()
true
true
f72c8559dfd7a6014d9c69e946707586ad068801
2,817
py
Python
src/dashboard/pages/visualization/visualization.py
ddlatumalea/disease_and_life
aa8c84fdd4a0b41bc0ee275538ac70a362eb26ba
[ "Apache-2.0" ]
null
null
null
src/dashboard/pages/visualization/visualization.py
ddlatumalea/disease_and_life
aa8c84fdd4a0b41bc0ee275538ac70a362eb26ba
[ "Apache-2.0" ]
null
null
null
src/dashboard/pages/visualization/visualization.py
ddlatumalea/disease_and_life
aa8c84fdd4a0b41bc0ee275538ac70a362eb26ba
[ "Apache-2.0" ]
null
null
null
from pathlib import Path import panel as pn import pandas as pd import plotly.express as px from models.pages import Page from models.utils.paths import get_prepared_data_path, get_standardized_data_file from dashboard.widgets import heatmap PREPARED_DATA_DIR = get_prepared_data_path() PREPARED_DATA_FILE = get_standardized_data_file() COLUMNS = ['non-communicable chronic disease [deaths]', 'cancer [deaths]', 'cardiovascular disease [deaths]', 'diabetes mellitus [deaths]', 'chronic respiratory diseases [deaths]', 'diseases of digestive system [deaths]', 'life expectancy [age]'] def get_correlation_heatmap(df, columns): corr = df[columns].corr() z = corr.values.round(decimals=2) x = corr.index y = corr.index return heatmap(z, x, y, labels=dict(color='Correlation')) def get_line_plot(df, x_col, y_col, index, title, width=500): if width is None: fig = px.line(df, x=x_col, y=y_col, color=index, title=title) return pn.pane.Plotly(fig) else: fig = px.line(df, x=x_col, y=y_col, color=index, title=title, width=width) return pn.pane.Plotly(fig) data = pd.read_csv(Path(PREPARED_DATA_DIR, PREPARED_DATA_FILE)) df = data[data['sex'] == 3] class VisualizationPage(Page): def __init__(self): super().__init__() self.df = df self.checkbutton = pn.widgets.CheckButtonGroup(name='Countries', value=['Netherlands'], options=['Netherlands', 'Japan', 'Canada']) self.pane = pn.Column(self.checkbutton, self.get_plot(self.checkbutton)) self.button = pn.widgets.Button(name='Visualization') self.checkbutton.param.watch(self.update, 'value') def get_plot(self, checkbutton): gspec = pn.GridSpec(ncols=2, nrows=4, width=1200, height=1800) selection = df.loc[df['country'].isin(checkbutton.value)] # life expectancy plot life_exp_plot = pn.pane.Plotly( px.line(selection, x='year', y='life expectancy [age]', color='country', title='life expectancy')) # plots about disease plots = [] for col in COLUMNS[:-1]: plots.append(pn.pane.Plotly( px.line(selection, x='year', y=col, labels={col: 'Deaths per 100.000 people'}, color='country', title=col.replace('[deaths]', '')))) gspec[0, :] = life_exp_plot gspec[1, 0] = plots[0] gspec[1, 1] = plots[1] gspec[2, 0] = plots[2] gspec[2, 1] = plots[3] gspec[3, 0] = plots[4] gspec[3, 1] = plots[5] return gspec def update(self, event): self.pane[1] = self.get_plot(self.checkbutton) def get_contents(self): return self.pane, self.button
32.011364
111
0.624778
from pathlib import Path import panel as pn import pandas as pd import plotly.express as px from models.pages import Page from models.utils.paths import get_prepared_data_path, get_standardized_data_file from dashboard.widgets import heatmap PREPARED_DATA_DIR = get_prepared_data_path() PREPARED_DATA_FILE = get_standardized_data_file() COLUMNS = ['non-communicable chronic disease [deaths]', 'cancer [deaths]', 'cardiovascular disease [deaths]', 'diabetes mellitus [deaths]', 'chronic respiratory diseases [deaths]', 'diseases of digestive system [deaths]', 'life expectancy [age]'] def get_correlation_heatmap(df, columns): corr = df[columns].corr() z = corr.values.round(decimals=2) x = corr.index y = corr.index return heatmap(z, x, y, labels=dict(color='Correlation')) def get_line_plot(df, x_col, y_col, index, title, width=500): if width is None: fig = px.line(df, x=x_col, y=y_col, color=index, title=title) return pn.pane.Plotly(fig) else: fig = px.line(df, x=x_col, y=y_col, color=index, title=title, width=width) return pn.pane.Plotly(fig) data = pd.read_csv(Path(PREPARED_DATA_DIR, PREPARED_DATA_FILE)) df = data[data['sex'] == 3] class VisualizationPage(Page): def __init__(self): super().__init__() self.df = df self.checkbutton = pn.widgets.CheckButtonGroup(name='Countries', value=['Netherlands'], options=['Netherlands', 'Japan', 'Canada']) self.pane = pn.Column(self.checkbutton, self.get_plot(self.checkbutton)) self.button = pn.widgets.Button(name='Visualization') self.checkbutton.param.watch(self.update, 'value') def get_plot(self, checkbutton): gspec = pn.GridSpec(ncols=2, nrows=4, width=1200, height=1800) selection = df.loc[df['country'].isin(checkbutton.value)] life_exp_plot = pn.pane.Plotly( px.line(selection, x='year', y='life expectancy [age]', color='country', title='life expectancy')) plots = [] for col in COLUMNS[:-1]: plots.append(pn.pane.Plotly( px.line(selection, x='year', y=col, labels={col: 'Deaths per 100.000 people'}, color='country', title=col.replace('[deaths]', '')))) gspec[0, :] = life_exp_plot gspec[1, 0] = plots[0] gspec[1, 1] = plots[1] gspec[2, 0] = plots[2] gspec[2, 1] = plots[3] gspec[3, 0] = plots[4] gspec[3, 1] = plots[5] return gspec def update(self, event): self.pane[1] = self.get_plot(self.checkbutton) def get_contents(self): return self.pane, self.button
true
true
f72c85a0942c0540d2abee2d9180bd484b5864a7
6,141
py
Python
main.py
akashrchandran/pokeowo
0b2621494ef56f350239817546b843814fe3448e
[ "MIT" ]
null
null
null
main.py
akashrchandran/pokeowo
0b2621494ef56f350239817546b843814fe3448e
[ "MIT" ]
null
null
null
main.py
akashrchandran/pokeowo
0b2621494ef56f350239817546b843814fe3448e
[ "MIT" ]
null
null
null
import datetime import json import multiprocessing import os import random import re import time import discum version = 'v0.01' config_path = 'data/config.json' logo = f''' ###### ### ### ## ####### ### ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## #### #### ## ## ## # ## ## ## ## ## ## ## ## ## ## ## ####### ## ## ## ## ## ## ## ## ## ## ## ### ### ## ## #### ### ### ## ####### ### ## ## ### ~ Pokétwo Autocatcher {version} ''' num_pokemon = 0 shiny = 0 legendary = 0 mythical = 0 poketwo_id = '716390085896962058' def auto_config(): global user_token, channel_id if not os.path.exists(config_path): with open(config_path, "a") as file: auth_token = input("Enter you Discord auth token: ") channel_id = input("Enter the preferred Channel ID for spamming and catching: ") file.write("{\n") file.write(f' "user_token" : "{auth_token}",\n') file.write(f' "channel_id" : "{channel_id}"\n') file.write("}") os.system('cls' if os.name=='nt' else 'clear') with open(config_path,'r') as file: info = json.loads(file.read()) user_token = info['user_token'] channel_id = info['channel_id'] with open('data/pokemon.txt', 'r', encoding='utf8') as file: pokemon_list = file.read() with open('data/legendary.txt','r') as file: legendary_list = file.read() with open('data/mythical.txt','r') as file: mythical_list = file.read() auto_config() print(logo) bot = discum.Client(token=user_token, log=False) def solve(message): hint = [message[i] for i in range(15, len(message) - 1) if message[i] != '\\'] hint_string = ''.join(hint) return re.findall( '^' + hint_string.replace('_', '.') + '$', pokemon_list, re.MULTILINE ) def spam(): while True: random_number = random.getrandbits(128) bot.sendMessage(channel_id, random_number) intervals = [2.0,2.1,2.2,2.3,2.4,2.5] time.sleep(random.choice(intervals)) def start_spam(): new_process = multiprocessing.Process(target=spam) new_process.start() return new_process def stop(process): process.terminate() def log(string): now = datetime.datetime.now() current_time = now.strftime('%H:%M:%S') print(f'[{current_time}]', string) @bot.gateway.command def on_ready(resp): if resp.event.ready_supplemental: user = bot.gateway.session.user log(f'Logged into account: {user["username"]}#{user["discriminator"]}') @bot.gateway.command def on_message(resp): global spam_process if resp.event.message: m = resp.parsed.auto() if m['channel_id'] == channel_id and m['author']['id'] == poketwo_id: if m['embeds']: embed_title = m['embeds'][0]['title'] if 'wild pokémon has appeared!' in embed_title: stop(spam_process) time.sleep(2) bot.sendMessage(channel_id, '<@716390085896962058> h') elif "Congratulations" in embed_title: embed_content = m['embeds'][0]['description'] if 'now level' in embed_content: stop(spam_process) split = embed_content.split(' ') a = embed_content.count(' ') level = int(split[a].replace('!', '')) if level == 100: #wait will implement in next update pass spam_process = start_spam() else: content = m['content'] if 'The pokémon is ' in content: if len(solve(content)) == 0: log('Pokemon not found.') else: for i in solve(content): stop(spam_process) time.sleep(2) bot.sendMessage(channel_id, f'<@716390085896962058> c {i}') time.sleep(2) spam_process = start_spam() elif 'Congratulations' in content: global shiny global legendary global num_pokemon global mythical num_pokemon += 1 split = content.split(' ') pokemon = split[7].replace('!','') if 'These colors seem unusual...' in content: shiny += 1 log(f'A shiny Pokémon was caught! Pokémon: {pokemon}') log(f'Shiny: {shiny} | Legendary: {legendary} | Mythical: {mythical}') elif re.findall( f'^{pokemon}$', legendary_list, re.MULTILINE ): legendary += 1 log(f'A legendary Pokémon was caught! Pokémon: {pokemon}') log(f'Shiny: {shiny} | Legendary: {legendary} | Mythical: {mythical}') elif re.findall(f'^{pokemon}$', mythical_list, re.MULTILINE): mythical += 1 log(f'A mythical Pokémon was caught! Pokémon: {pokemon}') log(f'Shiny: {shiny} | Legendary: {legendary} | Mythical: {mythical}') else: print(f'Total Pokémon Caught: {num_pokemon}') elif 'human' in content: stop(spam_process) log('Captcha Detected; Autocatcher Paused. Press enter to restart.') input() bot.sendMessage(channel_id, '<@716390085896962058> h') if __name__ == '__main__': print('\nEvent Log:') spam_process = start_spam() bot.gateway.run(auto_reconnect=True)
37.218182
96
0.485752
import datetime import json import multiprocessing import os import random import re import time import discum version = 'v0.01' config_path = 'data/config.json' logo = f''' ###### ### ### ## ####### ### ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## #### #### ## ## ## # ## ## ## ## ## ## ## ## ## ## ## ####### ## ## ## ## ## ## ## ## ## ## ## ### ### ## ## #### ### ### ## ####### ### ## ## ### ~ Pokétwo Autocatcher {version} ''' num_pokemon = 0 shiny = 0 legendary = 0 mythical = 0 poketwo_id = '716390085896962058' def auto_config(): global user_token, channel_id if not os.path.exists(config_path): with open(config_path, "a") as file: auth_token = input("Enter you Discord auth token: ") channel_id = input("Enter the preferred Channel ID for spamming and catching: ") file.write("{\n") file.write(f' "user_token" : "{auth_token}",\n') file.write(f' "channel_id" : "{channel_id}"\n') file.write("}") os.system('cls' if os.name=='nt' else 'clear') with open(config_path,'r') as file: info = json.loads(file.read()) user_token = info['user_token'] channel_id = info['channel_id'] with open('data/pokemon.txt', 'r', encoding='utf8') as file: pokemon_list = file.read() with open('data/legendary.txt','r') as file: legendary_list = file.read() with open('data/mythical.txt','r') as file: mythical_list = file.read() auto_config() print(logo) bot = discum.Client(token=user_token, log=False) def solve(message): hint = [message[i] for i in range(15, len(message) - 1) if message[i] != '\\'] hint_string = ''.join(hint) return re.findall( '^' + hint_string.replace('_', '.') + '$', pokemon_list, re.MULTILINE ) def spam(): while True: random_number = random.getrandbits(128) bot.sendMessage(channel_id, random_number) intervals = [2.0,2.1,2.2,2.3,2.4,2.5] time.sleep(random.choice(intervals)) def start_spam(): new_process = multiprocessing.Process(target=spam) new_process.start() return new_process def stop(process): process.terminate() def log(string): now = datetime.datetime.now() current_time = now.strftime('%H:%M:%S') print(f'[{current_time}]', string) @bot.gateway.command def on_ready(resp): if resp.event.ready_supplemental: user = bot.gateway.session.user log(f'Logged into account: {user["username"]}#{user["discriminator"]}') @bot.gateway.command def on_message(resp): global spam_process if resp.event.message: m = resp.parsed.auto() if m['channel_id'] == channel_id and m['author']['id'] == poketwo_id: if m['embeds']: embed_title = m['embeds'][0]['title'] if 'wild pokémon has appeared!' in embed_title: stop(spam_process) time.sleep(2) bot.sendMessage(channel_id, '<@716390085896962058> h') elif "Congratulations" in embed_title: embed_content = m['embeds'][0]['description'] if 'now level' in embed_content: stop(spam_process) split = embed_content.split(' ') a = embed_content.count(' ') level = int(split[a].replace('!', '')) if level == 100: pass spam_process = start_spam() else: content = m['content'] if 'The pokémon is ' in content: if len(solve(content)) == 0: log('Pokemon not found.') else: for i in solve(content): stop(spam_process) time.sleep(2) bot.sendMessage(channel_id, f'<@716390085896962058> c {i}') time.sleep(2) spam_process = start_spam() elif 'Congratulations' in content: global shiny global legendary global num_pokemon global mythical num_pokemon += 1 split = content.split(' ') pokemon = split[7].replace('!','') if 'These colors seem unusual...' in content: shiny += 1 log(f'A shiny Pokémon was caught! Pokémon: {pokemon}') log(f'Shiny: {shiny} | Legendary: {legendary} | Mythical: {mythical}') elif re.findall( f'^{pokemon}$', legendary_list, re.MULTILINE ): legendary += 1 log(f'A legendary Pokémon was caught! Pokémon: {pokemon}') log(f'Shiny: {shiny} | Legendary: {legendary} | Mythical: {mythical}') elif re.findall(f'^{pokemon}$', mythical_list, re.MULTILINE): mythical += 1 log(f'A mythical Pokémon was caught! Pokémon: {pokemon}') log(f'Shiny: {shiny} | Legendary: {legendary} | Mythical: {mythical}') else: print(f'Total Pokémon Caught: {num_pokemon}') elif 'human' in content: stop(spam_process) log('Captcha Detected; Autocatcher Paused. Press enter to restart.') input() bot.sendMessage(channel_id, '<@716390085896962058> h') if __name__ == '__main__': print('\nEvent Log:') spam_process = start_spam() bot.gateway.run(auto_reconnect=True)
true
true
f72c86f6141b9e5ce714030b5766cf7cff25194c
1,327
py
Python
isolated_functions.py
wonabru/chainnet
f8ec1e2b580af837cba3322ffe69b95156b1b9a1
[ "MIT" ]
5
2019-04-20T18:54:55.000Z
2019-08-23T09:17:20.000Z
isolated_functions.py
wonabru/chainnet
f8ec1e2b580af837cba3322ffe69b95156b1b9a1
[ "MIT" ]
null
null
null
isolated_functions.py
wonabru/chainnet
f8ec1e2b580af837cba3322ffe69b95156b1b9a1
[ "MIT" ]
null
null
null
import ast import re import pickle from Crypto.PublicKey import RSA from base64 import b64decode,b64encode from tkinter import messagebox def str2obj(s): return ast.literal_eval(s.replace('true', 'True').replace('false', 'False')) def trim_name(name): return name.replace('@','').replace('#','') def remove_special_char(in_seq): """ Function is responsible for normalize strings to defined format (UPPERCASE with '_' replacing any special character) :param in_seq: list of strings :return: list of strings """ _sub = re.sub(" {1,5}", "_", in_seq.strip()).lower() _chars = ['*', '\\', '&', '/', '+'] for x in _chars: _sub = _sub.replace(x, '_') return _sub class CFinish: finish = False def serialize(message): return pickle.dumps(message) def unserialize(ser_message): return pickle.loads(ser_message) def encode(n): b = bytearray() while n: b.append(n & 0xFF) n >>= 8 return b64encode(b).decode('utf-8') def decode(s): b = bytearray(b64decode(s.encode('utf-8'))) # in case you're passing in a bytes/str return sum((1 << (bi * 8)) * bb for (bi, bb) in enumerate(b)) class rsa_temp: key = RSA.generate(1024) def showError(ex): if len(ex.args) > 1: _title, _err = ex.args else: _title, _err = 'Other error', ex.args messagebox.showerror(title=str(_title), message=str(_err))
21.063492
117
0.679729
import ast import re import pickle from Crypto.PublicKey import RSA from base64 import b64decode,b64encode from tkinter import messagebox def str2obj(s): return ast.literal_eval(s.replace('true', 'True').replace('false', 'False')) def trim_name(name): return name.replace('@','').replace('#','') def remove_special_char(in_seq): _sub = re.sub(" {1,5}", "_", in_seq.strip()).lower() _chars = ['*', '\\', '&', '/', '+'] for x in _chars: _sub = _sub.replace(x, '_') return _sub class CFinish: finish = False def serialize(message): return pickle.dumps(message) def unserialize(ser_message): return pickle.loads(ser_message) def encode(n): b = bytearray() while n: b.append(n & 0xFF) n >>= 8 return b64encode(b).decode('utf-8') def decode(s): b = bytearray(b64decode(s.encode('utf-8'))) return sum((1 << (bi * 8)) * bb for (bi, bb) in enumerate(b)) class rsa_temp: key = RSA.generate(1024) def showError(ex): if len(ex.args) > 1: _title, _err = ex.args else: _title, _err = 'Other error', ex.args messagebox.showerror(title=str(_title), message=str(_err))
true
true
f72c87804c39b074934faddfa6a15a81e1a36cb8
4,587
py
Python
robot/hsin_agent.py
kanokkorn/watering_robot
b39fed532519e2b89a9f1ae1a3d1b72bb550cc1b
[ "MIT" ]
5
2020-04-01T13:55:12.000Z
2022-03-04T03:32:25.000Z
robot/hsin_agent.py
kanokkorn/watering_robot
b39fed532519e2b89a9f1ae1a3d1b72bb550cc1b
[ "MIT" ]
7
2019-12-21T10:26:40.000Z
2021-06-25T15:15:05.000Z
robot/hsin_agent.py
kanokkorn/watering_robot
b39fed532519e2b89a9f1ae1a3d1b72bb550cc1b
[ "MIT" ]
1
2020-06-03T07:41:21.000Z
2020-06-03T07:41:21.000Z
# import modules from gps3 import gps3 import serial import math import time import csv import os # setup gps socket ser = serial.Serial("/dev/ttyUSB0", 9600) gps_socket = gps3.GPSDSocket() data_stream = gps3.DataStream() gps_socket.connect() gps_socket.watch() # read csv files def track(): # prefix parameter distance = 10 earth_radius = 6371e3 k = 1 with open("robot/lat_lon.csv", newline="") as f: read = csv.reader(f) for gps_row in read: # print(gps_row) # check if gps read properly try: lat_b = float(gps_row[0]) # unpack list to float lon_b = float(gps_row[1]) except IndexError: os.system("clear") raise Exception("Indexing error...Program terminated.") ser.write(str.encode("S")) break # main function for new_data in gps_socket: while new_data and distance > 5: data_stream.unpack(new_data) # print('Altitude = ', data_stream.TPV['lat'], 'Latitude = ', data_stream.TPV['lon']) if (data_stream.TPV["lat"] == "n/a") or ( data_stream.TPV["lon"] != "n/a" ): pass if (data_stream.TPV["lat"] != "n/a") or ( data_stream.TPV["lon"] != "n/a" ): try: in_lat = float(data_stream.TPV["lat"]) except ValueError: print("lat N/A value") in_lat = 10.712709 try: in_lon = float(data_stream.TPV["lon"]) except ValueError: print("lon N/A value") in_lon = 99.378788 lat_A = math.radians(in_lat) lat_B = math.radians(lat_b) del_lat = math.radians(lat_b - (in_lat)) del_lon = math.radians(lon_b - (in_lon)) a = (math.sin(del_lat / 2) * math.sin(del_lat / 2)) + math.cos( lat_A ) * math.cos(lat_B) * ( math.sin(del_lon / 2) * math.sin(del_lon / 2) ) # check if equal zero try: c = 2 * math.atan2(math.sqrt(a), math.sqrt((1 - a))) except ValueError as identifier: print("No Value") distance = earth_radius * c # os.system('clear') print("Distance: ", distance, " Status : Running") ser.write(str.encode("M")) else: ser.write(str.encode("S")) os.system("clear") print("\n==== Checkpoint ", k, " start ====") time.sleep(0.3) print("\nDistance: ", distance, " Status : Stop") time.sleep(0.3) print("Serial_STOP") time.sleep(0.3) for target in range(10): ser.write(str.encode("O")) print("watering" + "." * target, end="\r") ser.write(str.encode("P")) time.sleep(0.8) time.sleep(0.3) print("\nClassification palm Tree :" + str(k)) time.sleep(0.3) # classify_edit.main() for target in range(10): print("writing csv files" + "." * target, end="\r") time.sleep(0.8) distance = 10 in_lat = lat_b in_lon = lon_b print("\n==== Checkpoint", k, " done ====\n") k += 1 time.sleep(1) print("Start Moving to next checkpoint\n") time.sleep(1) else: ser.write(str.encode("S")) os.system("clear") print("\n==== End of lines ====") time.sleep(1) print("\nFinished\n") if __name__ == "__main__": try: track() except KeyboardInterrupt: print("Serial_STOP") ser.write(str.encode("S")) raise Exception("Interrupt...Program terminated.")
36.404762
105
0.419228
from gps3 import gps3 import serial import math import time import csv import os ser = serial.Serial("/dev/ttyUSB0", 9600) gps_socket = gps3.GPSDSocket() data_stream = gps3.DataStream() gps_socket.connect() gps_socket.watch() def track(): distance = 10 earth_radius = 6371e3 k = 1 with open("robot/lat_lon.csv", newline="") as f: read = csv.reader(f) for gps_row in read: lat_b = float(gps_row[0]) lon_b = float(gps_row[1]) except IndexError: os.system("clear") raise Exception("Indexing error...Program terminated.") ser.write(str.encode("S")) break for new_data in gps_socket: while new_data and distance > 5: data_stream.unpack(new_data) if (data_stream.TPV["lat"] == "n/a") or ( data_stream.TPV["lon"] != "n/a" ): pass if (data_stream.TPV["lat"] != "n/a") or ( data_stream.TPV["lon"] != "n/a" ): try: in_lat = float(data_stream.TPV["lat"]) except ValueError: print("lat N/A value") in_lat = 10.712709 try: in_lon = float(data_stream.TPV["lon"]) except ValueError: print("lon N/A value") in_lon = 99.378788 lat_A = math.radians(in_lat) lat_B = math.radians(lat_b) del_lat = math.radians(lat_b - (in_lat)) del_lon = math.radians(lon_b - (in_lon)) a = (math.sin(del_lat / 2) * math.sin(del_lat / 2)) + math.cos( lat_A ) * math.cos(lat_B) * ( math.sin(del_lon / 2) * math.sin(del_lon / 2) ) try: c = 2 * math.atan2(math.sqrt(a), math.sqrt((1 - a))) except ValueError as identifier: print("No Value") distance = earth_radius * c print("Distance: ", distance, " Status : Running") ser.write(str.encode("M")) else: ser.write(str.encode("S")) os.system("clear") print("\n==== Checkpoint ", k, " start ====") time.sleep(0.3) print("\nDistance: ", distance, " Status : Stop") time.sleep(0.3) print("Serial_STOP") time.sleep(0.3) for target in range(10): ser.write(str.encode("O")) print("watering" + "." * target, end="\r") ser.write(str.encode("P")) time.sleep(0.8) time.sleep(0.3) print("\nClassification palm Tree :" + str(k)) time.sleep(0.3) for target in range(10): print("writing csv files" + "." * target, end="\r") time.sleep(0.8) distance = 10 in_lat = lat_b in_lon = lon_b print("\n==== Checkpoint", k, " done ====\n") k += 1 time.sleep(1) print("Start Moving to next checkpoint\n") time.sleep(1) else: ser.write(str.encode("S")) os.system("clear") print("\n==== End of lines ====") time.sleep(1) print("\nFinished\n") if __name__ == "__main__": try: track() except KeyboardInterrupt: print("Serial_STOP") ser.write(str.encode("S")) raise Exception("Interrupt...Program terminated.")
true
true
f72c8854af948f34376eadc837477a9b431ff2c9
2,138
py
Python
app/core/radiofrequency/__init__.py
FHellmann/MLWTF
582c3505d638907a848d5a6c739ee99981300f17
[ "Apache-2.0" ]
null
null
null
app/core/radiofrequency/__init__.py
FHellmann/MLWTF
582c3505d638907a848d5a6c739ee99981300f17
[ "Apache-2.0" ]
null
null
null
app/core/radiofrequency/__init__.py
FHellmann/MLWTF
582c3505d638907a848d5a6c739ee99981300f17
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python """ Author: Fabio Hellmann <info@fabio-hellmann.de> This is a layer between the raw execution unit and the database. """ import logging from datetime import datetime from . import rf_rpi from .models import Protocol, Signal from ..gpio import RaspberryPi3 as GPIO_PI from app.database import db from app.database.models import DataSource, DataSourceType from app.database.converter import converter _LOGGER = logging.getLogger(__name__) class RfDatabase(object): def __init__(self): self.db = db def save_received(self, signal : Signal): return self.db.add_event(converter.unstructure(signal), DataSource.LOW_RADIO_FREQUENCY, DataSourceType.SENSOR) def save_send(self, signal : Signal): return self.db.add_event(converter.unstructure(signal), DataSource.LOW_RADIO_FREQUENCY, DataSourceType.ACTUATOR) def get_received_signals_since(self, since : datetime): result_events = self.db.get_events_by(DataSource.LOW_RADIO_FREQUENCY, DataSourceType.SENSOR, since) result = [] for event in result_events: result.append(converter.structure(event.data, Signal)) return result class RfController(object): def __init__(self): self._db = RfDatabase() self._tx_device = rf_rpi.Device(GPIO_PI.GPIO_17.value) self._tx_device.enable_tx() self._rx_device = rf_rpi.Device(GPIO_PI.GPIO_27.value) self._rx_device.enable_rx() self._rx_device.add_rx_listener(self._receive) def __del__(self): self._tx_device.cleanup() self._rx_device.cleanup() def get_received_signals_since(self, since : datetime): return self._db.get_received_signals_since(since) def send(self, signal : Signal): _LOGGER.info("Sending radiofrequency signal: " + str(signal)) success = self._tx_device.tx_code(signal) self._db.save_send(signal) return success def _receive(self, signal : Signal): _LOGGER.info("Receiving radiofrequency signal: " + str(signal)) self._db.save_received(signal) rf_controller = RfController()
30.985507
120
0.713751
import logging from datetime import datetime from . import rf_rpi from .models import Protocol, Signal from ..gpio import RaspberryPi3 as GPIO_PI from app.database import db from app.database.models import DataSource, DataSourceType from app.database.converter import converter _LOGGER = logging.getLogger(__name__) class RfDatabase(object): def __init__(self): self.db = db def save_received(self, signal : Signal): return self.db.add_event(converter.unstructure(signal), DataSource.LOW_RADIO_FREQUENCY, DataSourceType.SENSOR) def save_send(self, signal : Signal): return self.db.add_event(converter.unstructure(signal), DataSource.LOW_RADIO_FREQUENCY, DataSourceType.ACTUATOR) def get_received_signals_since(self, since : datetime): result_events = self.db.get_events_by(DataSource.LOW_RADIO_FREQUENCY, DataSourceType.SENSOR, since) result = [] for event in result_events: result.append(converter.structure(event.data, Signal)) return result class RfController(object): def __init__(self): self._db = RfDatabase() self._tx_device = rf_rpi.Device(GPIO_PI.GPIO_17.value) self._tx_device.enable_tx() self._rx_device = rf_rpi.Device(GPIO_PI.GPIO_27.value) self._rx_device.enable_rx() self._rx_device.add_rx_listener(self._receive) def __del__(self): self._tx_device.cleanup() self._rx_device.cleanup() def get_received_signals_since(self, since : datetime): return self._db.get_received_signals_since(since) def send(self, signal : Signal): _LOGGER.info("Sending radiofrequency signal: " + str(signal)) success = self._tx_device.tx_code(signal) self._db.save_send(signal) return success def _receive(self, signal : Signal): _LOGGER.info("Receiving radiofrequency signal: " + str(signal)) self._db.save_received(signal) rf_controller = RfController()
true
true
f72c886994bd9fb0a5722665191651370d918e92
2,908
py
Python
tests/riscv/APIs/State_force.py
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
111
2020-06-12T22:31:30.000Z
2022-03-19T03:45:20.000Z
tests/riscv/APIs/State_force.py
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
34
2020-06-12T20:23:40.000Z
2022-03-15T20:04:31.000Z
tests/riscv/APIs/State_force.py
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
32
2020-06-12T19:15:26.000Z
2022-02-20T11:38:31.000Z
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the License for the specific language governing permissions and # limitations under the License. # import RandomUtils from Enums import EStateElementDuplicateMode from State import State from base.Sequence import Sequence from riscv.EnvRISCV import EnvRISCV from riscv.GenThreadRISCV import GenThreadRISCV # This test attempts to add StateElements to a State. There is no direct # mechanism for retrieving the StateElements after they have been added, so # this test merely ensures the method calls don't crash or fail. class MainSequence(Sequence): def generate(self, **kargs): state = State() state.setDuplicateMode(EStateElementDuplicateMode.Replace) mem_start_addr = (RandomUtils.random64(0, 0xFFFFFFFFFFFF) >> 3) << 3 mem_val = RandomUtils.random64() state.addMemoryStateElement(mem_start_addr, 8, mem_val) mem_values = [] for _ in range(RandomUtils.random32(1, 64)): mem_values.append(RandomUtils.random32(0, 0xFF)) mem_start_addr = RandomUtils.random64(0, 0xFFFFFFFFFFFF) state.addMemoryStateElementsAsBytes(mem_start_addr, mem_values) gpr_name = "x%d" % RandomUtils.random32(0, 31) state.addRegisterStateElement(gpr_name, (RandomUtils.random64(),)) fp_reg_name = "D%d" % RandomUtils.random32(0, 31) state.addRegisterStateElement(fp_reg_name, (RandomUtils.random64(),)) state.addSystemRegisterStateElementByField("sstatus", "FS", 0x3) state.addVmContextStateElement("mstatus", "MPRV", 0x1) state.addPcStateElement(RandomUtils.random64(0, 0xFFFFFFFFFFFF)) # Test creating duplicate StateElements state.addVmContextStateElement("mstatus", "MPRV", 0x0) state.setDuplicateMode(EStateElementDuplicateMode.Ignore) state.addRegisterStateElement("sstatus", (RandomUtils.random64(),)) # Test merging two StateElements mem_start_addr = (RandomUtils.random64(0, 0xFFFFFFFFFFFF) >> 3) << 3 mem_val = RandomUtils.random32() state.addMemoryStateElement(mem_start_addr, 4, mem_val) mem_start_addr += 4 mem_values = [] for _ in range(4): mem_values.append(RandomUtils.random32(0, 0xFF)) state.addMemoryStateElementsAsBytes(mem_start_addr, mem_values) MainSequenceClass = MainSequence GenThreadClass = GenThreadRISCV EnvClass = EnvRISCV
38.263158
77
0.725241
import RandomUtils from Enums import EStateElementDuplicateMode from State import State from base.Sequence import Sequence from riscv.EnvRISCV import EnvRISCV from riscv.GenThreadRISCV import GenThreadRISCV class MainSequence(Sequence): def generate(self, **kargs): state = State() state.setDuplicateMode(EStateElementDuplicateMode.Replace) mem_start_addr = (RandomUtils.random64(0, 0xFFFFFFFFFFFF) >> 3) << 3 mem_val = RandomUtils.random64() state.addMemoryStateElement(mem_start_addr, 8, mem_val) mem_values = [] for _ in range(RandomUtils.random32(1, 64)): mem_values.append(RandomUtils.random32(0, 0xFF)) mem_start_addr = RandomUtils.random64(0, 0xFFFFFFFFFFFF) state.addMemoryStateElementsAsBytes(mem_start_addr, mem_values) gpr_name = "x%d" % RandomUtils.random32(0, 31) state.addRegisterStateElement(gpr_name, (RandomUtils.random64(),)) fp_reg_name = "D%d" % RandomUtils.random32(0, 31) state.addRegisterStateElement(fp_reg_name, (RandomUtils.random64(),)) state.addSystemRegisterStateElementByField("sstatus", "FS", 0x3) state.addVmContextStateElement("mstatus", "MPRV", 0x1) state.addPcStateElement(RandomUtils.random64(0, 0xFFFFFFFFFFFF)) # Test creating duplicate StateElements state.addVmContextStateElement("mstatus", "MPRV", 0x0) state.setDuplicateMode(EStateElementDuplicateMode.Ignore) state.addRegisterStateElement("sstatus", (RandomUtils.random64(),)) # Test merging two StateElements mem_start_addr = (RandomUtils.random64(0, 0xFFFFFFFFFFFF) >> 3) << 3 mem_val = RandomUtils.random32() state.addMemoryStateElement(mem_start_addr, 4, mem_val) mem_start_addr += 4 mem_values = [] for _ in range(4): mem_values.append(RandomUtils.random32(0, 0xFF)) state.addMemoryStateElementsAsBytes(mem_start_addr, mem_values) MainSequenceClass = MainSequence GenThreadClass = GenThreadRISCV EnvClass = EnvRISCV
true
true
f72c88bad07b64edf6012e96a4a6af0ebf4b41c8
12,698
py
Python
mai_version/trees/TILDEQueryScorer.py
joschout/tilde
1403b50842b83f2edd6b16b1fbe24b9bec2d0048
[ "Apache-2.0" ]
16
2019-03-06T06:11:33.000Z
2022-02-07T21:30:25.000Z
mai_version/trees/TILDEQueryScorer.py
joschout/tilde
1403b50842b83f2edd6b16b1fbe24b9bec2d0048
[ "Apache-2.0" ]
4
2019-10-08T14:48:23.000Z
2020-03-26T00:31:57.000Z
mai_version/trees/TILDEQueryScorer.py
krishnangovindraj/tilde
5243a02d92f375d56ffc49ab8c3d1a87e31e99b9
[ "Apache-2.0" ]
4
2019-08-14T05:40:47.000Z
2020-08-05T13:21:16.000Z
import math from typing import Iterable, Set, List, Optional import problog import time from problog.logic import And, Term from mai_version.classification.example_partitioning import ExamplePartitioner from mai_version.representation.TILDE_query import TILDEQuery from mai_version.representation.example import ExampleWrapper from mai_version.representation.example import Label from mai_version.trees.scoring import entropy, information_gain2 class QueryScoreInfo: """Wrapper around the information about best scoring query""" def __init__(self, best_query: TILDEQuery, score_of_best_query: float, examples_satisfying_best_query: Set[ExampleWrapper], examples_not_satisfying_best_query: Set[ExampleWrapper]): self.best_query = best_query # type: TILDEQuery self.score_of_best_query = score_of_best_query # type: float self.examples_satisfying_best_query = examples_satisfying_best_query # type: Set[ExampleWrapper] self.examples_not_satisfying_best_query = examples_not_satisfying_best_query # type: Set[ExampleWrapper] class TILDEQueryScorer: @staticmethod def get_best_refined_query(refined_queries: Iterable[TILDEQuery], examples: Set[ExampleWrapper], example_partitioner: ExamplePartitioner, possible_targets: List[Label], probabilistic: Optional[bool] = False) -> QueryScoreInfo: # Tuple[Optional[TILDEQuery], float, Optional[Set[ExampleWrapper]], Optional[Set[ExampleWrapper]]]: best_query = None # type: Optional[TILDEQuery] score_best_query = - math.inf # type: float examples_satisfying_best_query = None # type: Optional[Set[ExampleWrapper]] examples_not_satisfying_best_query = None # type: Optional[Set[ExampleWrapper]] entropy_complete_set = entropy(examples, possible_targets) nb_of_examples_complete_set = len(examples) for q in refined_queries: # type: TILDEQuery print(q) # compute the score of the queries conj_of_tilde_query = q.to_conjunction() # type: And examples_satisfying_q, examples_not_satisfying_q = example_partitioner.get_examples_satisfying_query( examples, conj_of_tilde_query) # type: Set[ExampleWrapper] # examples_not_satisfying_q = examples - examples_satisfying_q # type: Set[ExampleWrapper] #TODO: no longer probabilistic! score = information_gain2(examples_satisfying_q, examples_not_satisfying_q, possible_targets, nb_of_examples_complete_set, entropy_complete_set) if score > score_best_query: best_query = q score_best_query = score examples_satisfying_best_query = examples_satisfying_q examples_not_satisfying_best_query = examples_not_satisfying_q return QueryScoreInfo(best_query, score_best_query, examples_satisfying_best_query, examples_not_satisfying_best_query) class TILDEQueryScorer2: @staticmethod def get_best_refined_query(refined_queries: Iterable[TILDEQuery], examples: Set[ExampleWrapper], example_partitioner: ExamplePartitioner, possible_targets: List[Label], probabilistic: Optional[bool] = False) -> QueryScoreInfo: # Tuple[Optional[TILDEQuery], float, Optional[Set[ExampleWrapper]], Optional[Set[ExampleWrapper]]]: best_query = None # type: Optional[TILDEQuery] score_best_query = - math.inf # type: float # examples_satisfying_best_query = None # type: Optional[Set[ExampleWrapper]] # examples_not_satisfying_best_query = None # type: Optional[Set[ExampleWrapper]] entropy_complete_set = entropy(examples, possible_targets) nb_of_examples_complete_set = len(examples) # ided_queries = list(zip(range(0,len(refined_queries)), refined_queries)) entropy_dict = {label: 0 for label in possible_targets} query_entropy_dicts = [(entropy_dict.copy(), entropy_dict.copy()) for q in refined_queries] for clause_db_ex in examples: db_to_query = clause_db_ex.extend() # type: ClauseDB if clause_db_ex.classification_term is not None: db_to_query += clause_db_ex.classification_term for id, q in zip(range(0,len(refined_queries)), refined_queries): to_query = Term('q' + str(id)) db_to_query += Term('query')(to_query) db_to_query += (to_query << q.to_conjunction()) start_time = time.time() evaluatable = problog.get_evaluatable() mid_time1 = time.time() something = evaluatable.create_from(db_to_query, engine=example_partitioner.engine) mid_time2 = time.time() results = something.evaluate() end_time = time.time() example_partitioner.nb_partitions_calculated += 1 get_evaluatable_duration = mid_time1 - start_time example_partitioner.sum_get_evaluatable += get_evaluatable_duration structure_creation_duration = mid_time2 - mid_time1 example_partitioner.sum_structure_creation_duration += structure_creation_duration if structure_creation_duration > example_partitioner.max_structure_creation_duration: example_partitioner.max_structure_creation_duration = structure_creation_duration if structure_creation_duration < example_partitioner.min_structure_creation_duration: example_partitioner.min_structure_creation_duration = structure_creation_duration if structure_creation_duration < 0.000001: example_partitioner.nb_structure_creation_zero += 1 evalutation_duration = end_time - mid_time2 example_partitioner.sum_evaluation_duration += evalutation_duration if evalutation_duration > example_partitioner.max_evaluation_duration: example_partitioner.max_evaluation_duration = evalutation_duration if evalutation_duration < example_partitioner.min_evaluation_duration: example_partitioner.min_evaluation_duration = evalutation_duration if evalutation_duration < 0.000001: example_partitioner.nb_evaluation_zero += 1 # results = problog.get_evaluatable().create_from(db_to_query, engine=example_partitioner.engine).evaluate() for to_query, prob in results.items(): id = int(to_query.functor[1:]) if prob > 0.5: query_entropy_dicts[id][0][clause_db_ex.get_label()] = query_entropy_dicts[id][0][clause_db_ex.get_label()] + 1 else: query_entropy_dicts[id][1][clause_db_ex.get_label()] = query_entropy_dicts[id][1][ clause_db_ex.get_label()] + 1 for query, (left_dic, right_dic) in zip(refined_queries, query_entropy_dicts): # -- ig -- ig = 0 if nb_of_examples_complete_set != 0: ig = entropy_complete_set nb_examples_left = sum(left_dic.values()) if nb_examples_left > 0: entropy_left = 0 for label in left_dic.keys(): label_value = left_dic[label] if label_value != 0: entropy_left -= label_value / nb_examples_left \ * math.log2(label_value / nb_examples_left) ig -= nb_examples_left / nb_of_examples_complete_set * entropy_left # ------ nb_examples_right = sum(right_dic.values()) if nb_examples_right > 0: entropy_right = 0 for label in right_dic.keys(): label_value = right_dic[label] if label_value != 0: entropy_right -= label_value / nb_examples_right \ * math.log2(label_value / nb_examples_right) ig -= nb_examples_right / nb_of_examples_complete_set * entropy_right if ig > score_best_query: best_query = query score_best_query = ig # --- we now know the best query, so create the partition again: examples_satisfying_best_query = set() # type: Optional[Set[ExampleWrapper]] examples_not_satisfying_best_query = set() # type: Optional[Set[ExampleWrapper]] to_query = Term('to_query') to_add1 = Term('query')(to_query) to_add2 = (to_query << best_query.to_conjunction()) for clause_db_ex in examples: db_to_query = clause_db_ex.extend() # type: ClauseDB if clause_db_ex.classification_term is not None: db_to_query += clause_db_ex.classification_term # db_to_query = example_db.extend() db_to_query += to_add1 db_to_query += to_add2 start_time = time.time() evaluatable = problog.get_evaluatable() mid_time1 = time.time() something = evaluatable.create_from(db_to_query, engine=example_partitioner.engine) mid_time2 = time.time() query_result = something.evaluate() end_time = time.time() example_partitioner.nb_partitions_calculated += 1 get_evaluatable_duration = mid_time1 - start_time example_partitioner.sum_get_evaluatable += get_evaluatable_duration structure_creation_duration = mid_time2 - mid_time1 example_partitioner.sum_structure_creation_duration += structure_creation_duration if structure_creation_duration > example_partitioner.max_structure_creation_duration: example_partitioner.max_structure_creation_duration = structure_creation_duration if structure_creation_duration < example_partitioner.min_structure_creation_duration: example_partitioner.min_structure_creation_duration = structure_creation_duration if structure_creation_duration < 0.000001: example_partitioner.nb_structure_creation_zero += 1 evalutation_duration = end_time - mid_time2 example_partitioner.sum_evaluation_duration += evalutation_duration if evalutation_duration > example_partitioner.max_evaluation_duration: example_partitioner.max_evaluation_duration = evalutation_duration if evalutation_duration < example_partitioner.min_evaluation_duration: example_partitioner.min_evaluation_duration = evalutation_duration if evalutation_duration < 0.000001: example_partitioner.nb_evaluation_zero += 1 # query_result = problog.get_evaluatable().create_from(db_to_query, # engine=example_partitioner.engine).evaluate() if query_result[to_query] > 0.5: examples_satisfying_best_query.add(clause_db_ex) else: examples_not_satisfying_best_query.add(clause_db_ex) # for qid, q in enumerate(refined_queries): # type: TILDEQuery # # compute the score of the queries # conj_of_tilde_query = q.to_conjunction() # type: And # # examples_satisfying_q, examples_not_satisfying_q = example_partitioner.get_examples_satisfying_query( # examples, conj_of_tilde_query) # type: Set[ExampleWrapper] # # examples_not_satisfying_q = examples - examples_satisfying_q # type: Set[ExampleWrapper] # # #TODO: no longer probabilistic! # score = information_gain2(examples_satisfying_q, examples_not_satisfying_q, possible_targets, nb_of_examples_complete_set, entropy_complete_set) # # if score > score_best_query: # best_query = q # score_best_query = score # examples_satisfying_best_query = examples_satisfying_q # examples_not_satisfying_best_query = examples_not_satisfying_q return QueryScoreInfo(best_query, score_best_query, examples_satisfying_best_query, examples_not_satisfying_best_query)
52.040984
158
0.654198
import math from typing import Iterable, Set, List, Optional import problog import time from problog.logic import And, Term from mai_version.classification.example_partitioning import ExamplePartitioner from mai_version.representation.TILDE_query import TILDEQuery from mai_version.representation.example import ExampleWrapper from mai_version.representation.example import Label from mai_version.trees.scoring import entropy, information_gain2 class QueryScoreInfo: def __init__(self, best_query: TILDEQuery, score_of_best_query: float, examples_satisfying_best_query: Set[ExampleWrapper], examples_not_satisfying_best_query: Set[ExampleWrapper]): self.best_query = best_query self.score_of_best_query = score_of_best_query self.examples_satisfying_best_query = examples_satisfying_best_query self.examples_not_satisfying_best_query = examples_not_satisfying_best_query class TILDEQueryScorer: @staticmethod def get_best_refined_query(refined_queries: Iterable[TILDEQuery], examples: Set[ExampleWrapper], example_partitioner: ExamplePartitioner, possible_targets: List[Label], probabilistic: Optional[bool] = False) -> QueryScoreInfo: best_query = None score_best_query = - math.inf examples_satisfying_best_query = None examples_not_satisfying_best_query = None entropy_complete_set = entropy(examples, possible_targets) nb_of_examples_complete_set = len(examples) for q in refined_queries: print(q) conj_of_tilde_query = q.to_conjunction() examples_satisfying_q, examples_not_satisfying_q = example_partitioner.get_examples_satisfying_query( examples, conj_of_tilde_query) score = information_gain2(examples_satisfying_q, examples_not_satisfying_q, possible_targets, nb_of_examples_complete_set, entropy_complete_set) if score > score_best_query: best_query = q score_best_query = score examples_satisfying_best_query = examples_satisfying_q examples_not_satisfying_best_query = examples_not_satisfying_q return QueryScoreInfo(best_query, score_best_query, examples_satisfying_best_query, examples_not_satisfying_best_query) class TILDEQueryScorer2: @staticmethod def get_best_refined_query(refined_queries: Iterable[TILDEQuery], examples: Set[ExampleWrapper], example_partitioner: ExamplePartitioner, possible_targets: List[Label], probabilistic: Optional[bool] = False) -> QueryScoreInfo: best_query = None score_best_query = - math.inf ts) nb_of_examples_complete_set = len(examples) entropy_dict = {label: 0 for label in possible_targets} query_entropy_dicts = [(entropy_dict.copy(), entropy_dict.copy()) for q in refined_queries] for clause_db_ex in examples: db_to_query = clause_db_ex.extend() if clause_db_ex.classification_term is not None: db_to_query += clause_db_ex.classification_term for id, q in zip(range(0,len(refined_queries)), refined_queries): to_query = Term('q' + str(id)) db_to_query += Term('query')(to_query) db_to_query += (to_query << q.to_conjunction()) start_time = time.time() evaluatable = problog.get_evaluatable() mid_time1 = time.time() something = evaluatable.create_from(db_to_query, engine=example_partitioner.engine) mid_time2 = time.time() results = something.evaluate() end_time = time.time() example_partitioner.nb_partitions_calculated += 1 get_evaluatable_duration = mid_time1 - start_time example_partitioner.sum_get_evaluatable += get_evaluatable_duration structure_creation_duration = mid_time2 - mid_time1 example_partitioner.sum_structure_creation_duration += structure_creation_duration if structure_creation_duration > example_partitioner.max_structure_creation_duration: example_partitioner.max_structure_creation_duration = structure_creation_duration if structure_creation_duration < example_partitioner.min_structure_creation_duration: example_partitioner.min_structure_creation_duration = structure_creation_duration if structure_creation_duration < 0.000001: example_partitioner.nb_structure_creation_zero += 1 evalutation_duration = end_time - mid_time2 example_partitioner.sum_evaluation_duration += evalutation_duration if evalutation_duration > example_partitioner.max_evaluation_duration: example_partitioner.max_evaluation_duration = evalutation_duration if evalutation_duration < example_partitioner.min_evaluation_duration: example_partitioner.min_evaluation_duration = evalutation_duration if evalutation_duration < 0.000001: example_partitioner.nb_evaluation_zero += 1 for to_query, prob in results.items(): id = int(to_query.functor[1:]) if prob > 0.5: query_entropy_dicts[id][0][clause_db_ex.get_label()] = query_entropy_dicts[id][0][clause_db_ex.get_label()] + 1 else: query_entropy_dicts[id][1][clause_db_ex.get_label()] = query_entropy_dicts[id][1][ clause_db_ex.get_label()] + 1 for query, (left_dic, right_dic) in zip(refined_queries, query_entropy_dicts): ig = 0 if nb_of_examples_complete_set != 0: ig = entropy_complete_set nb_examples_left = sum(left_dic.values()) if nb_examples_left > 0: entropy_left = 0 for label in left_dic.keys(): label_value = left_dic[label] if label_value != 0: entropy_left -= label_value / nb_examples_left \ * math.log2(label_value / nb_examples_left) ig -= nb_examples_left / nb_of_examples_complete_set * entropy_left nb_examples_right = sum(right_dic.values()) if nb_examples_right > 0: entropy_right = 0 for label in right_dic.keys(): label_value = right_dic[label] if label_value != 0: entropy_right -= label_value / nb_examples_right \ * math.log2(label_value / nb_examples_right) ig -= nb_examples_right / nb_of_examples_complete_set * entropy_right if ig > score_best_query: best_query = query score_best_query = ig examples_satisfying_best_query = set() examples_not_satisfying_best_query = set() to_query = Term('to_query') to_add1 = Term('query')(to_query) to_add2 = (to_query << best_query.to_conjunction()) for clause_db_ex in examples: db_to_query = clause_db_ex.extend() if clause_db_ex.classification_term is not None: db_to_query += clause_db_ex.classification_term db_to_query += to_add1 db_to_query += to_add2 start_time = time.time() evaluatable = problog.get_evaluatable() mid_time1 = time.time() something = evaluatable.create_from(db_to_query, engine=example_partitioner.engine) mid_time2 = time.time() query_result = something.evaluate() end_time = time.time() example_partitioner.nb_partitions_calculated += 1 get_evaluatable_duration = mid_time1 - start_time example_partitioner.sum_get_evaluatable += get_evaluatable_duration structure_creation_duration = mid_time2 - mid_time1 example_partitioner.sum_structure_creation_duration += structure_creation_duration if structure_creation_duration > example_partitioner.max_structure_creation_duration: example_partitioner.max_structure_creation_duration = structure_creation_duration if structure_creation_duration < example_partitioner.min_structure_creation_duration: example_partitioner.min_structure_creation_duration = structure_creation_duration if structure_creation_duration < 0.000001: example_partitioner.nb_structure_creation_zero += 1 evalutation_duration = end_time - mid_time2 example_partitioner.sum_evaluation_duration += evalutation_duration if evalutation_duration > example_partitioner.max_evaluation_duration: example_partitioner.max_evaluation_duration = evalutation_duration if evalutation_duration < example_partitioner.min_evaluation_duration: example_partitioner.min_evaluation_duration = evalutation_duration if evalutation_duration < 0.000001: example_partitioner.nb_evaluation_zero += 1 if query_result[to_query] > 0.5: examples_satisfying_best_query.add(clause_db_ex) else: examples_not_satisfying_best_query.add(clause_db_ex) examples_not_satisfying_best_query)
true
true
f72c8a7510c49c3ae446f48e397b061791a320e4
13,771
py
Python
logreg.py
naver/cog
5b34ca90757116b9cfae11d8838927ba73e1ede8
[ "BSD-3-Clause" ]
13
2021-10-13T11:13:55.000Z
2022-03-11T04:41:41.000Z
logreg.py
naver/cog
5b34ca90757116b9cfae11d8838927ba73e1ede8
[ "BSD-3-Clause" ]
null
null
null
logreg.py
naver/cog
5b34ca90757116b9cfae11d8838927ba73e1ede8
[ "BSD-3-Clause" ]
null
null
null
# ImageNet-CoG Benchmark # Copyright 2021-present NAVER Corp. # 3-Clause BSD License​ import argparse import copy import logging import math import os import shutil import time import optuna import torch as th import feature_ops import metrics import utils from iterators import TorchIterator from meters import AverageMeter, ProgressMeter logger = logging.getLogger() class LogReg: """ Logistic regression classifier with mini-batch SGD. """ def __init__(self, args, cfg): self.args = args self.cfg = cfg # load the training set features trainset = feature_ops.load_feature_set( args.train_features_path, "train", cfg.CLF.NORM_FTS ) if args.val: # randomly split the training set into train + val logger.info("Splitting the training set into train and val") trainset, testset = feature_ops.split_trainset(trainset, cfg.CLF.VAL_PERC) else: # load the test set testset = feature_ops.load_feature_set(args.test_features_path, "test", cfg.CLF.NORM_FTS) if cfg.CLF.N_SHOT > 0: logger.info( "Simulating few-shot learning setting, {} images per class.".format( cfg.CLF.N_SHOT ) ) trainset = feature_ops.make_fewshot_dataset(trainset, cfg.CLF.N_SHOT) self.trainset = trainset self.testset = testset self.trainset.print_info() self.testset.print_info() # determine number of cases if len(list(self.trainset.y.shape)) == 1: classes = th.unique(self.trainset.y) assert th.all(classes == th.unique(self.testset.y)) args.n_classes = classes.size(0) # move all features to the device if args.device == "cuda": feature_ops.move_data_to_cuda([self.trainset, self.testset]) def __call__(self, trial=None): """ The function called by Optuna. """ # empty the cache allocated in the previous call th.cuda.empty_cache() args = copy.deepcopy(self.args) cfg = self.cfg x_train = self.trainset.x y_train = self.trainset.y x_test = self.testset.x y_test = self.testset.y # create training and test set iterators train_iter = TorchIterator((x_train, y_train), cfg.CLF.BATCH_SIZE, shuffle=True) test_iter = TorchIterator((x_test, y_test), cfg.CLF.BATCH_SIZE, shuffle=False) # define logistic classifier model = th.nn.Linear(x_train.size(1), args.n_classes).to(args.device) crit = th.nn.CrossEntropyLoss().to(args.device) # sample a learning rate and weight decay if trial is not None: lr_intv = cfg.CLF.LR_INTV wd_intv = cfg.CLF.WD_INTV args.lr = trial.suggest_loguniform("lr", lr_intv[0], lr_intv[1]) args.wd = trial.suggest_loguniform("wd", wd_intv[0], wd_intv[1]) optim = th.optim.SGD( model.parameters(), lr=args.lr, momentum=args.mom, weight_decay=args.wd ) args.exp_dir = os.path.join( args.output_dir, "{}-lr-{}_wd-{}".format("val" if args.val else "final", args.lr, args.wd), ) os.makedirs(args.exp_dir, exist_ok=True) # write the model definition into exp_dir utils.write_to_file(str(model), os.path.join(args.exp_dir, "model.txt")) # logs computed during training / evaluation args.logs = { "train/loss": [], "train/top1": [], "train/top5": [], "test/loss": [], "test/top1": [], "test/top5": [], "lr": [], } # predictions over the evaluation sets args.preds = [] for epoch in range(cfg.CLF.N_EPOCHS): if not args.val: logger.info(f"**Epoch:{epoch}**") args.epoch = epoch train_stat = train(train_iter, model, crit, optim, epoch, args) validate(test_iter, model, crit, args) adjust_learning_rate(optim, args, cfg) # if something went wrong during training # e.g. SGD diverged if train_stat == -1: break # save the logs utils.save_pickle(args.logs, f"{args.exp_dir}/logs.pkl") # save the predictions utils.save_pickle(args.preds, f"{args.exp_dir}/preds.pkl") # save the whole args, for ease of access utils.save_pickle(vars(args), f"{args.exp_dir}/args.pkl") # save also the final model th.save( { "model": model.state_dict(), }, f"{args.exp_dir}/model.pth", ) # return the last test accuracy return args.logs["test/top1"][-1] def train(train_loader, model, criterion, optimizer, epoch, args): """ Train the classifier for one epoch. """ batch_time = AverageMeter("Time", ":6.3f") losses = AverageMeter("Loss", ":.4e") top1 = AverageMeter("Acc@1", ":6.2f") top5 = AverageMeter("Acc@5", ":6.2f") progress = ProgressMeter( len(train_loader), [batch_time, losses, top1, top5], prefix="Epoch: [{}]".format(epoch), ) # switch to train mode model.train() end = time.time() for i, (fts, lbls) in enumerate(train_loader): fts = fts.to(args.device) lbls = lbls.to(args.device) # compute output output = model(fts) loss = criterion(output, lbls) if not th.isfinite(loss): logger.info("Loss ({}) is not finite, terminating".format(loss.item())) optimizer.zero_grad() return -1 # measure accuracy and record loss acc1, acc5 = metrics.accuracy(output, lbls, topk=(1, 5)) losses.update(loss.item(), fts.size(0)) top1.update(acc1.item(), fts.size(0)) top5.update(acc5.item(), fts.size(0)) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if (not args.val) and (i % args.print_freq == 0): progress.display(i) args.logs["train/loss"].append(losses.avg) args.logs["train/top1"].append(top1.avg) args.logs["train/top5"].append(top5.avg) return 0 def validate(val_loader, model, criterion, args): losses = AverageMeter("Loss", ":.4e") top1 = AverageMeter("Acc@1", ":6.2f") top5 = AverageMeter("Acc@5", ":6.2f") # switch to evaluate mode model.eval() # keep predictions per class preds = th.ones(len(val_loader.tensors[0]), dtype=th.int32, device=args.device) * -1. six = 0 with th.no_grad(): for i, (fts, lbls) in enumerate(val_loader): fts = fts.to(args.device) lbls = lbls.to(args.device) bs = fts.size(0) # compute output output = model(fts) loss = criterion(output, lbls) # store the predicted classes preds[six:six + bs] = th.argmax(output, dim=1) six += bs # measure accuracy and record loss acc1, acc5 = metrics.accuracy(output, lbls, topk=(1, 5)) losses.update(loss.item(), bs) top1.update(acc1[0].item(), bs) top5.update(acc5[0].item(), bs) # make sure that there is no invalid prediction assert th.all(preds >= 0).item() args.preds.append(preds.detach().cpu()) args.logs["test/loss"].append(losses.avg) args.logs["test/top1"].append(top1.avg) args.logs["test/top5"].append(top5.avg) if not args.val: logger.info( " * Acc@1:{top1.avg:.3f} - Acc@5:{top5.avg:.3f}".format( top1=top1, top5=top5 ) ) def adjust_learning_rate(optimizer, args, cfg): """Decay the learning rate based on cosine schedule""" lr = args.lr lr *= 0.5 * (1.0 + math.cos(math.pi * args.epoch / cfg.CLF.N_EPOCHS)) for param_group in optimizer.param_groups: param_group["lr"] = lr args.logs["lr"].append(lr) def save_checkpoint(state, is_best, filename="checkpoint.pth.tar"): th.save(state, filename) if is_best: shutil.copyfile(filename, "model_best.pth.tar") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--model', type=utils.none_or_string_flag, help='Name of the model in the <model_title>_<architecture_name> form.' 'See the table of models in ./prepare_models/README.md for all the model names we support.' 'This is an optional argument that needs to be set along with --models_root_dir and --dataset.' 'When these three arguments are set, the script will load features from:' '<models_root_dir>/<model_title>/<architecture_name>/<dataset>/features_*/X_Y.pth.' 'If you would like to load pre-extracted features from somewhere else' 'then ignore this argument and provide the --train_features_dir and --test_features_dir arguments accordingly') parser.add_argument('--models_root_dir', type=utils.none_or_string_flag, help='Root directory for all models, see prepare_models/README.md for a detailed explanation.' 'This is an optional argument that needs to be set along with --model and --dataset.' 'Please see the help message for the --model argument as well.') parser.add_argument("--dataset", type=utils.none_or_string_flag, help="On which dataset to learn classifiers" 'Possible values are ("in1k", "cog_l1", "cog_l2", "cog_l3", "cog_l4", "cog_l5")' 'This is an optional argument that needs to be set along with --models_root_dir and --model.' 'Please see the help message for the --model argument as well.') parser.add_argument('--train_features_dir', type=utils.none_or_string_flag, help='Path to the directory containing pre-extracted training set features.' 'We expect a features file "X_Y.pth" under <train_features_dir>.' 'This is an optional argument that needs to be set if --models_root_dir, --model and --dataset are not set.') parser.add_argument('--test_features_dir', type=utils.none_or_string_flag, help='Path to the directory containing pre-extracted test set features.' 'We expect a features file "X_Y.pth" under <test_features_dir>.' 'This is an optional argument that needs to be set if --models_root_dir, --model and --dataset are not set.') parser.add_argument('--output_dir', type=utils.none_or_string_flag, help='Where to log program logs.' 'This is an optional argument that needs to be set if --models_root_dir is not set.' 'If not provided, we try to save the logs under' '<models_root_dir>/<model_title>/<architecture_name>/<dataset>/eval_logreg/seed*') # learning rate and momentum are tuned in this program, do not manually set. parser.add_argument("--lr", type=float, default=0.0, help="initial learning rate") parser.add_argument("--wd", type=float, default=0.0, help="weight decay") parser.add_argument("--mom", type=float, default=0.9, help="momentum") # program-related options parser.add_argument("--print_freq", default=100, type=int, help="print frequency (default: 10)") parser.add_argument("--device", type=str, default="cuda") # optionally to overwrite the default config parser.add_argument("opts", default=None, help="see configs/default.py for all options", nargs=argparse.REMAINDER) args = parser.parse_args() if args.device == "cuda" and not th.cuda.is_available(): print("CUDA is not available, I will run on CPU.") args.device = "cpu" # load the config file # create output directory, # locate pre-extracted features, # initialize program logger, # save args and cfg # this function sets the following arg variables: # - train_features_path, type=str # - test_features_path, type=str # - output_dir, type=str args, cfg = utils.init_program(args, _for="logreg") # tune hyper-parameters with optuna logger.info("Running Optuna...") hps_sampler = optuna.samplers.TPESampler(multivariate=True, seed=cfg.EVAL.SEED) study = optuna.create_study(sampler=hps_sampler, direction="maximize") args.val = True logreg = LogReg(args, cfg) study.optimize(logreg, n_trials=cfg.CLF.N_TRIALS, n_jobs=1, show_progress_bar=False) utils.save_pickle(study, os.path.join(args.output_dir, "study.pkl")) logger.info("") logger.info("*" * 50) logger.info("Hyper-parameter search ended") logger.info("best_trial:") logger.info(str(study.best_trial)) logger.info("best_params:") logger.info(str(study.best_params)) logger.info("*" * 50) logger.info("") # train the final classifier with the tuned hyper-parameters del logreg th.cuda.empty_cache() args.lr = study.best_params["lr"] args.wd = study.best_params["wd"] args.val = False logreg = LogReg(args, cfg) logreg()
37.625683
140
0.600392
import argparse import copy import logging import math import os import shutil import time import optuna import torch as th import feature_ops import metrics import utils from iterators import TorchIterator from meters import AverageMeter, ProgressMeter logger = logging.getLogger() class LogReg: def __init__(self, args, cfg): self.args = args self.cfg = cfg trainset = feature_ops.load_feature_set( args.train_features_path, "train", cfg.CLF.NORM_FTS ) if args.val: logger.info("Splitting the training set into train and val") trainset, testset = feature_ops.split_trainset(trainset, cfg.CLF.VAL_PERC) else: testset = feature_ops.load_feature_set(args.test_features_path, "test", cfg.CLF.NORM_FTS) if cfg.CLF.N_SHOT > 0: logger.info( "Simulating few-shot learning setting, {} images per class.".format( cfg.CLF.N_SHOT ) ) trainset = feature_ops.make_fewshot_dataset(trainset, cfg.CLF.N_SHOT) self.trainset = trainset self.testset = testset self.trainset.print_info() self.testset.print_info() if len(list(self.trainset.y.shape)) == 1: classes = th.unique(self.trainset.y) assert th.all(classes == th.unique(self.testset.y)) args.n_classes = classes.size(0) if args.device == "cuda": feature_ops.move_data_to_cuda([self.trainset, self.testset]) def __call__(self, trial=None): th.cuda.empty_cache() args = copy.deepcopy(self.args) cfg = self.cfg x_train = self.trainset.x y_train = self.trainset.y x_test = self.testset.x y_test = self.testset.y train_iter = TorchIterator((x_train, y_train), cfg.CLF.BATCH_SIZE, shuffle=True) test_iter = TorchIterator((x_test, y_test), cfg.CLF.BATCH_SIZE, shuffle=False) model = th.nn.Linear(x_train.size(1), args.n_classes).to(args.device) crit = th.nn.CrossEntropyLoss().to(args.device) if trial is not None: lr_intv = cfg.CLF.LR_INTV wd_intv = cfg.CLF.WD_INTV args.lr = trial.suggest_loguniform("lr", lr_intv[0], lr_intv[1]) args.wd = trial.suggest_loguniform("wd", wd_intv[0], wd_intv[1]) optim = th.optim.SGD( model.parameters(), lr=args.lr, momentum=args.mom, weight_decay=args.wd ) args.exp_dir = os.path.join( args.output_dir, "{}-lr-{}_wd-{}".format("val" if args.val else "final", args.lr, args.wd), ) os.makedirs(args.exp_dir, exist_ok=True) utils.write_to_file(str(model), os.path.join(args.exp_dir, "model.txt")) args.logs = { "train/loss": [], "train/top1": [], "train/top5": [], "test/loss": [], "test/top1": [], "test/top5": [], "lr": [], } args.preds = [] for epoch in range(cfg.CLF.N_EPOCHS): if not args.val: logger.info(f"**Epoch:{epoch}**") args.epoch = epoch train_stat = train(train_iter, model, crit, optim, epoch, args) validate(test_iter, model, crit, args) adjust_learning_rate(optim, args, cfg) if train_stat == -1: break utils.save_pickle(args.logs, f"{args.exp_dir}/logs.pkl") utils.save_pickle(args.preds, f"{args.exp_dir}/preds.pkl") utils.save_pickle(vars(args), f"{args.exp_dir}/args.pkl") th.save( { "model": model.state_dict(), }, f"{args.exp_dir}/model.pth", ) return args.logs["test/top1"][-1] def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter("Time", ":6.3f") losses = AverageMeter("Loss", ":.4e") top1 = AverageMeter("Acc@1", ":6.2f") top5 = AverageMeter("Acc@5", ":6.2f") progress = ProgressMeter( len(train_loader), [batch_time, losses, top1, top5], prefix="Epoch: [{}]".format(epoch), ) model.train() end = time.time() for i, (fts, lbls) in enumerate(train_loader): fts = fts.to(args.device) lbls = lbls.to(args.device) output = model(fts) loss = criterion(output, lbls) if not th.isfinite(loss): logger.info("Loss ({}) is not finite, terminating".format(loss.item())) optimizer.zero_grad() return -1 acc1, acc5 = metrics.accuracy(output, lbls, topk=(1, 5)) losses.update(loss.item(), fts.size(0)) top1.update(acc1.item(), fts.size(0)) top5.update(acc5.item(), fts.size(0)) optimizer.zero_grad() loss.backward() optimizer.step() batch_time.update(time.time() - end) end = time.time() if (not args.val) and (i % args.print_freq == 0): progress.display(i) args.logs["train/loss"].append(losses.avg) args.logs["train/top1"].append(top1.avg) args.logs["train/top5"].append(top5.avg) return 0 def validate(val_loader, model, criterion, args): losses = AverageMeter("Loss", ":.4e") top1 = AverageMeter("Acc@1", ":6.2f") top5 = AverageMeter("Acc@5", ":6.2f") model.eval() preds = th.ones(len(val_loader.tensors[0]), dtype=th.int32, device=args.device) * -1. six = 0 with th.no_grad(): for i, (fts, lbls) in enumerate(val_loader): fts = fts.to(args.device) lbls = lbls.to(args.device) bs = fts.size(0) output = model(fts) loss = criterion(output, lbls) preds[six:six + bs] = th.argmax(output, dim=1) six += bs acc1, acc5 = metrics.accuracy(output, lbls, topk=(1, 5)) losses.update(loss.item(), bs) top1.update(acc1[0].item(), bs) top5.update(acc5[0].item(), bs) assert th.all(preds >= 0).item() args.preds.append(preds.detach().cpu()) args.logs["test/loss"].append(losses.avg) args.logs["test/top1"].append(top1.avg) args.logs["test/top5"].append(top5.avg) if not args.val: logger.info( " * Acc@1:{top1.avg:.3f} - Acc@5:{top5.avg:.3f}".format( top1=top1, top5=top5 ) ) def adjust_learning_rate(optimizer, args, cfg): lr = args.lr lr *= 0.5 * (1.0 + math.cos(math.pi * args.epoch / cfg.CLF.N_EPOCHS)) for param_group in optimizer.param_groups: param_group["lr"] = lr args.logs["lr"].append(lr) def save_checkpoint(state, is_best, filename="checkpoint.pth.tar"): th.save(state, filename) if is_best: shutil.copyfile(filename, "model_best.pth.tar") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--model', type=utils.none_or_string_flag, help='Name of the model in the <model_title>_<architecture_name> form.' 'See the table of models in ./prepare_models/README.md for all the model names we support.' 'This is an optional argument that needs to be set along with --models_root_dir and --dataset.' 'When these three arguments are set, the script will load features from:' '<models_root_dir>/<model_title>/<architecture_name>/<dataset>/features_*/X_Y.pth.' 'If you would like to load pre-extracted features from somewhere else' 'then ignore this argument and provide the --train_features_dir and --test_features_dir arguments accordingly') parser.add_argument('--models_root_dir', type=utils.none_or_string_flag, help='Root directory for all models, see prepare_models/README.md for a detailed explanation.' 'This is an optional argument that needs to be set along with --model and --dataset.' 'Please see the help message for the --model argument as well.') parser.add_argument("--dataset", type=utils.none_or_string_flag, help="On which dataset to learn classifiers" 'Possible values are ("in1k", "cog_l1", "cog_l2", "cog_l3", "cog_l4", "cog_l5")' 'This is an optional argument that needs to be set along with --models_root_dir and --model.' 'Please see the help message for the --model argument as well.') parser.add_argument('--train_features_dir', type=utils.none_or_string_flag, help='Path to the directory containing pre-extracted training set features.' 'We expect a features file "X_Y.pth" under <train_features_dir>.' 'This is an optional argument that needs to be set if --models_root_dir, --model and --dataset are not set.') parser.add_argument('--test_features_dir', type=utils.none_or_string_flag, help='Path to the directory containing pre-extracted test set features.' 'We expect a features file "X_Y.pth" under <test_features_dir>.' 'This is an optional argument that needs to be set if --models_root_dir, --model and --dataset are not set.') parser.add_argument('--output_dir', type=utils.none_or_string_flag, help='Where to log program logs.' 'This is an optional argument that needs to be set if --models_root_dir is not set.' 'If not provided, we try to save the logs under' '<models_root_dir>/<model_title>/<architecture_name>/<dataset>/eval_logreg/seed*') parser.add_argument("--lr", type=float, default=0.0, help="initial learning rate") parser.add_argument("--wd", type=float, default=0.0, help="weight decay") parser.add_argument("--mom", type=float, default=0.9, help="momentum") parser.add_argument("--print_freq", default=100, type=int, help="print frequency (default: 10)") parser.add_argument("--device", type=str, default="cuda") parser.add_argument("opts", default=None, help="see configs/default.py for all options", nargs=argparse.REMAINDER) args = parser.parse_args() if args.device == "cuda" and not th.cuda.is_available(): print("CUDA is not available, I will run on CPU.") args.device = "cpu" args, cfg = utils.init_program(args, _for="logreg") logger.info("Running Optuna...") hps_sampler = optuna.samplers.TPESampler(multivariate=True, seed=cfg.EVAL.SEED) study = optuna.create_study(sampler=hps_sampler, direction="maximize") args.val = True logreg = LogReg(args, cfg) study.optimize(logreg, n_trials=cfg.CLF.N_TRIALS, n_jobs=1, show_progress_bar=False) utils.save_pickle(study, os.path.join(args.output_dir, "study.pkl")) logger.info("") logger.info("*" * 50) logger.info("Hyper-parameter search ended") logger.info("best_trial:") logger.info(str(study.best_trial)) logger.info("best_params:") logger.info(str(study.best_params)) logger.info("*" * 50) logger.info("") del logreg th.cuda.empty_cache() args.lr = study.best_params["lr"] args.wd = study.best_params["wd"] args.val = False logreg = LogReg(args, cfg) logreg()
true
true
f72c8ab58a23d585b39a3037e18747d52bcb4b75
1,132
py
Python
Chapter02/Ch02_Code/GUI_tabbed_two_mighty_labels.py
mr4dsd43/Python-GUI-Programming-Cookbook-Second-Edition
18e4632106169991e9b75680bdd7250c9d77c3be
[ "MIT" ]
2
2021-01-12T03:13:29.000Z
2021-01-12T03:13:31.000Z
Chapter02/Ch02_Code/GUI_tabbed_two_mighty_labels.py
mr4dsd43/Python-GUI-Programming-Cookbook-Second-Edition
18e4632106169991e9b75680bdd7250c9d77c3be
[ "MIT" ]
null
null
null
Chapter02/Ch02_Code/GUI_tabbed_two_mighty_labels.py
mr4dsd43/Python-GUI-Programming-Cookbook-Second-Edition
18e4632106169991e9b75680bdd7250c9d77c3be
[ "MIT" ]
1
2022-02-22T02:06:32.000Z
2022-02-22T02:06:32.000Z
''' May 2017 @author: Burkhard A. Meier ''' #====================== # imports #====================== import tkinter as tk from tkinter import ttk # Create instance win = tk.Tk() # Add a title win.title("Python GUI") tabControl = ttk.Notebook(win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # LabelFrame using tab1 as the parent mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) # Label using mighty as the parent a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') # Add another label ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) # Add some space around each label for child in mighty.winfo_children(): child.grid_configure(padx=8) #====================== # Start GUI #====================== win.mainloop()
25.155556
65
0.620141
import tkinter as tk from tkinter import ttk win = tk.Tk() win.title("Python GUI") tabControl = ttk.Notebook(win) tab1 = ttk.Frame(tabControl) tabControl.add(tab1, text='Tab 1') tab2 = ttk.Frame(tabControl) tabControl.add(tab2, text='Tab 2') tabControl.pack(expand=1, fill="both") mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) for child in mighty.winfo_children(): child.grid_configure(padx=8) win.mainloop()
true
true
f72c8ecfbd321747538079c852e41d9f1f85d700
3,446
py
Python
sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_validate.py
kashifkhan/azure-sdk-for-python
9c28b76e89b0855e41bd12d5b4a59b51acd47eec
[ "MIT" ]
null
null
null
sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_validate.py
kashifkhan/azure-sdk-for-python
9c28b76e89b0855e41bd12d5b4a59b51acd47eec
[ "MIT" ]
null
null
null
sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_validate.py
kashifkhan/azure-sdk-for-python
9c28b76e89b0855e41bd12d5b4a59b51acd47eec
[ "MIT" ]
null
null
null
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import functools from ._version import VERSIONS_SUPPORTED def check_for_unsupported_actions_types(*args, **kwargs): client = args[0] # this assumes the client has an _api_version attribute selected_api_version = client._api_version # pylint: disable=protected-access if "actions" not in kwargs: actions = args[2] else: actions = kwargs.get("actions") if actions is None: return actions_version_mapping = { "2022-03-01-preview": [ "ExtractSummaryAction", "RecognizeCustomEntitiesAction", "SingleCategoryClassifyAction", "MultiCategoryClassifyAction" ] } unsupported = { arg: version for version, args in actions_version_mapping.items() for arg in args if arg in [action.__class__.__name__ for action in actions] and selected_api_version != version and VERSIONS_SUPPORTED.index(selected_api_version) < VERSIONS_SUPPORTED.index(version) } if unsupported: error_strings = [ f"'{param}' is only available for API version {version} and up.\n" for param, version in unsupported.items() ] raise ValueError("".join(error_strings)) def validate_multiapi_args(**kwargs): args_mapping = kwargs.pop("args_mapping", None) version_method_added = kwargs.pop("version_method_added", None) custom_wrapper = kwargs.pop("custom_wrapper", None) def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: # this assumes the client has an _api_version attribute client = args[0] selected_api_version = client._api_version # pylint: disable=protected-access except AttributeError: return func(*args, **kwargs) # the latest version is selected, we assume all features supported if selected_api_version == VERSIONS_SUPPORTED[-1]: return func(*args, **kwargs) if version_method_added and version_method_added != selected_api_version and \ VERSIONS_SUPPORTED.index(selected_api_version) < VERSIONS_SUPPORTED.index(version_method_added): raise ValueError(f"'{func.__name__}' is only available for API version {version_method_added} and up.") if args_mapping: unsupported = { arg: version for version, args in args_mapping.items() for arg in args if arg in kwargs.keys() and selected_api_version != version and VERSIONS_SUPPORTED.index(selected_api_version) < VERSIONS_SUPPORTED.index(version) } if unsupported: error_strings = [ f"'{param}' is only available for API version {version} and up.\n" for param, version in unsupported.items() ] raise ValueError("".join(error_strings)) if custom_wrapper: custom_wrapper(*args, **kwargs) return func(*args, **kwargs) return wrapper return decorator
35.163265
119
0.589089
import functools from ._version import VERSIONS_SUPPORTED def check_for_unsupported_actions_types(*args, **kwargs): client = args[0] selected_api_version = client._api_version if "actions" not in kwargs: actions = args[2] else: actions = kwargs.get("actions") if actions is None: return actions_version_mapping = { "2022-03-01-preview": [ "ExtractSummaryAction", "RecognizeCustomEntitiesAction", "SingleCategoryClassifyAction", "MultiCategoryClassifyAction" ] } unsupported = { arg: version for version, args in actions_version_mapping.items() for arg in args if arg in [action.__class__.__name__ for action in actions] and selected_api_version != version and VERSIONS_SUPPORTED.index(selected_api_version) < VERSIONS_SUPPORTED.index(version) } if unsupported: error_strings = [ f"'{param}' is only available for API version {version} and up.\n" for param, version in unsupported.items() ] raise ValueError("".join(error_strings)) def validate_multiapi_args(**kwargs): args_mapping = kwargs.pop("args_mapping", None) version_method_added = kwargs.pop("version_method_added", None) custom_wrapper = kwargs.pop("custom_wrapper", None) def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: client = args[0] selected_api_version = client._api_version except AttributeError: return func(*args, **kwargs) if selected_api_version == VERSIONS_SUPPORTED[-1]: return func(*args, **kwargs) if version_method_added and version_method_added != selected_api_version and \ VERSIONS_SUPPORTED.index(selected_api_version) < VERSIONS_SUPPORTED.index(version_method_added): raise ValueError(f"'{func.__name__}' is only available for API version {version_method_added} and up.") if args_mapping: unsupported = { arg: version for version, args in args_mapping.items() for arg in args if arg in kwargs.keys() and selected_api_version != version and VERSIONS_SUPPORTED.index(selected_api_version) < VERSIONS_SUPPORTED.index(version) } if unsupported: error_strings = [ f"'{param}' is only available for API version {version} and up.\n" for param, version in unsupported.items() ] raise ValueError("".join(error_strings)) if custom_wrapper: custom_wrapper(*args, **kwargs) return func(*args, **kwargs) return wrapper return decorator
true
true
f72c8ed99253eaa655d08778cb9bf6fa834191af
10,956
py
Python
google/ads/google_ads/v0/proto/resources/shared_criterion_pb2.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
google/ads/google_ads/v0/proto/resources/shared_criterion_pb2.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
google/ads/google_ads/v0/proto/resources/shared_criterion_pb2.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v0/proto/resources/shared_criterion.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.ads.google_ads.v0.proto.common import criteria_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2 from google.ads.google_ads.v0.proto.enums import criterion_type_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_enums_dot_criterion__type__pb2 from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/ads/googleads_v0/proto/resources/shared_criterion.proto', package='google.ads.googleads.v0.resources', syntax='proto3', serialized_options=_b('\n%com.google.ads.googleads.v0.resourcesB\024SharedCriterionProtoP\001ZJgoogle.golang.org/genproto/googleapis/ads/googleads/v0/resources;resources\242\002\003GAA\252\002!Google.Ads.GoogleAds.V0.Resources\312\002!Google\\Ads\\GoogleAds\\V0\\Resources\352\002%Google::Ads::GoogleAds::V0::Resources'), serialized_pb=_b('\n>google/ads/googleads_v0/proto/resources/shared_criterion.proto\x12!google.ads.googleads.v0.resources\x1a\x33google/ads/googleads_v0/proto/common/criteria.proto\x1a\x38google/ads/googleads_v0/proto/enums/criterion_type.proto\x1a\x1egoogle/protobuf/wrappers.proto\"\xdc\x04\n\x0fSharedCriterion\x12\x15\n\rresource_name\x18\x01 \x01(\t\x12\x30\n\nshared_set\x18\x02 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0c\x63riterion_id\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int64Value\x12L\n\x04type\x18\x04 \x01(\x0e\x32>.google.ads.googleads.v0.enums.CriterionTypeEnum.CriterionType\x12>\n\x07keyword\x18\x03 \x01(\x0b\x32+.google.ads.googleads.v0.common.KeywordInfoH\x00\x12I\n\ryoutube_video\x18\x05 \x01(\x0b\x32\x30.google.ads.googleads.v0.common.YouTubeVideoInfoH\x00\x12M\n\x0fyoutube_channel\x18\x06 \x01(\x0b\x32\x32.google.ads.googleads.v0.common.YouTubeChannelInfoH\x00\x12\x42\n\tplacement\x18\x07 \x01(\x0b\x32-.google.ads.googleads.v0.common.PlacementInfoH\x00\x12T\n\x13mobile_app_category\x18\x08 \x01(\x0b\x32\x35.google.ads.googleads.v0.common.MobileAppCategoryInfoH\x00\x42\x0b\n\tcriterionB\x81\x02\n%com.google.ads.googleads.v0.resourcesB\x14SharedCriterionProtoP\x01ZJgoogle.golang.org/genproto/googleapis/ads/googleads/v0/resources;resources\xa2\x02\x03GAA\xaa\x02!Google.Ads.GoogleAds.V0.Resources\xca\x02!Google\\Ads\\GoogleAds\\V0\\Resources\xea\x02%Google::Ads::GoogleAds::V0::Resourcesb\x06proto3') , dependencies=[google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2.DESCRIPTOR,google_dot_ads_dot_googleads__v0_dot_proto_dot_enums_dot_criterion__type__pb2.DESCRIPTOR,google_dot_protobuf_dot_wrappers__pb2.DESCRIPTOR,]) _SHAREDCRITERION = _descriptor.Descriptor( name='SharedCriterion', full_name='google.ads.googleads.v0.resources.SharedCriterion', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='resource_name', full_name='google.ads.googleads.v0.resources.SharedCriterion.resource_name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='shared_set', full_name='google.ads.googleads.v0.resources.SharedCriterion.shared_set', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='criterion_id', full_name='google.ads.googleads.v0.resources.SharedCriterion.criterion_id', index=2, number=26, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='type', full_name='google.ads.googleads.v0.resources.SharedCriterion.type', index=3, number=4, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='keyword', full_name='google.ads.googleads.v0.resources.SharedCriterion.keyword', index=4, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='youtube_video', full_name='google.ads.googleads.v0.resources.SharedCriterion.youtube_video', index=5, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='youtube_channel', full_name='google.ads.googleads.v0.resources.SharedCriterion.youtube_channel', index=6, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='placement', full_name='google.ads.googleads.v0.resources.SharedCriterion.placement', index=7, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='mobile_app_category', full_name='google.ads.googleads.v0.resources.SharedCriterion.mobile_app_category', index=8, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='criterion', full_name='google.ads.googleads.v0.resources.SharedCriterion.criterion', index=0, containing_type=None, fields=[]), ], serialized_start=245, serialized_end=849, ) _SHAREDCRITERION.fields_by_name['shared_set'].message_type = google_dot_protobuf_dot_wrappers__pb2._STRINGVALUE _SHAREDCRITERION.fields_by_name['criterion_id'].message_type = google_dot_protobuf_dot_wrappers__pb2._INT64VALUE _SHAREDCRITERION.fields_by_name['type'].enum_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_enums_dot_criterion__type__pb2._CRITERIONTYPEENUM_CRITERIONTYPE _SHAREDCRITERION.fields_by_name['keyword'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._KEYWORDINFO _SHAREDCRITERION.fields_by_name['youtube_video'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._YOUTUBEVIDEOINFO _SHAREDCRITERION.fields_by_name['youtube_channel'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._YOUTUBECHANNELINFO _SHAREDCRITERION.fields_by_name['placement'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._PLACEMENTINFO _SHAREDCRITERION.fields_by_name['mobile_app_category'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._MOBILEAPPCATEGORYINFO _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['keyword']) _SHAREDCRITERION.fields_by_name['keyword'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['youtube_video']) _SHAREDCRITERION.fields_by_name['youtube_video'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['youtube_channel']) _SHAREDCRITERION.fields_by_name['youtube_channel'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['placement']) _SHAREDCRITERION.fields_by_name['placement'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['mobile_app_category']) _SHAREDCRITERION.fields_by_name['mobile_app_category'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] DESCRIPTOR.message_types_by_name['SharedCriterion'] = _SHAREDCRITERION _sym_db.RegisterFileDescriptor(DESCRIPTOR) SharedCriterion = _reflection.GeneratedProtocolMessageType('SharedCriterion', (_message.Message,), dict( DESCRIPTOR = _SHAREDCRITERION, __module__ = 'google.ads.googleads_v0.proto.resources.shared_criterion_pb2' , __doc__ = """A criterion belonging to a shared set. Attributes: resource_name: The resource name of the shared criterion. Shared set resource names have the form: ``customers/{customer_id}/sharedCriteria /{shared_set_id}_{criterion_id}`` shared_set: The shared set to which the shared criterion belongs. criterion_id: The ID of the criterion. This field is ignored for mutates. type: The type of the criterion. criterion: The criterion. Exactly one must be set. keyword: Keyword. youtube_video: YouTube Video. youtube_channel: YouTube Channel. placement: Placement. mobile_app_category: Mobile App Category. """, # @@protoc_insertion_point(class_scope:google.ads.googleads.v0.resources.SharedCriterion) )) _sym_db.RegisterMessage(SharedCriterion) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
59.221622
1,457
0.793264
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database _sym_db = _symbol_database.Default() from google.ads.google_ads.v0.proto.common import criteria_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2 from google.ads.google_ads.v0.proto.enums import criterion_type_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_enums_dot_criterion__type__pb2 from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/ads/googleads_v0/proto/resources/shared_criterion.proto', package='google.ads.googleads.v0.resources', syntax='proto3', serialized_options=_b('\n%com.google.ads.googleads.v0.resourcesB\024SharedCriterionProtoP\001ZJgoogle.golang.org/genproto/googleapis/ads/googleads/v0/resources;resources\242\002\003GAA\252\002!Google.Ads.GoogleAds.V0.Resources\312\002!Google\\Ads\\GoogleAds\\V0\\Resources\352\002%Google::Ads::GoogleAds::V0::Resources'), serialized_pb=_b('\n>google/ads/googleads_v0/proto/resources/shared_criterion.proto\x12!google.ads.googleads.v0.resources\x1a\x33google/ads/googleads_v0/proto/common/criteria.proto\x1a\x38google/ads/googleads_v0/proto/enums/criterion_type.proto\x1a\x1egoogle/protobuf/wrappers.proto\"\xdc\x04\n\x0fSharedCriterion\x12\x15\n\rresource_name\x18\x01 \x01(\t\x12\x30\n\nshared_set\x18\x02 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0c\x63riterion_id\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int64Value\x12L\n\x04type\x18\x04 \x01(\x0e\x32>.google.ads.googleads.v0.enums.CriterionTypeEnum.CriterionType\x12>\n\x07keyword\x18\x03 \x01(\x0b\x32+.google.ads.googleads.v0.common.KeywordInfoH\x00\x12I\n\ryoutube_video\x18\x05 \x01(\x0b\x32\x30.google.ads.googleads.v0.common.YouTubeVideoInfoH\x00\x12M\n\x0fyoutube_channel\x18\x06 \x01(\x0b\x32\x32.google.ads.googleads.v0.common.YouTubeChannelInfoH\x00\x12\x42\n\tplacement\x18\x07 \x01(\x0b\x32-.google.ads.googleads.v0.common.PlacementInfoH\x00\x12T\n\x13mobile_app_category\x18\x08 \x01(\x0b\x32\x35.google.ads.googleads.v0.common.MobileAppCategoryInfoH\x00\x42\x0b\n\tcriterionB\x81\x02\n%com.google.ads.googleads.v0.resourcesB\x14SharedCriterionProtoP\x01ZJgoogle.golang.org/genproto/googleapis/ads/googleads/v0/resources;resources\xa2\x02\x03GAA\xaa\x02!Google.Ads.GoogleAds.V0.Resources\xca\x02!Google\\Ads\\GoogleAds\\V0\\Resources\xea\x02%Google::Ads::GoogleAds::V0::Resourcesb\x06proto3') , dependencies=[google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2.DESCRIPTOR,google_dot_ads_dot_googleads__v0_dot_proto_dot_enums_dot_criterion__type__pb2.DESCRIPTOR,google_dot_protobuf_dot_wrappers__pb2.DESCRIPTOR,]) _SHAREDCRITERION = _descriptor.Descriptor( name='SharedCriterion', full_name='google.ads.googleads.v0.resources.SharedCriterion', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='resource_name', full_name='google.ads.googleads.v0.resources.SharedCriterion.resource_name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='shared_set', full_name='google.ads.googleads.v0.resources.SharedCriterion.shared_set', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='criterion_id', full_name='google.ads.googleads.v0.resources.SharedCriterion.criterion_id', index=2, number=26, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='type', full_name='google.ads.googleads.v0.resources.SharedCriterion.type', index=3, number=4, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='keyword', full_name='google.ads.googleads.v0.resources.SharedCriterion.keyword', index=4, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='youtube_video', full_name='google.ads.googleads.v0.resources.SharedCriterion.youtube_video', index=5, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='youtube_channel', full_name='google.ads.googleads.v0.resources.SharedCriterion.youtube_channel', index=6, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='placement', full_name='google.ads.googleads.v0.resources.SharedCriterion.placement', index=7, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='mobile_app_category', full_name='google.ads.googleads.v0.resources.SharedCriterion.mobile_app_category', index=8, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='criterion', full_name='google.ads.googleads.v0.resources.SharedCriterion.criterion', index=0, containing_type=None, fields=[]), ], serialized_start=245, serialized_end=849, ) _SHAREDCRITERION.fields_by_name['shared_set'].message_type = google_dot_protobuf_dot_wrappers__pb2._STRINGVALUE _SHAREDCRITERION.fields_by_name['criterion_id'].message_type = google_dot_protobuf_dot_wrappers__pb2._INT64VALUE _SHAREDCRITERION.fields_by_name['type'].enum_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_enums_dot_criterion__type__pb2._CRITERIONTYPEENUM_CRITERIONTYPE _SHAREDCRITERION.fields_by_name['keyword'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._KEYWORDINFO _SHAREDCRITERION.fields_by_name['youtube_video'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._YOUTUBEVIDEOINFO _SHAREDCRITERION.fields_by_name['youtube_channel'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._YOUTUBECHANNELINFO _SHAREDCRITERION.fields_by_name['placement'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._PLACEMENTINFO _SHAREDCRITERION.fields_by_name['mobile_app_category'].message_type = google_dot_ads_dot_googleads__v0_dot_proto_dot_common_dot_criteria__pb2._MOBILEAPPCATEGORYINFO _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['keyword']) _SHAREDCRITERION.fields_by_name['keyword'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['youtube_video']) _SHAREDCRITERION.fields_by_name['youtube_video'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['youtube_channel']) _SHAREDCRITERION.fields_by_name['youtube_channel'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['placement']) _SHAREDCRITERION.fields_by_name['placement'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] _SHAREDCRITERION.oneofs_by_name['criterion'].fields.append( _SHAREDCRITERION.fields_by_name['mobile_app_category']) _SHAREDCRITERION.fields_by_name['mobile_app_category'].containing_oneof = _SHAREDCRITERION.oneofs_by_name['criterion'] DESCRIPTOR.message_types_by_name['SharedCriterion'] = _SHAREDCRITERION _sym_db.RegisterFileDescriptor(DESCRIPTOR) SharedCriterion = _reflection.GeneratedProtocolMessageType('SharedCriterion', (_message.Message,), dict( DESCRIPTOR = _SHAREDCRITERION, __module__ = 'google.ads.googleads_v0.proto.resources.shared_criterion_pb2' , __doc__ = """A criterion belonging to a shared set. Attributes: resource_name: The resource name of the shared criterion. Shared set resource names have the form: ``customers/{customer_id}/sharedCriteria /{shared_set_id}_{criterion_id}`` shared_set: The shared set to which the shared criterion belongs. criterion_id: The ID of the criterion. This field is ignored for mutates. type: The type of the criterion. criterion: The criterion. Exactly one must be set. keyword: Keyword. youtube_video: YouTube Video. youtube_channel: YouTube Channel. placement: Placement. mobile_app_category: Mobile App Category. """, # @@protoc_insertion_point(class_scope:google.ads.googleads.v0.resources.SharedCriterion) )) _sym_db.RegisterMessage(SharedCriterion) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
true
true
f72c907b1f918fdf342d234b59f8c92fc6aa1d93
2,070
py
Python
cows_bulls.py
hmlewis-astro/coding_practice
a781443399766bf13df0d2de93f0ce3acda0c77d
[ "MIT" ]
null
null
null
cows_bulls.py
hmlewis-astro/coding_practice
a781443399766bf13df0d2de93f0ce3acda0c77d
[ "MIT" ]
null
null
null
cows_bulls.py
hmlewis-astro/coding_practice
a781443399766bf13df0d2de93f0ce3acda0c77d
[ "MIT" ]
null
null
null
''' File name: pythonpractice.py Author: Hannah Lewis Date created: 08/03/2020 Date last modified: 08/03/2020 Python Version: 3.7 ''' import random def main(): ''' Create a program that will play the “cows and bulls” game with the user. ''' print("You will try to guess a random 4-digit number.") print("A 'cow' is a correct digit in the correct place.") print("A 'bull' is a correct digit in the wrong place.") print("The game ends when you get 4 cows!\n") print("You can type 'exit' at any time to end the game.\n") num = str(random.randint(10000, 99999))[1:5] # Get random number, remove first digit so that first digit can be 0 guess = input("Give me your best guess: ") # Get first guess count = 0 cow = 0 bull = 0 guessing = True while guessing: assert len(guess) == 4, "Input must be 4-digits long." if guess == 'exit': # Player can exit at any time print("The number was " + str(num) + ".") print("Better luck next time.") guessing = False break count += 1 for i in range(0,4): # Compare digits if num[i] == guess[i]: cow+=1 elif num[i] in guess: bull+=1 print("You got {} cows, and {} bulls.".format(cow,bull)) # How many cows and bulls if cow == 4: # If all digits are correct if count == 1: print("You got it on the first try!") guessing = False if count > 1: print("You got it! It took you", count, "tries.") print("The number was " + str(num) + ".") guessing = False else: # Guess again cow = bull = 0 guess = input("Guess again: ") #TODO: ask if they want to play another game return if __name__ == '__main__': print("Ready to Cows and Bulls?") main() # Runs exercise
27.972973
117
0.522705
import random def main(): print("You will try to guess a random 4-digit number.") print("A 'cow' is a correct digit in the correct place.") print("A 'bull' is a correct digit in the wrong place.") print("The game ends when you get 4 cows!\n") print("You can type 'exit' at any time to end the game.\n") num = str(random.randint(10000, 99999))[1:5] guess = input("Give me your best guess: ") count = 0 cow = 0 bull = 0 guessing = True while guessing: assert len(guess) == 4, "Input must be 4-digits long." if guess == 'exit': print("The number was " + str(num) + ".") print("Better luck next time.") guessing = False break count += 1 for i in range(0,4): if num[i] == guess[i]: cow+=1 elif num[i] in guess: bull+=1 print("You got {} cows, and {} bulls.".format(cow,bull)) if cow == 4: if count == 1: print("You got it on the first try!") guessing = False if count > 1: print("You got it! It took you", count, "tries.") print("The number was " + str(num) + ".") guessing = False else: cow = bull = 0 guess = input("Guess again: ") return if __name__ == '__main__': print("Ready to Cows and Bulls?") main()
true
true
f72c90b37b41d597ef1c839e1131577727a7329a
227
py
Python
game/admin.py
zxalif/simpleapi
89d9f1c81b7c8e46d9764573fc1070a453751b4a
[ "MIT" ]
null
null
null
game/admin.py
zxalif/simpleapi
89d9f1c81b7c8e46d9764573fc1070a453751b4a
[ "MIT" ]
8
2020-06-05T23:34:44.000Z
2022-02-10T09:11:05.000Z
game/admin.py
zxalif/simpleapi
89d9f1c81b7c8e46d9764573fc1070a453751b4a
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import ( Category, Game, Thread, ThreadImage ) admin.site.register(Category) admin.site.register(Game) admin.site.register(Thread) admin.site.register(ThreadImage)
17.461538
32
0.748899
from django.contrib import admin from .models import ( Category, Game, Thread, ThreadImage ) admin.site.register(Category) admin.site.register(Game) admin.site.register(Thread) admin.site.register(ThreadImage)
true
true
f72c9168c0692e02e3f54b61d9c5f5e6399fc4d3
867
py
Python
blog/pelican-plugins/headerid/headerid.py
lemonsong/lemonsong.github.io
14a65b8c2506c95bab64f50143f3850be3edadc1
[ "MIT" ]
null
null
null
blog/pelican-plugins/headerid/headerid.py
lemonsong/lemonsong.github.io
14a65b8c2506c95bab64f50143f3850be3edadc1
[ "MIT" ]
1
2022-01-10T04:39:05.000Z
2022-01-10T04:39:05.000Z
blog/pelican-plugins/headerid/headerid.py
lemonsong/lemonsong.github.io
14a65b8c2506c95bab64f50143f3850be3edadc1
[ "MIT" ]
null
null
null
from pelican import readers from pelican.readers import PelicanHTMLTranslator from pelican import signals from docutils import nodes def register(): class HeaderIDPatchedPelicanHTMLTranslator(PelicanHTMLTranslator): def depart_title(self, node): close_tag = self.context[-1] parent = node.parent if isinstance(parent, nodes.section) and parent.hasattr('ids') and parent['ids']: anchor_name = parent['ids'][0] # add permalink anchor if close_tag.startswith('</h'): self.body.append( '<a class="headerlink" href="#%s" title="Permalink to this headline">*</a>' % anchor_name ) PelicanHTMLTranslator.depart_title(self, node) readers.PelicanHTMLTranslator = HeaderIDPatchedPelicanHTMLTranslator
43.35
113
0.635525
from pelican import readers from pelican.readers import PelicanHTMLTranslator from pelican import signals from docutils import nodes def register(): class HeaderIDPatchedPelicanHTMLTranslator(PelicanHTMLTranslator): def depart_title(self, node): close_tag = self.context[-1] parent = node.parent if isinstance(parent, nodes.section) and parent.hasattr('ids') and parent['ids']: anchor_name = parent['ids'][0] if close_tag.startswith('</h'): self.body.append( '<a class="headerlink" href="#%s" title="Permalink to this headline">*</a>' % anchor_name ) PelicanHTMLTranslator.depart_title(self, node) readers.PelicanHTMLTranslator = HeaderIDPatchedPelicanHTMLTranslator
true
true
f72c916ef8e95900c5ab3a87d685611c982bda39
2,960
py
Python
linsae/cogs/Events.py
drakedeveloper/Linsae
1a866fbb95df3a7270e446dca18e9dca8beb2c3a
[ "Apache-2.0" ]
1
2019-06-27T00:47:21.000Z
2019-06-27T00:47:21.000Z
linsae/cogs/Events.py
drakedeveloper/Linsae
1a866fbb95df3a7270e446dca18e9dca8beb2c3a
[ "Apache-2.0" ]
null
null
null
linsae/cogs/Events.py
drakedeveloper/Linsae
1a866fbb95df3a7270e446dca18e9dca8beb2c3a
[ "Apache-2.0" ]
null
null
null
import discord import time import asyncio from datetime import datetime import time from discord.ext import tasks, commands from tinydb import TinyDB, Query import re class Events(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_guild_join(self, guild): role = await guild.create_role(name="Muted", colour=discord.Colour.dark_grey()) for channel in guild.channels: await channel.set_permissions(role, send_messages = False) await asyncio.sleep(delay=5) for member in guild.members: if member.guild_permissions.administrator and member.id != self.bot.user.id: join_message = discord.Embed(title="__**Linsae!**__", description=f"**Hello, {member.mention}, This is me linsae and in order for me to work you need to do some configuration, sooo let's get started!**", colour=0x4298f4, timestamp=datetime.utcnow()) join_message.add_field(name="__Knowledge__", value=f"""**First of all, {member.mention} let me introduce my self: - My name as you know is Linsae and i'm glad to meet you. - My developer is Ɗrake#7418 and if you need any help with bots or something feel free to contact him! - My birthday is 6/25/2019.**""") join_message.add_field(name="__Configuration__", value=""" Alright so i'm a support bot that helps moderators and make their lifes easier, so what do i do ? .If a member needs help with something he can just type ***?support*** in a specific channel that i will menion later. .i have many moderator commands like ban, warn, kick, mute and more.... --> Now in order to do all that the i need to config somethings in the server and don't worry i won't do harm to it!i will just create some channels and roles and ask you things but for that to work you need to type ***?ticketconfig*** in any channel and i will give you instructions!""") join_message.set_footer( text="For more help just try to read this embed again or contact the developer!", icon_url=self.bot.user.avatar_url) join_message.set_author(name=self.bot.user) join_message.set_thumbnail(url=guild.icon_url) await member.send(embed=join_message) @commands.Cog.listener() async def on_message(self, message): if str(message.channel) == "ticket-request": if message.content != "?support": await message.delete() if message.content == "nigga" or message.content == "nigger" or message.content == "nigro": await message.delete() await message.channel.send("You can't say that!") def setup(bot): bot.add_cog(Events(bot))
55.849057
294
0.631419
import discord import time import asyncio from datetime import datetime import time from discord.ext import tasks, commands from tinydb import TinyDB, Query import re class Events(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_guild_join(self, guild): role = await guild.create_role(name="Muted", colour=discord.Colour.dark_grey()) for channel in guild.channels: await channel.set_permissions(role, send_messages = False) await asyncio.sleep(delay=5) for member in guild.members: if member.guild_permissions.administrator and member.id != self.bot.user.id: join_message = discord.Embed(title="__**Linsae!**__", description=f"**Hello, {member.mention}, This is me linsae and in order for me to work you need to do some configuration, sooo let's get started!**", colour=0x4298f4, timestamp=datetime.utcnow()) join_message.add_field(name="__Knowledge__", value=f"""**First of all, {member.mention} let me introduce my self: - My name as you know is Linsae and i'm glad to meet you. - My developer is Ɗrake#7418 and if you need any help with bots or something feel free to contact him! - My birthday is 6/25/2019.**""") join_message.add_field(name="__Configuration__", value=""" Alright so i'm a support bot that helps moderators and make their lifes easier, so what do i do ? .If a member needs help with something he can just type ***?support*** in a specific channel that i will menion later. .i have many moderator commands like ban, warn, kick, mute and more.... --> Now in order to do all that the i need to config somethings in the server and don't worry i won't do harm to it!i will just create some channels and roles and ask you things but for that to work you need to type ***?ticketconfig*** in any channel and i will give you instructions!""") join_message.set_footer( text="For more help just try to read this embed again or contact the developer!", icon_url=self.bot.user.avatar_url) join_message.set_author(name=self.bot.user) join_message.set_thumbnail(url=guild.icon_url) await member.send(embed=join_message) @commands.Cog.listener() async def on_message(self, message): if str(message.channel) == "ticket-request": if message.content != "?support": await message.delete() if message.content == "nigga" or message.content == "nigger" or message.content == "nigro": await message.delete() await message.channel.send("You can't say that!") def setup(bot): bot.add_cog(Events(bot))
true
true