index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
40,490
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/tree_aggregation.py
51,53
35,65
next
ValueGenerator
62,65
53,65
class ValueGenerator(metaclass=abc.ABCMeta): """Base class establishing interface for stateful value generation. A `ValueGenerator` maintains a state, and each time `next` is called, a new value is generated and the state is advanced. """ @abc.abstractmethod def initialize(self): """Makes an initializ...
class ValueGenerator(metaclass=abc.ABCMeta): """Base class establishing interface for stateful value generation. A `ValueGenerator` maintains a state, and each time `next` is called, a new value is generated and the state is advanced. """ @abc.abstractmethod def initialize(self): """Makes an initializ...
raise NotImplementedError
"""Gets next value and advances the ValueGenerator. Args: state: The current state. Returns: A pair (value, new_state) where value is the next value and new_state is the advanced state. """ raise NotImplementedError
2
207
13
220
# Copyright 2021, The TensorFlow 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 t...
# Copyright 2021, The TensorFlow 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 t...
40,495
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/tree_aggregation_query_test.py
446,456
380,482
test_scalar_tree_aggregation_reset
TreeResidualQueryTest
456,482
456,482
class TreeResidualQueryTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('r5d10n0s1s16eff', 5, 10, 0., 1, 16, 0.1, True), ('r3d5n1s1s32eff', 3, 5, 1., 1, 32, 1., True), ('r10d3n1s2s16eff', 10, 3, 1., 2, 16, 10., True), ('r10d3n1s2s16', 10, 3, 1., 2, 16, 10., Fa...
class TreeResidualQueryTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('r5d10n0s1s16eff', 5, 10, 0., 1, 16, 0.1, True), ('r3d5n1s1s32eff', 3, 5, 1., 1, 32, 1., True), ('r10d3n1s2s16eff', 10, 3, 1., 2, 16, 10., True), ('r10d3n1s2s16', 10, 3, 1., 2, 16, 10., Fa...
total_steps = 20 query = tree_aggregation_query.TreeResidualSumQuery( clip_fn=_get_l2_clip_fn(), clip_value=scalar_value + 1., # no clip noise_generator=lambda: tree_node_value, record_specs=tf.TensorSpec([]), use_efficient=False) global_state = query.initial_global_...
total_steps = 20 query = tree_aggregation_query.TreeResidualSumQuery( clip_fn=_get_l2_clip_fn(), clip_value=scalar_value + 1., # no clip noise_generator=lambda: tree_node_value, record_specs=tf.TensorSpec([]), use_efficient=False) global_state = query.initial_global_...
111
1,143
393
1,536
# Copyright 2021, The TensorFlow 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 t...
# Copyright 2021, The TensorFlow 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 t...
40,496
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/tree_aggregation_test.py
31,32
23,35
next
ConstantValueGenerator
32,35
32,35
class ConstantValueGenerator(tree_aggregation.ValueGenerator): def __init__(self, constant_value): self.constant_value = constant_value def initialize(self): return () def next(self, state): FILL_FUNC_BODY
class ConstantValueGenerator(tree_aggregation.ValueGenerator): def __init__(self, constant_value): self.constant_value = constant_value def initialize(self): return () def next(self, state): FILL_FUNC_BODY
return self.constant_value, state
return self.constant_value, state
3
71
15
86
# Copyright 2021, Google LLC. # # 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...
# Copyright 2021, Google LLC. # # 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...
40,498
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/dp_query/tree_aggregation_test.py
316,318
301,399
return_noise
GaussianNoiseGeneratorTest
318,321
318,321
class GaussianNoiseGeneratorTest(tf.test.TestCase, parameterized.TestCase): def assertStateEqual(self, state1, state2): for s1, s2 in zip(tf.nest.flatten(state1), tf.nest.flatten(state2)): self.assertAllEqual(s1, s2) def test_random_generator_tf(self, noise_mean=1.0, ...
class GaussianNoiseGeneratorTest(tf.test.TestCase, parameterized.TestCase): def assertStateEqual(self, state1, state2): for s1, s2 in zip(tf.nest.flatten(state1), tf.nest.flatten(state2)): self.assertAllEqual(s1, s2) def test_random_generator_tf(self, noise_mean=1.0, ...
value, state = g.next(state) return noise_mean + value, state
value, state = g.next(state) return noise_mean + value, state
9
1,422
26
1,448
# Copyright 2021, Google LLC. # # 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...
# Copyright 2021, Google LLC. # # 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...
40,502
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/estimators/binary_class_head_test.py
26,27
23,79
testLoss
DPBinaryClassHeadTest
28,47
27,47
class DPBinaryClassHeadTest(tf.test.TestCase): """Tests for DP-enabled binary class heads.""" def testLoss(self): FILL_FUNC_BODY def testCreateTPUEstimatorSpec(self): """Tests that an Estimator built with this head works.""" train_features, train_labels = test_utils.make_input_data(256, 2) feature_co...
class DPBinaryClassHeadTest(tf.test.TestCase): """Tests for DP-enabled binary class heads.""" def testLoss(self): """Tests loss() returns per-example losses.""" FILL_FUNC_BODY def testCreateTPUEstimatorSpec(self): """Tests that an Estimator built with this head works.""" train_features, train_labels ...
head = binary_class_head.DPBinaryClassHead() features = {'feature_a': np.full((4), 1.0)} labels = np.array([[1.0], [1.0], [1.0], [0.0]]) logits = np.full((4, 1), 0.5) actual_loss = head.loss(labels, logits, features) expected_loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=label...
"""Tests loss() returns per-example losses.""" head = binary_class_head.DPBinaryClassHead() features = {'feature_a': np.full((4), 1.0)} labels = np.array([[1.0], [1.0], [1.0], [0.0]]) logits = np.full((4, 1), 0.5) actual_loss = head.loss(labels, logits, features) expected_loss = tf.nn.sigm...
42
448
251
699
# Copyright 2020, The TensorFlow 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 t...
# Copyright 2020, The TensorFlow 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 t...
40,503
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/estimators/head_utils.py
20,22
1,57
binary_or_multi_class_head
45,57
22,57
# Copyright 2020, The TensorFlow 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 t...
# Copyright 2020, The TensorFlow 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 t...
if n_classes == 2: head = DPBinaryClassHead( weight_column=weight_column, label_vocabulary=label_vocabulary, loss_reduction=loss_reduction) else: head = DPMultiClassHead( n_classes, weight_column=weight_column, label_vocabulary=label_vocabulary, loss_r...
"""Creates either binary or multi-class head. Args: n_classes: Number of label classes. weight_column: A string or a `NumericColumn` created by `tf.feature_column.numeric_column` defining feature column representing weights. It is used to down weight or boost examples during training. It ...
20
625
127
752
# Copyright 2020, The TensorFlow 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 t...
# Copyright 2020, The TensorFlow 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 t...
40,504
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/estimators/v1/dnn.py
49,50
24,70
_model_fn
DNNClassifier
51,65
50,65
class DNNClassifier(estimator.Estimator): """DP version of `tf.compat.v1.estimator.DNNClassifier`.""" def __init__( self, hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None, label_vocabulary=None, optimizer='Adagrad', activation_fn=t...
class DNNClassifier(estimator.Estimator): """DP version of `tf.compat.v1.estimator.DNNClassifier`.""" def __init__( self, hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None, label_vocabulary=None, optimizer='Adagrad', activation_fn=t...
return dnn._dnn_model_fn( # pylint: disable=protected-access features=features, labels=labels, mode=mode, head=head, hidden_units=hidden_units, feature_columns=tuple(feature_columns or []), optimizer=optimizer, activation_fn=activati...
"""Call the defined shared dnn_model_fn.""" return dnn._dnn_model_fn( # pylint: disable=protected-access features=features, labels=labels, mode=mode, head=head, hidden_units=hidden_units, feature_columns=tuple(feature_columns or []), opt...
19
384
149
533
# Copyright 2020 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 applica...
# Copyright 2020 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 applica...
40,505
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/estimators/v1/linear.py
53,54
23,73
_model_fn
LinearClassifier
55,67
54,67
class LinearClassifier(estimator.Estimator): """DP version of `tf.compat.v1.estimator.LinearClassifier`.""" def __init__( self, feature_columns, model_dir=None, n_classes=2, weight_column=None, label_vocabulary=None, optimizer='Ftrl', config=None, partitioner=N...
class LinearClassifier(estimator.Estimator): """DP version of `tf.compat.v1.estimator.LinearClassifier`.""" def __init__( self, feature_columns, model_dir=None, n_classes=2, weight_column=None, label_vocabulary=None, optimizer='Ftrl', config=None, partitioner=N...
return linear._linear_model_fn( # pylint: disable=protected-access features=features, labels=labels, mode=mode, head=head, feature_columns=tuple(feature_columns or []), optimizer=optimizer, partitioner=partitioner, config=config, ...
"""Call the defined shared _linear_model_fn.""" return linear._linear_model_fn( # pylint: disable=protected-access features=features, labels=labels, mode=mode, head=head, feature_columns=tuple(feature_columns or []), optimizer=optimizer, ...
17
453
114
567
# Copyright 2023 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 applica...
# Copyright 2023 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 applica...
40,506
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/estimators/v1/linear_test.py
32,40
27,79
testRunsWithoutErrors
DPLinearClassifierClassifierTest
40,79
40,79
class DPLinearClassifierClassifierTest( tf.test.TestCase, parameterized.TestCase ): """Tests for DP-enabled LinearClassifier.""" @parameterized.named_parameters( ('BinaryClassLinear 1', 2, 1), ('BinaryClassLinear 4', 2, 4), ('MultiClassLinear 3', 3, 1), ('MultiClassLinear 4', 4, 1), ...
class DPLinearClassifierClassifierTest( tf.test.TestCase, parameterized.TestCase ): """Tests for DP-enabled LinearClassifier.""" @parameterized.named_parameters( ('BinaryClassLinear 1', 2, 1), ('BinaryClassLinear 4', 2, 4), ('MultiClassLinear 3', 3, 1), ('MultiClassLinear 4', 4, 1), ...
train_features, train_labels = test_utils.make_input_data(256, n_classes) feature_columns = [] for key in train_features: feature_columns.append(tf.feature_column.numeric_column(key=key)) # pylint: disable=g-deprecated-tf-checker optimizer = functools.partial( DPGradientDescentGaussianOp...
train_features, train_labels = test_utils.make_input_data(256, n_classes) feature_columns = [] for key in train_features: feature_columns.append(tf.feature_column.numeric_column(key=key)) # pylint: disable=g-deprecated-tf-checker optimizer = functools.partial( DPGradientDescentGaussianOp...
64
162
450
612
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,507
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/common_manip_utils.py
22,26
1,49
maybe_add_microbatch_axis
37,49
26,49
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
if num_microbatches is None: return x def _expand(t): with tf.control_dependencies( [tf.assert_equal(tf.math.floormod(tf.shape(t)[0], num_microbatches), 0)] ): return tf.reshape( t, tf.concat([[num_microbatches, -1], tf.shape(t)[1:]], axis=0) ) return tf.nest.map_struct...
"""Adds the microbatch axis to a collection of tensors. Args: x: Model output or input tensors. num_microbatches: If None, x is returned unchanged. Otherwise, must divide the batch size. Returns: The input tensor x, reshaped from [batch_size, ...] to [num_microbatches, batch_size / num_mic...
25
388
147
535
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,508
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/dense_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(dense_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(dense_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(dense_test.GradNormTest, self).setUp() self.strategy = ctu.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(dense_test.GradNormTest, self).setUp() self.strategy = ctu.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
36
78
114
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,509
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/einsum_dense_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(einsum_dense_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(einsum_dense_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(einsum_dense_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(einsum_dense_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
40
85
125
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,511
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/embedding_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(embedding_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(embedding_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(embedding_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(embedding_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
36
81
117
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,512
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/layer_normalization_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(layer_normalization_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(layer_normalization_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(layer_normalization_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(layer_normalization_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
38
83
121
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,513
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/multi_head_attention_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(multi_head_attention_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(multi_head_attention_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(multi_head_attention_test.GradNormTest, self).setUp() self.strategy = ctu.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(multi_head_attention_test.GradNormTest, self).setUp() self.strategy = ctu.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
39
81
120
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,514
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/nlp_on_device_embedding_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(nlp_on_device_embedding_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(nlp_on_device_embedding_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(nlp_on_device_embedding_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(nlp_on_device_embedding_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
43
88
131
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,515
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/fast_gradient_clipping/registry_functions/nlp_position_embedding_tpu_test.py
22,23
20,29
setUp
GradNormTpuTest
23,29
23,29
class GradNormTpuTest(nlp_position_embedding_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
class GradNormTpuTest(nlp_position_embedding_test.GradNormTest): def setUp(self): FILL_FUNC_BODY
super(nlp_position_embedding_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
super(nlp_position_embedding_test.GradNormTest, self).setUp() self.strategy = common_test_utils.create_tpu_strategy() self.assertIn('TPU', self.strategy.extended.worker_devices[0]) self.using_tpu = True
10
41
86
127
# Copyright 2023, The TensorFlow 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 t...
# Copyright 2023, The TensorFlow 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 t...
40,517
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/logistic_regression/datasets_test.py
60,61
22,76
test_mnist_dataset
DatasetsTest
61,76
61,76
class DatasetsTest(parameterized.TestCase): @parameterized.parameters( (1, np.array([ [1], ])), (2, np.array([ [1], ])), (5, np.array([[-1, 1], [1, -1]])), (15, np.array([[-1, 1.5, 2.1], [1.3, -3.3, -7.1], [1.3, -3.3, -7.1]]))) def test_linearly_separable_labeled_example...
class DatasetsTest(parameterized.TestCase): @parameterized.parameters( (1, np.array([ [1], ])), (2, np.array([ [1], ])), (5, np.array([[-1, 1], [1, -1]])), (15, np.array([[-1, 1.5, 2.1], [1.3, -3.3, -7.1], [1.3, -3.3, -7.1]]))) def test_linearly_separable_labeled_example...
(train_dataset, test_dataset) = datasets.mnist_dataset() self.assertEqual(train_dataset.points.shape, (60000, 784)) self.assertEqual(train_dataset.labels.shape, (60000,)) self.assertEqual(test_dataset.points.shape, (10000, 784)) self.assertEqual(test_dataset.labels.shape, (10000,)) # Check that ...
(train_dataset, test_dataset) = datasets.mnist_dataset() self.assertEqual(train_dataset.points.shape, (60000, 784)) self.assertEqual(train_dataset.labels.shape, (60000,)) self.assertEqual(test_dataset.points.shape, (10000, 784)) self.assertEqual(test_dataset.labels.shape, (10000,)) # Check that ...
54
711
320
1,031
# Copyright 2021, The TensorFlow 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 t...
# Copyright 2021, The TensorFlow 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 t...
40,518
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/logistic_regression/multinomial_logistic_test.py
43,50
23,79
test_compute_dpsgd_noise_multiplier
MultinomialLogisticRegressionTest
50,59
50,59
class MultinomialLogisticRegressionTest(parameterized.TestCase): @parameterized.parameters( (5000, 500, 3, 1, 1e-5, 40, 2, 0.05), (5000, 500, 4, 1, 1e-5, 40, 2, 0.05), (10000, 1000, 3, 1, 1e-5, 40, 4, 0.1), (10000, 1000, 4, 1, 1e-5, 40, 4, 0.1), ) def test_logistic_objective_perturbation(...
class MultinomialLogisticRegressionTest(parameterized.TestCase): @parameterized.parameters( (5000, 500, 3, 1, 1e-5, 40, 2, 0.05), (5000, 500, 4, 1, 1e-5, 40, 2, 0.05), (10000, 1000, 3, 1, 1e-5, 40, 4, 0.1), (10000, 1000, 4, 1, 1e-5, 40, 4, 0.1), ) def test_logistic_objective_perturbation(...
noise_multiplier = multinomial_logistic.compute_dpsgd_noise_multiplier( num_train, epsilon, delta, epochs, batch_size, tolerance) epsilon_lower_bound = compute_dp_sgd_privacy_lib.compute_dp_sgd_privacy( num_train, batch_size, noise_multiplier + tolerance, epochs, delta)[0] epsilon_upper_boun...
noise_multiplier = multinomial_logistic.compute_dpsgd_noise_multiplier( num_train, epsilon, delta, epochs, batch_size, tolerance) epsilon_lower_bound = compute_dp_sgd_privacy_lib.compute_dp_sgd_privacy( num_train, batch_size, noise_multiplier + tolerance, epochs, delta)[0] epsilon_upper_boun...
33
966
205
1,171
# Copyright 2021, The TensorFlow 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 t...
# Copyright 2021, The TensorFlow 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 t...
40,519
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/logistic_regression/single_layer_softmax_test.py
24,32
22,38
test_single_layer_softmax
SingleLayerSoftmaxTest
32,38
32,38
class SingleLayerSoftmaxTest(parameterized.TestCase): @parameterized.parameters( (5000, 500, 3, 40, 2, 0.05), (5000, 500, 4, 40, 2, 0.05), (10000, 1000, 3, 40, 4, 0.1), (10000, 1000, 4, 40, 4, 0.1), ) def test_single_layer_softmax(self, num_train, num_test, dimension, epochs, ...
class SingleLayerSoftmaxTest(parameterized.TestCase): @parameterized.parameters( (5000, 500, 3, 40, 2, 0.05), (5000, 500, 4, 40, 2, 0.05), (10000, 1000, 3, 40, 4, 0.1), (10000, 1000, 4, 40, 4, 0.1), ) def test_single_layer_softmax(self, num_train, num_test, dimension, epochs, ...
(train_dataset, test_dataset) = datasets.synthetic_linearly_separable_data( num_train, num_test, dimension, num_classes) _, accuracy = single_layer_softmax.single_layer_softmax_classifier( train_dataset, test_dataset, epochs, num_classes, 'sgd') self.assertAlmostEqual(accuracy[-1], 1, delta=...
(train_dataset, test_dataset) = datasets.synthetic_linearly_separable_data( num_train, num_test, dimension, num_classes) _, accuracy = single_layer_softmax.single_layer_softmax_classifier( train_dataset, test_dataset, epochs, num_classes, 'sgd') self.assertAlmostEqual(accuracy[-1], 1, delta=...
20
188
115
303
# Copyright 2021, The TensorFlow 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 t...
# Copyright 2021, The TensorFlow 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 t...
40,520
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tensorflow_privacy/privacy/optimizers/dp_optimizer_eager_test.py
89,94
22,117
testNoiseMultiplier
DPOptimizerEagerTest
94,117
94,117
class DPOptimizerEagerTest(tf.test.TestCase, parameterized.TestCase): def setUp(self): tf.compat.v1.enable_eager_execution() super().setUp() def _loss_fn(self, val0, val1): return 0.5 * tf.reduce_sum( input_tensor=tf.math.squared_difference(val0, val1), axis=1) @parameterized.named_paramete...
class DPOptimizerEagerTest(tf.test.TestCase, parameterized.TestCase): def setUp(self): tf.compat.v1.enable_eager_execution() super().setUp() def _loss_fn(self, val0, val1): return 0.5 * tf.reduce_sum( input_tensor=tf.math.squared_difference(val0, val1), axis=1) @parameterized.named_paramete...
with tf.GradientTape(persistent=True) as gradient_tape: var0 = tf.Variable([0.0]) data0 = tf.Variable([[0.0]]) dp_sum_query = gaussian_query.GaussianSumQuery(4.0, 8.0) opt = cls(dp_sum_query, num_microbatches=1, learning_rate=2.0) self.evaluate(tf.compat.v1.global_variables_initiali...
with tf.GradientTape(persistent=True) as gradient_tape: var0 = tf.Variable([0.0]) data0 = tf.Variable([[0.0]]) dp_sum_query = gaussian_query.GaussianSumQuery(4.0, 8.0) opt = cls(dp_sum_query, num_microbatches=1, learning_rate=2.0) self.evaluate(tf.compat.v1.global_variables_initiali...
60
1,283
328
1,611
# Copyright 2019, The TensorFlow 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 t...
# Copyright 2019, The TensorFlow 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 t...
40,523
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy
/home/hieuvd/dung_repo/raw/stars_02/tensorflow_privacy/privacy/tutorials/mnist_dpsgd_tutorial.py
95,96
1,135
main
96,133
96,133
# Copyright 2020, The TensorFlow 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 t...
# Copyright 2020, The TensorFlow 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 t...
logging.set_verbosity(logging.INFO) if FLAGS.dpsgd and FLAGS.batch_size % FLAGS.microbatches != 0: raise ValueError('Number of microbatches should divide evenly batch_size') # Instantiate the tf.Estimator. mnist_classifier = tf_estimator.Estimator( model_fn=cnn_model_fn, model_dir=FLAGS.model_dir) ...
logging.set_verbosity(logging.INFO) if FLAGS.dpsgd and FLAGS.batch_size % FLAGS.microbatches != 0: raise ValueError('Number of microbatches should divide evenly batch_size') # Instantiate the tf.Estimator. mnist_classifier = tf_estimator.Estimator( model_fn=cnn_model_fn, model_dir=FLAGS.model_dir) ...
139
1,298
585
1,883
# Copyright 2020, The TensorFlow 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 t...
# Copyright 2020, The TensorFlow 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 t...
40,636
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/common/bdd_tags.py
7,8
1,74
look_for_bdd_tags
8,74
8,74
from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import Match from terraform_compliance.common.error_handling import Error import re def look_for_bdd_tags(_step_obj): FILL_FUNC_BODY
from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import Match from terraform_compliance.common.error_handling import Error import re def look_for_bdd_tags(_step_obj): FILL_FUNC_BODY
_step_obj.context.no_failure = False _step_obj.context.failure_class = None _step_obj.context.no_skip = False _step_obj.context.skip_class = None # to pick a tagname that user used _step_obj.context.lines_to_noskip = [] _step_obj.context.bad_tags = False _step_obj.context.resources_to_exclud...
_step_obj.context.no_failure = False _step_obj.context.failure_class = None _step_obj.context.no_skip = False _step_obj.context.skip_class = None # to pick a tagname that user used _step_obj.context.lines_to_noskip = [] _step_obj.context.bad_tags = False _step_obj.context.resources_to_exclud...
231
73
1,077
1,150
from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import Match from terraform_compliance.common.error_handling import Error import re def look_for_bdd_tags(_step_obj): FILL_FUNC_BODY
from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import Match from terraform_compliance.common.error_handling import Error import re def look_for_bdd_tags(_step_obj): FILL_FUNC_BODY
40,638
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/common/helper.py
68,69
25,195
issubset
Match
69,82
69,82
class Match(object): def __init__(self, case_sensitive, regex_flag=None): self.case_sensitive = case_sensitive self.regex_flag = regex_flag def equals(self, left, right): if not isinstance(left, (bool, int, float, str)) or not isinstance(right, (bool, int, float, str)): rais...
class Match(object): def __init__(self, case_sensitive, regex_flag=None): self.case_sensitive = case_sensitive self.regex_flag = regex_flag def equals(self, left, right): if not isinstance(left, (bool, int, float, str)) or not isinstance(right, (bool, int, float, str)): rais...
if not isinstance(set1, Iterable) or isinstance(set1, str): raise TerraformComplianceInternalFailure('{} should be a non-str iterable'.format(set1)) if not isinstance(set2, Iterable) or isinstance(set2, str): raise TerraformComplianceInternalFailure('{} should be a non-str itera...
if not isinstance(set1, Iterable) or isinstance(set1, str): raise TerraformComplianceInternalFailure('{} should be a non-str iterable'.format(set1)) if not isinstance(set2, Iterable) or isinstance(set2, str): raise TerraformComplianceInternalFailure('{} should be a non-str itera...
55
1,695
182
1,877
import re from netaddr import IPNetwork from terraform_compliance.steps import resource_name from collections.abc import Iterable from copy import deepcopy import sys from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from semver import VersionInfo, compare from terraform_compliance.c...
import re from netaddr import IPNetwork from terraform_compliance.steps import resource_name from collections.abc import Iterable from copy import deepcopy import sys from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from semver import VersionInfo, compare from terraform_compliance.c...
40,639
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/common/pip_helper.py
5,6
1,26
reinstall_radish
6,26
6,26
import subprocess from sys import exit, executable def reinstall_radish(): FILL_FUNC_BODY
import subprocess from sys import exit, executable def reinstall_radish(): FILL_FUNC_BODY
def pip(action, package, params=None): print('{}ing {}..'.format(action, package)) if action == 'uninstall': cmds = [executable, "-m", "pip", action, '--yes', package] else: cmds = [executable, "-m", "pip", action, package] subprocess.call(cmds) print("...
def pip(action, package, params=None): print('{}ing {}..'.format(action, package)) if action == 'uninstall': cmds = [executable, "-m", "pip", action, '--yes', package] else: cmds = [executable, "-m", "pip", action, package] subprocess.call(cmds) print("...
51
30
222
252
import subprocess from sys import exit, executable def reinstall_radish(): FILL_FUNC_BODY
import subprocess from sys import exit, executable def reinstall_radish(): FILL_FUNC_BODY
40,640
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/common/terraform_files.py
32,33
1,146
convert_terraform_plan_to_json
33,107
33,107
import os import stat import sys import subprocess import platform import urllib.request import tempfile from shutil import unpack_archive import re def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: ...
import os import stat import sys import subprocess import platform import urllib.request import tempfile from shutil import unpack_archive import re def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: ...
print('. Converting terraform plan file.') if terraform_executable is None: terraform_executable = which('terraform') else: print('. Using {} as terraform executable.'.format(terraform_executable)) if terraform_executable is None: sys.stderr.write('ERROR: Could not find "terrafo...
print('. Converting terraform plan file.') if terraform_executable is None: terraform_executable = which('terraform') else: print('. Using {} as terraform executable.'.format(terraform_executable)) if terraform_executable is None: sys.stderr.write('ERROR: Could not find "terrafo...
290
773
1,046
1,819
import os import stat import sys import subprocess import platform import urllib.request import tempfile from shutil import unpack_archive import re def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: ...
import os import stat import sys import subprocess import platform import urllib.request import tempfile from shutil import unpack_archive import re def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: ...
40,641
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/extensions/cache.py
15,16
5,20
delete
Cache
16,18
16,18
class Cache(object): def __init__(self): self.cache = diskcache.Cache(Defaults.cache_dir) def set(self, key, value): return self.cache.add(bytes(key, encoding='utf8'), value) def get(self, key): return self.cache.get(bytes(key, encoding='utf8')) def delete(self, key): FILL_FUN...
class Cache(object): def __init__(self): self.cache = diskcache.Cache(Defaults.cache_dir) def set(self, key, value): return self.cache.add(bytes(key, encoding='utf8'), value) def get(self, key): return self.cache.get(bytes(key, encoding='utf8')) def delete(self, key): FILL_FUN...
del self.cache[bytes(key, encoding='utf8')]
del self.cache[bytes(key, encoding='utf8')]
3
130
21
151
import diskcache from terraform_compliance.common.defaults import Defaults class Cache(object): def __init__(self): self.cache = diskcache.Cache(Defaults.cache_dir) def set(self, key, value): return self.cache.add(bytes(key, encoding='utf8'), value) def get(self, key): return sel...
import diskcache from terraform_compliance.common.defaults import Defaults class Cache(object): def __init__(self): self.cache = diskcache.Cache(Defaults.cache_dir) def set(self, key, value): return self.cache.add(bytes(key, encoding='utf8'), value) def get(self, key): return sel...
40,642
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/extensions/override_radish_hookerrors.py
71,72
1,94
handle_radish_errors
72,94
72,94
from __future__ import unicode_literals import colorful import sys from radish.exceptions import ( RadishError, HookError, ) from radish.utils import Failure, console_write from terraform_compliance.common.defaults import Defaults from radish.exceptions import ( LanguageNotSupportedError, FeatureFileN...
from __future__ import unicode_literals import colorful import sys from radish.exceptions import ( RadishError, HookError, ) from radish.utils import Failure, console_write from terraform_compliance.common.defaults import Defaults from radish.exceptions import ( LanguageNotSupportedError, FeatureFileN...
mapping = [ { 'class': FeatureFileSyntaxError, 'text': 'You have a SyntaxError in your feature file! Please have a look into terraform-compliance and ' 'radish documentation to find out which features are supported and how you could use them: ' ...
mapping = [ { 'class': FeatureFileSyntaxError, 'text': 'You have a SyntaxError in your feature file! Please have a look into terraform-compliance and ' 'radish documentation to find out which features are supported and how you could use them: ' ...
72
508
247
755
from __future__ import unicode_literals import colorful import sys from radish.exceptions import ( RadishError, HookError, ) from radish.utils import Failure, console_write from terraform_compliance.common.defaults import Defaults from radish.exceptions import ( LanguageNotSupportedError, FeatureFileN...
from __future__ import unicode_literals import colorful import sys from radish.exceptions import ( RadishError, HookError, ) from radish.utils import Failure, console_write from terraform_compliance.common.defaults import Defaults from radish.exceptions import ( LanguageNotSupportedError, FeatureFileN...
40,643
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/extensions/override_radish_step.py
135,136
20,221
debug
Step
139,160
136,160
class Step(Model): """ Represents a step """ class State(object): """ Represents the step state FIXME: for the python3 version this should be an Enum """ UNTESTED = "untested" SKIPPED = "skipped" PASSED = "passed" FAILED = "f...
class Step(Model): """ Represents a step """ class State(object): """ Represents the step state FIXME: for the python3 version this should be an Enum """ UNTESTED = "untested" SKIPPED = "skipped" PASSED = "passed" FAILED = "f...
if not self.runable: self.state = Step.State.UNTESTED return self.state self._validate() args, kwargs = self.argument_match.evaluate() pdb = utils.get_debugger() try: pdb.runcall(self.definition_func, self, *args, **kwargs) except Ex...
""" Debugs the step """ if not self.runable: self.state = Step.State.UNTESTED return self.state self._validate() args, kwargs = self.argument_match.evaluate() pdb = utils.get_debugger() try: pdb.runcall(self.defin...
50
1,541
222
1,763
# -*- coding: utf-8 -*- """ This module provides a class to represent a Step """ from __future__ import unicode_literals import base64 import re from radish.model import Model from radish.exceptions import RadishError from radish.terrain import world from radish.stepregistry import StepRegistry from radish.matc...
# -*- coding: utf-8 -*- """ This module provides a class to represent a Step """ from __future__ import unicode_literals import base64 import re from radish.model import Model from radish.exceptions import RadishError from radish.terrain import world from radish.stepregistry import StepRegistry from radish.matc...
40,646
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/extensions/security_groups.py
88,89
11,119
_expand_ports
SecurityGroupRule
89,111
89,111
class SecurityGroupRule(object): def __init__(self, **kwargs): self.from_port = kwargs.get('from_port', kwargs.get('values', {}).get('from_port')) self.to_port = kwargs.get('to_port', kwargs.get('values', {}).get('to_port')) self.ports = str(kwargs.get('port')) self.protocol = [proto...
class SecurityGroupRule(object): def __init__(self, **kwargs): self.from_port = kwargs.get('from_port', kwargs.get('values', {}).get('from_port')) self.to_port = kwargs.get('to_port', kwargs.get('values', {}).get('to_port')) self.ports = str(kwargs.get('port')) self.protocol = [proto...
if '-' in port: self.from_port, self.to_port = [int(port_number) for port_number in port.split('-')] self.from_port = self.from_port if self.from_port > 0 else 1 self.to_port = self.to_port if self.to_port > 0 else 1 self.ports = self._get_port_range(self.from_por...
if '-' in port: self.from_port, self.to_port = [int(port_number) for port_number in port.split('-')] self.from_port = self.from_port if self.from_port > 0 else 1 self.to_port = self.to_port if self.to_port > 0 else 1 self.ports = self._get_port_range(self.from_por...
86
1,203
327
1,530
from terraform_compliance.common.helper import ( check_if_cidr, is_ip_in_cidr ) from terraform_compliance.common.exceptions import ( TerraformComplianceInvalidData, TerraformComplianceInternalFailure ) class SecurityGroupRule(object): def __init__(self, **kwargs): self.from_port = kwargs.g...
from terraform_compliance.common.helper import ( check_if_cidr, is_ip_in_cidr ) from terraform_compliance.common.exceptions import ( TerraformComplianceInvalidData, TerraformComplianceInternalFailure ) class SecurityGroupRule(object): def __init__(self, **kwargs): self.from_port = kwargs.g...
40,650
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/interpolations.py
4,5
1,18
i_flatten_everything_found
5,18
5,18
# -*- coding: utf-8 -*- def i_flatten_everything_found(_step_obj): FILL_FUNC_BODY
# -*- coding: utf-8 -*- def i_flatten_everything_found(_step_obj): FILL_FUNC_BODY
flattened_list = [] addresses_flattened = [] for each in _step_obj.context.stash: flattened_list.append(each.get('values', each)) addresses_flattened.append(each.get('address', each)) if flattened_list: _step_obj.context.stash = { 'address': ', '.join(addresses_flatt...
flattened_list = [] addresses_flattened = [] for each in _step_obj.context.stash: flattened_list.append(each.get('values', each)) addresses_flattened.append(each.get('address', each)) if flattened_list: _step_obj.context.stash = { 'address': ', '.join(addresses_flatt...
27
40
143
183
# -*- coding: utf-8 -*- def i_flatten_everything_found(_step_obj): FILL_FUNC_BODY
# -*- coding: utf-8 -*- def i_flatten_everything_found(_step_obj): FILL_FUNC_BODY
40,651
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/it_must_be_in.py
4,5
1,21
it_must_be_in
5,21
5,21
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
match = _step_obj.context.match values = [resource['values'] for resource in _step_obj.context.stash] for value in values: if not isinstance(value, (bool, int, float, str)): Error(_step_obj, 'Values are not of the correct type. (bool, str, int, float)') if 'haystack' not in _step_o...
match = _step_obj.context.match values = [resource['values'] for resource in _step_obj.context.stash] for value in values: if not isinstance(value, (bool, int, float, str)): Error(_step_obj, 'Values are not of the correct type. (bool, str, int, float)') if 'haystack' not in _step_o...
74
61
273
334
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
40,653
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/it_must_have_reference_address_referenced.py
11,12
1,24
it_must_have_reference_address_referenced
12,24
12,24
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( search_regex_in_list ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.defaults import Defaults def it_must_...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( search_regex_in_list ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.defaults import Defaults def it_must_...
if _step_obj.context.stash: for resource in _step_obj.context.stash: if isinstance(resource, dict): if Defaults.r_mount_addr_ptr_list in resource and search_regex_in_list(reference_address, res...
if _step_obj.context.stash: for resource in _step_obj.context.stash: if isinstance(resource, dict): if Defaults.r_mount_addr_ptr_list in resource and search_regex_in_list(reference_address, res...
49
124
192
316
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( search_regex_in_list ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.defaults import Defaults def it_must_...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( search_regex_in_list ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.defaults import Defaults def it_must_...
40,654
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/it_must_not_be_in.py
4,5
1,21
it_must_not_be_in
5,21
5,21
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_not_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_not_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
match = _step_obj.context.match values = [resource['values'] for resource in _step_obj.context.stash] for value in values: if not isinstance(value, (bool, int, float, str)): Error(_step_obj, 'Values are not of the correct type. (bool, str, int, float)') if 'haystack' not in _step_o...
match = _step_obj.context.match values = [resource['values'] for resource in _step_obj.context.stash] for value in values: if not isinstance(value, (bool, int, float, str)): Error(_step_obj, 'Values are not of the correct type. (bool, str, int, float)') if 'haystack' not in _step_o...
68
63
267
330
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_not_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null def it_must_not_be_in(_step_obj, haystack, cover=False): FILL_FUNC_BODY
40,655
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/its_key_condition_be_value.py
10,11
1,64
its_key_condition_be_value
11,64
11,64
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( Null, ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented def its_key_condition_be_value(_step_obj, key, condition, value, stash=Null, depth=0):...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( Null, ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented def its_key_condition_be_value(_step_obj, key, condition, value, stash=Null, depth=0):...
match = _step_obj.context.match seek_regex_key_in_dict_values = match.seek_regex_key_in_dict_values if condition not in ('must', 'must not'): raise TerraformComplianceNotImplemented('This step only accepts "must" and "must not" as a condition.') condition = condition == 'must' if stash is ...
match = _step_obj.context.match seek_regex_key_in_dict_values = match.seek_regex_key_in_dict_values if condition not in ('must', 'must not'): raise TerraformComplianceNotImplemented('This step only accepts "must" and "must not" as a condition.') condition = condition == 'must' if stash is ...
253
114
801
915
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( Null, ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented def its_key_condition_be_value(_step_obj, key, condition, value, stash=Null, depth=0):...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( Null, ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented def its_key_condition_be_value(_step_obj, key, condition, value, stash=Null, depth=0):...
40,656
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/its_value_condition_be_null.py
6,7
1,40
its_value_condition_be_null
7,40
7,40
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null import re def its_value_condition_be_null(_step_obj, condition): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null import re def its_value_condition_be_null(_step_obj, condition): FILL_FUNC_BODY
if condition not in ['must', 'must not']: Error(_step_obj, 'Condition must be one of "must" or "must not"') return condition_must = condition == 'must' match = _step_obj.context.match regex = r'{}'.format(u'(\x00|^$)$') is_null = lambda x: x in ([], {}, None, Null) or (isinstance(x...
if condition not in ['must', 'must not']: Error(_step_obj, 'Condition must be one of "must" or "must not"') return condition_must = condition == 'must' match = _step_obj.context.match regex = r'{}'.format(u'(\x00|^$)$') is_null = lambda x: x in ([], {}, None, Null) or (isinstance(x...
149
62
490
552
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null import re def its_value_condition_be_null(_step_obj, condition): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.common.helper import Null import re def its_value_condition_be_null(_step_obj, condition): FILL_FUNC_BODY
40,657
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/its_value_condition_contain.py
51,52
1,68
_its_value_condition_contain
52,68
52,68
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.exceptions impor...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.exceptions impor...
if isinstance(values, list): values = [str(v) for v in values] _fail_text = 'did not contain' if condition == 'must' else 'contains' fail_message = '{} property in {} {} {}, it is set to {}'.format( _step_obj.context.property_name, _step_obj.context.name, ...
if isinstance(values, list): values = [str(v) for v in values] _fail_text = 'did not contain' if condition == 'must' else 'contains' fail_message = '{} property in {} {} {}, it is set to {}'.format( _step_obj.context.property_name, _step_obj.context.name, ...
66
572
182
754
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.exceptions impor...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.exceptions impor...
40,658
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/its_value_condition_match_the_search_regex.py
11,12
1,142
its_value_condition_match_the_search_regex_regex
12,68
12,68
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error import re def its_value_condition_match_the_search_regex_regex(_step_obj, condition, search_regex, _stash=EmptyStash): FILL_FUNC_BOD...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error import re def its_value_condition_match_the_search_regex_regex(_step_obj, condition, search_regex, _stash=EmptyStash): FILL_FUNC_BOD...
def fail(condition, name=None): text = 'matches' if condition == 'must not' else 'does not match' name = name if (name is not None or name is not False) else _step_obj.context.name pattern = 'Null/None' if regex == '\x00' else regex Error(_step_obj, '{} property in {} {} {} with {} {...
def fail(condition, name=None): text = 'matches' if condition == 'must not' else 'does not match' name = name if (name is not None or name is not False) else _step_obj.context.name pattern = 'Null/None' if regex == '\x00' else regex Error(_step_obj, '{} property in {} {} {} with {} {...
188
997
703
1,700
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error import re def its_value_condition_match_the_search_regex_regex(_step_obj, condition, search_regex, _stash=EmptyStash): FILL_FUNC_BOD...
# -*- coding: utf-8 -*- from terraform_compliance.common.helper import ( EmptyStash, get_resource_name_from_stash ) from terraform_compliance.common.error_handling import Error import re def its_value_condition_match_the_search_regex_regex(_step_obj, condition, search_regex, _stash=EmptyStash): FILL_FUNC_BOD...
40,659
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/property_is_enabled.py
10,11
1,34
property_is_enabled
11,34
11,34
# -*- coding: utf-8 -*- from terraform_compliance.steps import property_match_list from terraform_compliance.common.helper import ( Null ) from terraform_compliance.common.error_handling import Error def property_is_enabled(_step_obj, something): FILL_FUNC_BODY
# -*- coding: utf-8 -*- from terraform_compliance.steps import property_match_list from terraform_compliance.common.helper import ( Null ) from terraform_compliance.common.error_handling import Error def property_is_enabled(_step_obj, something): FILL_FUNC_BODY
match = _step_obj.context.match seek_key_in_dict = match.seek_key_in_dict for resource in _step_obj.context.stash: if isinstance(resource, dict): if match.contains(property_match_list, something): something = match.get(match.get(property_match_list, something), resource[...
match = _step_obj.context.match seek_key_in_dict = match.seek_key_in_dict for resource in _step_obj.context.stash: if isinstance(resource, dict): if match.contains(property_match_list, something): something = match.get(match.get(property_match_list, something), resource[...
61
89
270
359
# -*- coding: utf-8 -*- from terraform_compliance.steps import property_match_list from terraform_compliance.common.helper import ( Null ) from terraform_compliance.common.error_handling import Error def property_is_enabled(_step_obj, something): FILL_FUNC_BODY
# -*- coding: utf-8 -*- from terraform_compliance.steps import property_match_list from terraform_compliance.common.helper import ( Null ) from terraform_compliance.common.error_handling import Error def property_is_enabled(_step_obj, something): FILL_FUNC_BODY
40,660
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/then/security_group_related.py
8,9
1,29
it_condition_have_proto_protocol_and_port_port_for_cidr
9,29
9,29
# -*- coding: utf-8 -*- from terraform_compliance.extensions.security_groups import SecurityGroup from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.error_handling import Error def it_condition_have_proto_protocol_and_port_port_for_cidr(_step_obj, c...
# -*- coding: utf-8 -*- from terraform_compliance.extensions.security_groups import SecurityGroup from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.error_handling import Error def it_condition_have_proto_protocol_and_port_port_for_cidr(_step_obj, c...
searching_for=dict(port=port, protocol=proto, cidr_blocks=cidr) for sg in _step_obj.context.stash: sg_obj = SecurityGroup(searching_for, sg['values'], address=sg['address']) if condition == 'must only': sg_obj.must_only_have() elif condition == 'must': sg_obj.mus...
searching_for=dict(port=port, protocol=proto, cidr_blocks=cidr) for sg in _step_obj.context.stash: sg_obj = SecurityGroup(searching_for, sg['values'], address=sg['address']) if condition == 'must only': sg_obj.must_only_have() elif condition == 'must': sg_obj.mus...
68
115
247
362
# -*- coding: utf-8 -*- from terraform_compliance.extensions.security_groups import SecurityGroup from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.error_handling import Error def it_condition_have_proto_protocol_and_port_port_for_cidr(_step_obj, c...
# -*- coding: utf-8 -*- from terraform_compliance.extensions.security_groups import SecurityGroup from terraform_compliance.common.exceptions import TerraformComplianceInternalFailure from terraform_compliance.common.error_handling import Error def it_condition_have_proto_protocol_and_port_port_for_cidr(_step_obj, c...
40,662
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/when/its_key_is_value.py
11,12
1,148
its_key_is_value
12,81
12,81
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( get_resource_address_list_from_stash, Null ) from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_is_value(_step_obj, key, value, dict_value=None, add...
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( get_resource_address_list_from_stash, Null ) from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_is_value(_step_obj, key, value, dict_value=None, add...
match = _step_obj.context.match match.regex_flag = regex_match orig_key = key if key == 'reference': if address is not Null: key = Defaults.r_mount_addr_ptr elif address is Null: key = Defaults.r_mount_addr_ptr_list found_list = [] for obj in _step_o...
match = _step_obj.context.match match.regex_flag = regex_match orig_key = key if key == 'reference': if address is not Null: key = Defaults.r_mount_addr_ptr elif address is Null: key = Defaults.r_mount_addr_ptr_list found_list = [] for obj in _step_o...
220
996
900
1,896
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( get_resource_address_list_from_stash, Null ) from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_is_value(_step_obj, key, value, dict_value=None, add...
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( get_resource_address_list_from_stash, Null ) from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_is_value(_step_obj, key, value, dict_value=None, add...
40,663
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/when/its_key_metadata_has_something.py
5,6
1,33
its_key_metadata_has_something
6,33
6,33
from terraform_compliance.common.error_handling import Error from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_metadata_has_something(_step_obj, key, value, has_step=True, regex_match=None): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_metadata_has_something(_step_obj, key, value, has_step=True, regex_match=None): FILL_FUNC_BODY
match = _step_obj.context.match match.regex_flag = regex_match if match.equals(key, 'values'): Error(_step_obj, 'The key "values" is not metadata, please use the "When its property has something" step instead.') found_list = [] for resource in _step_obj.context.stash: # documen...
match = _step_obj.context.match match.regex_flag = regex_match if match.equals(key, 'values'): Error(_step_obj, 'The key "values" is not metadata, please use the "When its property has something" step instead.') found_list = [] for resource in _step_obj.context.stash: # documen...
96
81
332
413
from terraform_compliance.common.error_handling import Error from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_metadata_has_something(_step_obj, key, value, has_step=True, regex_match=None): FILL_FUNC_BODY
from terraform_compliance.common.error_handling import Error from terraform_compliance.extensions.ext_radish_bdd import skip_step def its_key_metadata_has_something(_step_obj, key, value, has_step=True, regex_match=None): FILL_FUNC_BODY
40,664
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli
/home/hieuvd/dung_repo/raw/stars_02/terraform-compliance_cli/cli/terraform_compliance/steps/when/maths.py
41,42
1,83
i_expect_the_result_is_operator_than_number
42,83
42,83
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( EmptyStash, Null ) from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.error_handling import Error def i_action_...
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( EmptyStash, Null ) from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.error_handling import Error def i_action_...
def fail(assertion, message): try: assert assertion, 'Failed' except AssertionError as e: Error(_step_obj, 'for {} on {}. {}.'.format(_step_obj.context.address, _step_obj.context.property_name, ...
def fail(assertion, message): try: assert assertion, 'Failed' except AssertionError as e: Error(_step_obj, 'for {} on {}. {}.'.format(_step_obj.context.address, _step_obj.context.property_name, ...
180
542
650
1,192
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( EmptyStash, Null ) from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.error_handling import Error def i_action_...
# -*- coding: utf-8 -*- from terraform_compliance.common.defaults import Defaults from terraform_compliance.common.helper import ( EmptyStash, Null ) from terraform_compliance.common.exceptions import TerraformComplianceNotImplemented from terraform_compliance.common.error_handling import Error def i_action_...
40,668
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/cli.py
80,81
1,114
main
81,112
81,112
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
config_file = os.path.join(urlwatch_dir, CONFIG_FILE) urls_file = os.path.join(urlwatch_dir, URLS_FILE) hooks_file = os.path.join(urlwatch_dir, HOOKS_FILE) new_cache_file = os.path.join(urlwatch_cache_dir, CACHE_FILE) old_cache_file = os.path.join(urlwatch_dir, CACHE_FILE) cache_file = new_cache...
config_file = os.path.join(urlwatch_dir, CONFIG_FILE) urls_file = os.path.join(urlwatch_dir, URLS_FILE) hooks_file = os.path.join(urlwatch_dir, HOOKS_FILE) new_cache_file = os.path.join(urlwatch_cache_dir, CACHE_FILE) old_cache_file = os.path.join(urlwatch_dir, CACHE_FILE) cache_file = new_cache...
83
1,039
451
1,490
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
40,670
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/config.py
66,67
53,125
parse_args
CommandConfig
67,125
67,125
class CommandConfig(BaseConfig): def __init__(self, args, pkgname, urlwatch_dir, prefix, config, urls, hooks, cache, verbose): super().__init__(pkgname, urlwatch_dir, config, urls, cache, hooks, verbose) self.migrate_cache = migrate_cache self.migrate_urls = migrate_urls self.examp...
class CommandConfig(BaseConfig): def __init__(self, args, pkgname, urlwatch_dir, prefix, config, urls, hooks, cache, verbose): super().__init__(pkgname, urlwatch_dir, config, urls, cache, hooks, verbose) self.migrate_cache = migrate_cache self.migrate_urls = migrate_urls self.examp...
parser = argparse.ArgumentParser(description=urlwatch.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('joblist', metavar='JOB', type=str, nargs="*", help='indexes or tags of job(s) to run, depending on --tags. If using indexes, ...
parser = argparse.ArgumentParser(description=urlwatch.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('joblist', metavar='JOB', type=str, nargs="*", help='indexes or tags of job(s) to run, depending on --tags. If using indexes, ...
299
229
1,240
1,469
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,671
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
217,218
213,227
match
AutoMatchFilter
218,227
218,227
class AutoMatchFilter(FilterBase): """Automatically matches subclass filters with a given location""" MATCH = None def match(self): FILL_FUNC_BODY
class AutoMatchFilter(FilterBase): """Automatically matches subclass filters with a given location""" MATCH = None def match(self): FILL_FUNC_BODY
if self.MATCH is None: return False d = self.job.to_dict() result = all(d.get(k, None) == v for k, v in self.MATCH.items()) logger.debug('Matching %r with %r result: %r', self, self.job, result) return result
if self.MATCH is None: return False d = self.job.to_dict() result = all(d.get(k, None) == v for k, v in self.MATCH.items()) logger.debug('Matching %r with %r result: %r', self, self.job, result) return result
31
48
96
144
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,672
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
282,283
275,309
filter
BeautifyFilter
283,309
283,309
class BeautifyFilter(FilterBase): """Beautify HTML""" __kind__ = 'beautify' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
class BeautifyFilter(FilterBase): """Beautify HTML""" __kind__ = 'beautify' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
if BeautifulSoup is None: raise ImportError('Please install BeautifulSoup') soup = BeautifulSoup(data, features="lxml") if jsbeautifier is not None: scripts = soup.find_all('script') for script in scripts: if script.string is not None: ...
if BeautifulSoup is None: raise ImportError('Please install BeautifulSoup') soup = BeautifulSoup(data, features="lxml") if jsbeautifier is not None: scripts = soup.find_all('script') for script in scripts: if script.string is not None: ...
80
64
279
343
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,673
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
807,808
795,813
filter
CssFilter
808,813
808,813
class CssFilter(FilterBase): """Filter XML/HTML using CSS selectors""" __kind__ = 'css' __supported_subfilters__ = { 'selector': 'The CSS selector to use for filtering (required)', **LXML_PARSER_COMMON_SUBFILTERS, } __default_subfilter__ = 'selector' def filter(self, data, su...
class CssFilter(FilterBase): """Filter XML/HTML using CSS selectors""" __kind__ = 'css' __supported_subfilters__ = { 'selector': 'The CSS selector to use for filtering (required)', **LXML_PARSER_COMMON_SUBFILTERS, } __default_subfilter__ = 'selector' def filter(self, data, su...
lxml_parser = LxmlParser('css', subfilter, 'selector') lxml_parser.feed(data) return lxml_parser.get_filtered_data()
lxml_parser = LxmlParser('css', subfilter, 'selector') lxml_parser.feed(data) return lxml_parser.get_filtered_data()
8
117
52
169
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,674
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
346,347
333,376
filter
Csv2TextFilter
347,376
347,376
class Csv2TextFilter(FilterBase): """Convert CSV to plaintext""" __kind__ = 'csv2text' __supported_subfilters__ = { 'format_message': 'A string used to format for each CSV line', 'ignore_header': 'Force index-based format string, even if headers are used', 'has_header': 'Override a...
class Csv2TextFilter(FilterBase): """Convert CSV to plaintext""" __kind__ = 'csv2text' __supported_subfilters__ = { 'format_message': 'A string used to format for each CSV line', 'ignore_header': 'Force index-based format string, even if headers are used', 'has_header': 'Override a...
has_header_config = subfilter.get('has_header') if has_header_config is None: has_header = csv.Sniffer().has_header(data) else: has_header = has_header_config reader = csv.reader(data.split('\n')) data_list = list(reader) header = None i...
has_header_config = subfilter.get('has_header') if has_header_config is None: has_header = csv.Sniffer().has_header(data) else: has_header = has_header_config reader = csv.reader(data.split('\n')) data_list = list(reader) header = None i...
62
146
263
409
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,675
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
527,528
510,555
handle_starttag
ElementsBy
528,540
528,540
class ElementsBy(html.parser.HTMLParser): def __init__(self, filter_by, name, value=None): super().__init__() self._filter_by = filter_by if self._filter_by == FilterBy.ATTRIBUTE: self._attributes = {name: value} else: self._name = name self._result ...
class ElementsBy(html.parser.HTMLParser): def __init__(self, filter_by, name, value=None): super().__init__() self._filter_by = filter_by if self._filter_by == FilterBy.ATTRIBUTE: self._attributes = {name: value} else: self._name = name self._result ...
ad = dict(attrs) if self._filter_by == FilterBy.ATTRIBUTE and all(ad.get(k, None) == v for k, v in self._attributes.items()): self._inside = True elif self._filter_by == FilterBy.TAG and tag == self._name: self._inside = True if self._inside: self._r...
ad = dict(attrs) if self._filter_by == FilterBy.ATTRIBUTE and all(ad.get(k, None) == v for k, v in self._attributes.items()): self._inside = True elif self._filter_by == FilterBy.TAG and tag == self._name: self._inside = True if self._inside: self._r...
53
293
175
468
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,676
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
201,203
93,213
is_bytes_filter_kind
FilterBase
203,206
203,206
class FilterBase(object, metaclass=TrackSubClasses): __subclasses__ = {} __anonymous_subclasses__ = [] def __init__(self, job, state): self.job = job self.state = state @classmethod def filter_documentation(cls): result = [] for sc in TrackSubClasses.sorted_by_kind(...
class FilterBase(object, metaclass=TrackSubClasses): __subclasses__ = {} __anonymous_subclasses__ = [] def __init__(self, job, state): self.job = job self.state = state @classmethod def filter_documentation(cls): result = [] for sc in TrackSubClasses.sorted_by_kind(...
return (filter_kind in [name for name, class_ in cls.__subclasses__.items() if getattr(class_, '__uses_bytes__', False)])
return (filter_kind in [name for name, class_ in cls.__subclasses__.items() if getattr(class_, '__uses_bytes__', False)])
13
1,421
47
1,468
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,677
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
586,587
575,595
filter
GetElementByClass
587,595
587,595
class GetElementByClass(FilterBase): """Get all HTML elements by class""" __kind__ = 'element-by-class' __supported_subfilters__ = { 'class': 'HTML class attribute to filter for (required)', } __default_subfilter__ = 'class' def filter(self, data, subfilter): FILL_FUNC_BODY
class GetElementByClass(FilterBase): """Get all HTML elements by class""" __kind__ = 'element-by-class' __supported_subfilters__ = { 'class': 'HTML class attribute to filter for (required)', } __default_subfilter__ = 'class' def filter(self, data, subfilter): FILL_FUNC_BODY
if 'class' not in subfilter: raise ValueError('Need an element class for filtering') element_by_class = ElementsBy(FilterBy.ATTRIBUTE, 'class', subfilter['class']) element_by_class.feed(data) return element_by_class.get_html()
if 'class' not in subfilter: raise ValueError('Need an element class for filtering') element_by_class = ElementsBy(FilterBy.ATTRIBUTE, 'class', subfilter['class']) element_by_class.feed(data) return element_by_class.get_html()
20
101
87
188
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,678
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
566,567
555,575
filter
GetElementById
567,575
567,575
class GetElementById(FilterBase): """Get an HTML element by its ID""" __kind__ = 'element-by-id' __supported_subfilters__ = { 'id': 'ID of the element to filter for (required)', } __default_subfilter__ = 'id' def filter(self, data, subfilter): FILL_FUNC_BODY
class GetElementById(FilterBase): """Get an HTML element by its ID""" __kind__ = 'element-by-id' __supported_subfilters__ = { 'id': 'ID of the element to filter for (required)', } __default_subfilter__ = 'id' def filter(self, data, subfilter): FILL_FUNC_BODY
if 'id' not in subfilter: raise ValueError('Need an element ID for filtering') element_by_id = ElementsBy(FilterBy.ATTRIBUTE, 'id', subfilter['id']) element_by_id.feed(data) return element_by_id.get_html()
if 'id' not in subfilter: raise ValueError('Need an element ID for filtering') element_by_id = ElementsBy(FilterBy.ATTRIBUTE, 'id', subfilter['id']) element_by_id.feed(data) return element_by_id.get_html()
20
102
87
189
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,679
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
606,607
595,615
filter
GetElementByStyle
607,615
607,615
class GetElementByStyle(FilterBase): """Get all HTML elements by style""" __kind__ = 'element-by-style' __supported_subfilters__ = { 'style': 'HTML style attribute value to filter for (required)', } __default_subfilter__ = 'style' def filter(self, data, subfilter): FILL_FUNC_BODY
class GetElementByStyle(FilterBase): """Get all HTML elements by style""" __kind__ = 'element-by-style' __supported_subfilters__ = { 'style': 'HTML style attribute value to filter for (required)', } __default_subfilter__ = 'style' def filter(self, data, subfilter): FILL_FUNC_BODY
if 'style' not in subfilter: raise ValueError('Need an element style for filtering') element_by_style = ElementsBy(FilterBy.ATTRIBUTE, 'style', subfilter['style']) element_by_style.feed(data) return element_by_style.get_html()
if 'style' not in subfilter: raise ValueError('Need an element style for filtering') element_by_style = ElementsBy(FilterBy.ATTRIBUTE, 'style', subfilter['style']) element_by_style.feed(data) return element_by_style.get_html()
20
102
87
189
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,680
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
626,627
615,635
filter
GetElementByTag
627,635
627,635
class GetElementByTag(FilterBase): """Get an HTML element by its tag""" __kind__ = 'element-by-tag' __supported_subfilters__ = { 'tag': 'HTML tag name to filter for (required)', } __default_subfilter__ = 'tag' def filter(self, data, subfilter): FILL_FUNC_BODY
class GetElementByTag(FilterBase): """Get an HTML element by its tag""" __kind__ = 'element-by-tag' __supported_subfilters__ = { 'tag': 'HTML tag name to filter for (required)', } __default_subfilter__ = 'tag' def filter(self, data, subfilter): FILL_FUNC_BODY
if 'tag' not in subfilter: raise ValueError('Need a tag for filtering') element_by_tag = ElementsBy(FilterBy.TAG, subfilter['tag']) element_by_tag.feed(data) return element_by_tag.get_html()
if 'tag' not in subfilter: raise ValueError('Need a tag for filtering') element_by_tag = ElementsBy(FilterBy.TAG, subfilter['tag']) element_by_tag.feed(data) return element_by_tag.get_html()
18
102
81
183
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,681
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
456,457
445,464
filter
GrepFilter
457,464
457,464
class GrepFilter(FilterBase): """Filter only lines matching a regular expression""" __kind__ = 'grep' __supported_subfilters__ = { 're': 'Lines matching this expression are kept (required)', } __default_subfilter__ = 're' def filter(self, data, subfilter): FILL_FUNC_BODY
class GrepFilter(FilterBase): """Filter only lines matching a regular expression""" __kind__ = 'grep' __supported_subfilters__ = { 're': 'Lines matching this expression are kept (required)', } __default_subfilter__ = 're' def filter(self, data, subfilter): FILL_FUNC_BODY
if 're' not in subfilter: raise ValueError('The grep filter needs a regular expression') return '\n'.join(line for line in data.splitlines() if re.search(subfilter['re'], line) is not None)
if 're' not in subfilter: raise ValueError('The grep filter needs a regular expression') return '\n'.join(line for line in data.splitlines() if re.search(subfilter['re'], line) is not None)
25
99
70
169
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,682
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
655,656
648,663
filter
HexdumpFilter
656,663
656,663
class HexdumpFilter(FilterBase): """Convert binary data to hex dump format""" __kind__ = 'hexdump' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
class HexdumpFilter(FilterBase): """Convert binary data to hex dump format""" __kind__ = 'hexdump' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
data = bytearray(data.encode('utf-8', 'ignore')) blocks = [data[i * 16:(i + 1) * 16] for i in range(int((len(data) + (16 - 1)) / 16))] return '\n'.join('%s %s' % (' '.join('%02x' % c for c in block), ''.join((chr(c) if (c > 31 and c < 127) else '.') ...
data = bytearray(data.encode('utf-8', 'ignore')) blocks = [data[i * 16:(i + 1) * 16] for i in range(int((len(data) + (16 - 1)) / 16))] return '\n'.join('%s %s' % (' '.join('%02x' % c for c in block), ''.join((chr(c) if (c > 31 and c < 127) else '.') ...
54
66
144
210
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,683
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
321,322
309,333
filter
Html2TextFilter
322,333
322,333
class Html2TextFilter(FilterBase): """Convert HTML to plaintext""" __kind__ = 'html2text' __supported_subfilters__ = { 'method': 'Method to use for conversion (default: re)', '<any>': 'Method-specific options passed to html2text', } __default_subfilter__ = 'method' def filter...
class Html2TextFilter(FilterBase): """Convert HTML to plaintext""" __kind__ = 'html2text' __supported_subfilters__ = { 'method': 'Method to use for conversion (default: re)', '<any>': 'Method-specific options passed to html2text', } __default_subfilter__ = 'method' def filter...
if 'method' in subfilter: method = subfilter['method'] options = {key: val for (key, val) in subfilter.items() if key != 'method'} else: method = 're' options = {} return html2text(data, baseurl=getattr(self.job, 'url', getattr(self.job, 'navigate...
if 'method' in subfilter: method = subfilter['method'] options = {key: val for (key, val) in subfilter.items() if key != 'method'} else: method = 're' options = {} return html2text(data, baseurl=getattr(self.job, 'url', getattr(self.job, 'navigate...
36
118
122
240
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,684
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
408,409
401,412
filter
Ical2TextFilter
409,412
409,412
class Ical2TextFilter(FilterBase): """Convert iCalendar to plaintext""" __kind__ = 'ical2text' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
class Ical2TextFilter(FilterBase): """Convert iCalendar to plaintext""" __kind__ = 'ical2text' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
return ical2text(data)
return ical2text(data)
2
67
15
82
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,685
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
475,476
464,483
filter
InverseGrepFilter
476,483
476,483
class InverseGrepFilter(FilterBase): """Remove lines matching a regular expression""" __kind__ = 'grepi' __supported_subfilters__ = { 're': 'Lines matching this expression are removed (required)', } __default_subfilter__ = 're' def filter(self, data, subfilter): FILL_FUNC_BODY
class InverseGrepFilter(FilterBase): """Remove lines matching a regular expression""" __kind__ = 'grepi' __supported_subfilters__ = { 're': 'Lines matching this expression are removed (required)', } __default_subfilter__ = 're' def filter(self, data, subfilter): FILL_FUNC_BODY
if 're' not in subfilter: raise ValueError('The inverse grep filter needs a regular expression') return '\n'.join(line for line in data.splitlines() if re.search(subfilter['re'], line) is None)
if 're' not in subfilter: raise ValueError('The inverse grep filter needs a regular expression') return '\n'.join(line for line in data.splitlines() if re.search(subfilter['re'], line) is None)
25
100
70
170
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,686
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
976,977
965,990
filter
JQFilter
977,990
977,990
class JQFilter(FilterBase): """Parse, transform, and extract data from json as text using `jq`""" __kind__ = 'jq' __supported_subfilters__ = { 'query': 'jq query function to execute on data', } __default_subfilter__ = 'query' def filter(self, data, subfilter): FILL_FUNC_BODY
class JQFilter(FilterBase): """Parse, transform, and extract data from json as text using `jq`""" __kind__ = 'jq' __supported_subfilters__ = { 'query': 'jq query function to execute on data', } __default_subfilter__ = 'query' def filter(self, data, subfilter): FILL_FUNC_BODY
try: jsondata = json.loads(data) except ValueError: raise ValueError('The url response contained invalid JSON') if 'query' not in subfilter: raise ValueError('{} filter needs a query'.format(self.__kind__)) if jq is None: raise ImportErr...
try: jsondata = json.loads(data) except ValueError: raise ValueError('The url response contained invalid JSON') if 'query' not in subfilter: raise ValueError('{} filter needs a query'.format(self.__kind__)) if jq is None: raise ImportErr...
35
106
119
225
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,687
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
423,424
412,429
filter
JsonFormatFilter
424,429
424,429
class JsonFormatFilter(FilterBase): """Convert to formatted json""" __kind__ = 'format-json' __supported_subfilters__ = { 'indentation': 'Indentation level for pretty-printing', } __default_subfilter__ = 'indentation' def filter(self, data, subfilter): FILL_FUNC_BODY
class JsonFormatFilter(FilterBase): """Convert to formatted json""" __kind__ = 'format-json' __supported_subfilters__ = { 'indentation': 'Indentation level for pretty-printing', } __default_subfilter__ = 'indentation' def filter(self, data, subfilter): FILL_FUNC_BODY
indentation = int(subfilter.get('indentation', 4)) parsed_json = json.loads(data) return json.dumps(parsed_json, ensure_ascii=False, sort_keys=True, indent=indentation, separators=(',', ': '))
indentation = int(subfilter.get('indentation', 4)) parsed_json = json.loads(data) return json.dumps(parsed_json, ensure_ascii=False, sort_keys=True, indent=indentation, separators=(',', ': '))
15
98
81
179
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,688
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
261,262
245,275
filter
LegacyHooksPyFilter
262,275
262,275
class LegacyHooksPyFilter(FilterBase): FILENAME = os.path.expanduser('~/.urlwatch/lib/hooks.py') def __init__(self, job, state): super().__init__(job, state) self.hooks = None if os.path.exists(self.FILENAME): try: self.hooks = import_module_from_source('leg...
class LegacyHooksPyFilter(FilterBase): FILENAME = os.path.expanduser('~/.urlwatch/lib/hooks.py') def __init__(self, job, state): super().__init__(job, state) self.hooks = None if os.path.exists(self.FILENAME): try: self.hooks = import_module_from_source('leg...
if subfilter is not None: logger.warning('Legacy hooks filter does not have any subfilter -- ignored') try: result = self.hooks.filter(self.job.get_location(), data) if result is None: result = data return result except Exception a...
if subfilter is not None: logger.warning('Legacy hooks filter does not have any subfilter -- ignored') try: result = self.hooks.filter(self.job.get_location(), data) if result is None: result = data return result except Exception a...
43
180
116
296
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,689
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
775,776
663,785
get_filtered_data
LxmlParser
776,785
776,785
class LxmlParser: EXPR_NAMES = {'css': 'a CSS selector', 'xpath': 'an XPath expression'} def __init__(self, filter_kind, subfilter, expr_key): self.filter_kind = filter_kind if expr_key not in subfilter: raise ValueError('Need %s for filtering' % (self.EXPR_NAMES[f...
class LxmlParser: EXPR_NAMES = {'css': 'a CSS selector', 'xpath': 'an XPath expression'} def __init__(self, filter_kind, subfilter, expr_key): self.filter_kind = filter_kind if expr_key not in subfilter: raise ValueError('Need %s for filtering' % (self.EXPR_NAMES[f...
elements = list(self._get_filtered_elements()) if self.skip: elements = elements[self.skip:] if self.maxitems: elements = elements[:self.maxitems] elements = (self._to_string(element) for element in elements) return '\n'.join(sorted(elements) if self.sort_...
elements = list(self._get_filtered_elements()) if self.skip: elements = elements[self.skip:] if self.maxitems: elements = elements[:self.maxitems] elements = (self._to_string(element) for element in elements) return '\n'.join(sorted(elements) if self.sort_...
26
1,374
102
1,476
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,690
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
949,950
938,965
filter
OCRFilter
950,965
950,965
class OCRFilter(FilterBase): """Convert text in images to plaintext using Tesseract OCR""" __kind__ = 'ocr' __uses_bytes__ = True __supported_subfilters__ = { 'language': 'Language of the text (e.g. "fra" or "eng+fra")', 'timeout': 'Timeout (in seconds) for OCR (default 10 seconds)', ...
class OCRFilter(FilterBase): """Convert text in images to plaintext using Tesseract OCR""" __kind__ = 'ocr' __uses_bytes__ = True __supported_subfilters__ = { 'language': 'Language of the text (e.g. "fra" or "eng+fra")', 'timeout': 'Timeout (in seconds) for OCR (default 10 seconds)', ...
if not isinstance(data, bytes): raise ValueError('The ocr filter needs bytes input (is it the first filter?)') language = subfilter.get('language', None) timeout = int(subfilter.get('timeout', 10)) if pytesseract is None: raise ImportError('Please install pytess...
if not isinstance(data, bytes): raise ValueError('The ocr filter needs bytes input (is it the first filter?)') language = subfilter.get('language', None) timeout = int(subfilter.get('timeout', 10)) if pytesseract is None: raise ImportError('Please install pytess...
44
131
164
295
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,691
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
390,391
376,401
filter
Pdf2TextFilter
391,401
391,401
class Pdf2TextFilter(FilterBase): """Convert PDF to plaintext""" # Requires data to be in bytes (not unicode) # Dependency: pdftotext (https://github.com/jalan/pdftotext), itself based # on poppler (https://poppler.freedesktop.org/) # Note: check pdftotext website for OS-specific dependencies for in...
class Pdf2TextFilter(FilterBase): """Convert PDF to plaintext""" # Requires data to be in bytes (not unicode) # Dependency: pdftotext (https://github.com/jalan/pdftotext), itself based # on poppler (https://poppler.freedesktop.org/) # Note: check pdftotext website for OS-specific dependencies for in...
# data must be bytes if not isinstance(data, bytes): raise ValueError('The pdf2text filter needs bytes input (is it the first filter?)') if pdftotext is None: raise ImportError('Please install pdftotext') return '\n\n'.join(pdftotext.PDF(io.BytesIO(data), passwo...
# data must be bytes if not isinstance(data, bytes): raise ValueError('The pdf2text filter needs bytes input (is it the first filter?)') if pdftotext is None: raise ImportError('Please install pdftotext') return '\n\n'.join(pdftotext.PDF(io.BytesIO(data), passwo...
33
173
114
287
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,692
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
440,441
429,445
filter
PrettyXMLFilter
441,445
441,445
class PrettyXMLFilter(FilterBase): """Pretty-print XML""" __kind__ = 'pretty-xml' __supported_subfilters__ = { 'indentation': 'Indentation level for pretty-printing', } __default_subfilter__ = 'indentation' def filter(self, data, subfilter): FILL_FUNC_BODY
class PrettyXMLFilter(FilterBase): """Pretty-print XML""" __kind__ = 'pretty-xml' __supported_subfilters__ = { 'indentation': 'Indentation level for pretty-printing', } __default_subfilter__ = 'indentation' def filter(self, data, subfilter): FILL_FUNC_BODY
indentation = int(subfilter.get('indentation', 2)) return minidom.parseString(data).toprettyxml(indent=' ' * indentation)
indentation = int(subfilter.get('indentation', 2)) return minidom.parseString(data).toprettyxml(indent=' ' * indentation)
9
100
50
150
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,693
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
231,232
227,245
match
RegexMatchFilter
232,245
232,245
class RegexMatchFilter(FilterBase): """Same as AutoMatchFilter but matching is done with regexes""" MATCH = None def match(self): FILL_FUNC_BODY
class RegexMatchFilter(FilterBase): """Same as AutoMatchFilter but matching is done with regexes""" MATCH = None def match(self): FILL_FUNC_BODY
if self.MATCH is None: return False d = self.job.to_dict() # It's a match if we have at least one key/value pair that matches, # and no key/value pairs that do not match matches = [v.match(d[k]) for k, v in self.MATCH.items() if k in d] result = len(matches)...
if self.MATCH is None: return False d = self.job.to_dict() # It's a match if we have at least one key/value pair that matches, # and no key/value pairs that do not match matches = [v.match(d[k]) for k, v in self.MATCH.items() if k in d] result = len(matches)...
62
50
154
204
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,694
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
843,844
831,851
filter
RegexSub
844,851
844,851
class RegexSub(FilterBase): """Replace text with regular expressions using Python's re.sub""" __kind__ = 're.sub' __supported_subfilters__ = { 'pattern': 'Regular expression to search for (required)', 'repl': 'Replacement string (default: empty string)', } __default_subfilter__ = ...
class RegexSub(FilterBase): """Replace text with regular expressions using Python's re.sub""" __kind__ = 're.sub' __supported_subfilters__ = { 'pattern': 'Regular expression to search for (required)', 'repl': 'Replacement string (default: empty string)', } __default_subfilter__ = ...
if 'pattern' not in subfilter: raise ValueError('{} needs a pattern'.format(self.__kind__)) # Default: Replace with empty string if no "repl" value is set return re.sub(subfilter['pattern'], subfilter.get('repl', ''), data)
if 'pattern' not in subfilter: raise ValueError('{} needs a pattern'.format(self.__kind__)) # Default: Replace with empty string if no "repl" value is set return re.sub(subfilter['pattern'], subfilter.get('repl', ''), data)
27
121
82
203
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,695
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
880,881
869,894
filter
RemoveDuplicateLinesFilter
881,894
881,894
class RemoveDuplicateLinesFilter(FilterBase): """Remove duplicate lines""" __kind__ = 'remove-duplicate-lines' __supported_subfilters__ = { 'separator': 'Item separator (default: newline)', } __default_subfilter__ = 'separator' def filter(self, data, subfilter): FILL_FUNC_BODY
class RemoveDuplicateLinesFilter(FilterBase): """Remove duplicate lines""" __kind__ = 'remove-duplicate-lines' __supported_subfilters__ = { 'separator': 'Item separator (default: newline)', } __default_subfilter__ = 'separator' def filter(self, data, subfilter): FILL_FUNC_BODY
separator = subfilter.get('separator', '\n') data_lines = data.split(separator) def get_unique_lines(lines): seen = set() for line in lines: if line not in seen: yield line seen.add(line) return separator.j...
separator = subfilter.get('separator', '\n') data_lines = data.split(separator) def get_unique_lines(lines): seen = set() for line in lines: if line not in seen: yield line seen.add(line) return separator.j...
26
103
108
211
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,696
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
905,906
894,910
filter
ReverseFilter
906,910
906,910
class ReverseFilter(FilterBase): """Reverse input items""" __kind__ = 'reverse' __supported_subfilters__ = { 'separator': 'Item separator (default: newline)', } __default_subfilter__ = 'separator' def filter(self, data, subfilter): FILL_FUNC_BODY
class ReverseFilter(FilterBase): """Reverse input items""" __kind__ = 'reverse' __supported_subfilters__ = { 'separator': 'Item separator (default: newline)', } __default_subfilter__ = 'separator' def filter(self, data, subfilter): FILL_FUNC_BODY
separator = subfilter.get('separator', '\n') return separator.join(reversed(data.split(separator)))
separator = subfilter.get('separator', '\n') return separator.join(reversed(data.split(separator)))
6
99
41
140
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,697
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
642,643
635,648
filter
Sha1Filter
643,648
643,648
class Sha1Filter(FilterBase): """Calculate the SHA-1 checksum of the content""" __kind__ = 'sha1sum' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
class Sha1Filter(FilterBase): """Calculate the SHA-1 checksum of the content""" __kind__ = 'sha1sum' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
sha = hashlib.sha1() sha.update(data.encode('utf-8', 'ignore')) return sha.hexdigest()
sha = hashlib.sha1() sha.update(data.encode('utf-8', 'ignore')) return sha.hexdigest()
7
72
43
115
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,698
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
921,922
910,938
filter
ShellPipeFilter
922,938
922,938
class ShellPipeFilter(FilterBase): """Filter using a shell command""" __kind__ = 'shellpipe' __supported_subfilters__ = { 'command': 'Shell command to execute for filtering (required)', } __default_subfilter__ = 'command' def filter(self, data, subfilter): FILL_FUNC_BODY
class ShellPipeFilter(FilterBase): """Filter using a shell command""" __kind__ = 'shellpipe' __supported_subfilters__ = { 'command': 'Shell command to execute for filtering (required)', } __default_subfilter__ = 'command' def filter(self, data, subfilter): FILL_FUNC_BODY
if 'command' not in subfilter: raise ValueError('{} filter needs a command'.format(self.__kind__)) encoding = sys.getdefaultencoding() # Work on a copy to not modify the outside environment env = dict(os.environ) env.update({ 'URLWATCH_JOB_NAME': self.jo...
if 'command' not in subfilter: raise ValueError('{} filter needs a command'.format(self.__kind__)) encoding = sys.getdefaultencoding() # Work on a copy to not modify the outside environment env = dict(os.environ) env.update({ 'URLWATCH_JOB_NAME': self.jo...
47
97
184
281
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,699
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
863,864
851,869
filter
SortFilter
864,869
864,869
class SortFilter(FilterBase): """Sort input items""" __kind__ = 'sort' __supported_subfilters__ = { 'reverse': 'Set to true to reverse sorting order', 'separator': 'Item separator (default: newline)', } __default_subfilter__ = 'separator' def filter(self, data, subfilter): FI...
class SortFilter(FilterBase): """Sort input items""" __kind__ = 'sort' __supported_subfilters__ = { 'reverse': 'Set to true to reverse sorting order', 'separator': 'Item separator (default: newline)', } __default_subfilter__ = 'separator' def filter(self, data, subfilter): FI...
reverse = (isinstance(subfilter, dict) and subfilter.get('reverse', False) is True) separator = subfilter.get('separator', '\n') return separator.join(sorted(data.split(separator), key=str.casefold, reverse=reverse))
reverse = (isinstance(subfilter, dict) and subfilter.get('reverse', False) is True) separator = subfilter.get('separator', '\n') return separator.join(sorted(data.split(separator), key=str.casefold, reverse=reverse))
17
110
80
190
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,700
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
490,491
483,494
filter
StripFilter
491,494
491,494
class StripFilter(FilterBase): """Strip leading and trailing whitespace""" __kind__ = 'strip' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
class StripFilter(FilterBase): """Strip leading and trailing whitespace""" __kind__ = 'strip' __no_subfilter__ = True def filter(self, data, subfilter): FILL_FUNC_BODY
return data.strip()
return data.strip()
2
65
12
77
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,701
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
501,502
494,505
filter
StripLinesFilter
502,505
502,505
class StripLinesFilter(FilterBase): """Strip leading and trailing whitespace in every line""" __kind__ = 'striplines' __no_subfilter__ = True def filter(self, data, subfilter=None): FILL_FUNC_BODY
class StripLinesFilter(FilterBase): """Strip leading and trailing whitespace in every line""" __kind__ = 'striplines' __no_subfilter__ = True def filter(self, data, subfilter=None): FILL_FUNC_BODY
return '\n'.join(line.strip() for line in data.splitlines())
return '\n'.join(line.strip() for line in data.splitlines())
6
74
25
99
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,702
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/filters.py
825,826
813,831
filter
XPathFilter
826,831
826,831
class XPathFilter(FilterBase): """Filter XML/HTML using XPath expressions""" __kind__ = 'xpath' __supported_subfilters__ = { 'path': 'The XPath to use for filtering (required)', **LXML_PARSER_COMMON_SUBFILTERS, } __default_subfilter__ = 'path' def filter(self, data, subfilter...
class XPathFilter(FilterBase): """Filter XML/HTML using XPath expressions""" __kind__ = 'xpath' __supported_subfilters__ = { 'path': 'The XPath to use for filtering (required)', **LXML_PARSER_COMMON_SUBFILTERS, } __default_subfilter__ = 'path' def filter(self, data, subfilter...
lxml_parser = LxmlParser('xpath', subfilter, 'path') lxml_parser.feed(data) return lxml_parser.get_filtered_data()
lxml_parser = LxmlParser('xpath', subfilter, 'path') lxml_parser.feed(data) return lxml_parser.get_filtered_data()
8
118
53
171
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,703
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/handler.py
91,92
49,176
save
JobState
92,98
92,98
class JobState(object): def __init__(self, cache_storage, job): self.cache_storage = cache_storage self.job = job self.verb = None self.old_data = None self.new_data = None self.history_data = {} self.timestamp = None self.current_timestamp = None ...
class JobState(object): def __init__(self, cache_storage, job): self.cache_storage = cache_storage self.job = job self.verb = None self.old_data = None self.new_data = None self.history_data = {} self.timestamp = None self.current_timestamp = None ...
if self.new_data is None and self.exception is not None: # If no new data has been retrieved due to an exception, use the old job data self.new_data = self.old_data self.cache_storage.save(self.job, self.job.get_guid(), self.new_data, time.time(), self.tries, self.etag)
if self.new_data is None and self.exception is not None: # If no new data has been retrieved due to an exception, use the old job data self.new_data = self.old_data self.cache_storage.save(self.job, self.job.get_guid(), self.new_data, time.time(), self.tries, self.etag)
35
1,438
103
1,541
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,704
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/handler.py
219,220
176,224
finish_one
Report
220,224
220,224
class Report(object): def __init__(self, urlwatch_config): self.config = urlwatch_config.config_storage.config self.job_states = [] self.start = datetime.datetime.now() def _result(self, verb, job_state): if job_state.exception is not None: logger.debug('Got excepti...
class Report(object): def __init__(self, urlwatch_config): self.config = urlwatch_config.config_storage.config self.job_states = [] self.start = datetime.datetime.now() def _result(self, verb, job_state): if job_state.exception is not None: logger.debug('Got excepti...
end = datetime.datetime.now() duration = (end - self.start) ReporterBase.submit_one(name, self, self.job_states, duration)
end = datetime.datetime.now() duration = (end - self.start) ReporterBase.submit_one(name, self, self.job_states, duration)
12
432
48
480
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,705
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/html2txt.py
49,50
1,138
html2text
66,138
50,138
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
if method == 're': stripped_tags = re.sub(r'<[^>]*>', '', data) d = '\n'.join((line.rstrip() for line in stripped_tags.splitlines() if line.strip() != '')) return d if method == 'pyhtml2text': if pyhtml2text is None: raise ImportError("Please install python's html2te...
""" Convert a string consisting of HTML to plain text for easy difference checking. Method may be one of: 'lynx' - Use "lynx -dump" for conversion options: see "lynx -help" output for options that work with "-dump" 'html2text' - Use "html2text -nobs" for...
301
881
1,055
1,936
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,706
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/ical2txt.py
37,38
1,70
ical2text
38,70
38,70
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
if vobject is None: raise ImportError('Please install vobject') result = [] if isinstance(ical_string, str): parsedCal = vobject.readOne(ical_string) else: try: parsedCal = vobject.readOne(ical_string) except Exception: parsedCal = vobject.readOne...
if vobject is None: raise ImportError('Please install vobject') result = [] if isinstance(ical_string, str): parsedCal = vobject.readOne(ical_string) else: try: parsedCal = vobject.readOne(ical_string) except Exception: parsedCal = vobject.readOne...
83
557
327
884
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,707
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/mailer.py
128,129
1,135
set_password
130,135
129,135
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
if keyring is None: raise ImportError('keyring module missing - service unsupported') password = getpass.getpass(prompt='Enter password for {} using {}: '.format(from_email, smtp_server)) keyring.set_password(smtp_server, from_email, password)
''' Set the keyring password for the mail connection. Interactive.''' if keyring is None: raise ImportError('keyring module missing - service unsupported') password = getpass.getpass(prompt='Enter password for {} using {}: '.format(from_email, smtp_server)) keyring.set_password(smtp_server, fro...
24
1,545
82
1,627
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,708
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/mailer.py
52,53
48,78
msg_plain
Mailer
53,63
53,63
class Mailer(object): def send(self, msg): raise NotImplementedError def msg_plain(self, from_email, to_email, reply_to_email, subject, body): FILL_FUNC_BODY def msg_html(self, from_email, to_email, reply_to_email, subject, body_text, body_html): msg = email.mime.multipart.MIMEMultipart('alt...
class Mailer(object): def send(self, msg): raise NotImplementedError def msg_plain(self, from_email, to_email, reply_to_email, subject, body): FILL_FUNC_BODY def msg_html(self, from_email, to_email, reply_to_email, subject, body_text, body_html): msg = email.mime.multipart.MIMEMultipart('alt...
msg = email.mime.text.MIMEText(body, 'plain', 'utf-8') msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email msg['Date'] = email.utils.formatdate() if reply_to_email: msg['Reply-To'] = reply_to_email return msg
msg = email.mime.text.MIMEText(body, 'plain', 'utf-8') msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email msg['Date'] = email.utils.formatdate() if reply_to_email: msg['Reply-To'] = reply_to_email return msg
24
252
108
360
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,709
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/mailer.py
87,88
78,110
send
SMTPMailer
88,110
88,110
class SMTPMailer(Mailer): def __init__(self, smtp_user, smtp_server, smtp_port, tls, auth, insecure_password=None): self.smtp_server = smtp_server self.smtp_user = smtp_user self.smtp_port = smtp_port self.tls = tls self.auth = auth self.insecure_password = insecure_p...
class SMTPMailer(Mailer): def __init__(self, smtp_user, smtp_server, smtp_port, tls, auth, insecure_password=None): self.smtp_server = smtp_server self.smtp_user = smtp_user self.smtp_port = smtp_port self.tls = tls self.auth = auth self.insecure_password = insecure_p...
s = smtplib.SMTP(self.smtp_server, self.smtp_port) s.ehlo() if self.tls: s.starttls() if self.auth: if self.insecure_password: passwd = self.insecure_password elif keyring is not None: passwd = keyring.get_password(sel...
s = smtplib.SMTP(self.smtp_server, self.smtp_port) s.ehlo() if self.tls: s.starttls() if self.auth: if self.insecure_password: passwd = self.insecure_password elif keyring is not None: passwd = keyring.get_password(sel...
61
133
268
401
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,710
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/mailer.py
114,115
110,124
send
SendmailMailer
115,124
115,124
class SendmailMailer(Mailer): def __init__(self, sendmail_path): self.sendmail_path = sendmail_path def send(self, msg): FILL_FUNC_BODY
class SendmailMailer(Mailer): def __init__(self, sendmail_path): self.sendmail_path = sendmail_path def send(self, msg): FILL_FUNC_BODY
p = subprocess.Popen([self.sendmail_path, '-oi', '-f', msg['From']] + msg['To'].split(','), stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) result = p.communicate(msg.as_string(maxheaderlen=78)...
p = subprocess.Popen([self.sendmail_path, '-oi', '-f', msg['From']] + msg['To'].split(','), stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) result = p.communicate(msg.as_string(maxheaderlen=78)...
20
56
129
185
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,711
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/main.py
71,72
41,114
should_run
Urlwatch
72,86
72,86
class Urlwatch(object): def __init__(self, urlwatch_config, config_storage, cache_storage, urls_storage): self.urlwatch_config = urlwatch_config logger.info('Using %s as URLs file', self.urlwatch_config.urls) logger.info('Using %s for hooks', self.urlwatch_config.hooks) logger.info...
class Urlwatch(object): def __init__(self, urlwatch_config, config_storage, cache_storage, urls_storage): self.urlwatch_config = urlwatch_config logger.info('Using %s as URLs file', self.urlwatch_config.urls) logger.info('Using %s for hooks', self.urlwatch_config.hooks) logger.info...
if not job.is_enabled(): return False # Tag mode and tag(s) were specified if self.urlwatch_config.tags and self.urlwatch_config.tag_set: return job.matching_tags(self.urlwatch_config.tag_set) # Index mode and index(es) were specified if not self.urlwatc...
if not job.is_enabled(): return False # Tag mode and tag(s) were specified if self.urlwatch_config.tags and self.urlwatch_config.tag_set: return job.matching_tags(self.urlwatch_config.tag_set) # Index mode and index(es) were specified if not self.urlwatc...
44
654
154
808
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,712
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/migration.py
71,72
1,89
migrate_cache
72,89
72,89
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# Migrate urlwatch 1.x cache to urlwatch 2.x urlwatch_config = urlwatcher.urlwatch_config cache = urlwatch_config.cache cache_dir = os.path.join(urlwatch_config.urlwatch_dir, 'cache') # On Windows and macOS with case-insensitive filesystems, we have to check if # "cache.db" exists in the folde...
# Migrate urlwatch 1.x cache to urlwatch 2.x urlwatch_config = urlwatcher.urlwatch_config cache = urlwatch_config.cache cache_dir = os.path.join(urlwatch_config.urlwatch_dir, 'cache') # On Windows and macOS with case-insensitive filesystems, we have to check if # "cache.db" exists in the folde...
72
1,033
308
1,341
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,713
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/util.py
116,117
1,141
chunkstring
117,141
117,141
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
if len(string) <= length: return [string] if numbering: # Subtract to fit numbering (FIXME: this breaks for > 9 chunks) length -= len(' (0/0)') parts = [] string = string.strip() while string: if len(string) <= length: parts.append(str...
if len(string) <= length: return [string] if numbering: # Subtract to fit numbering (FIXME: this breaks for > 9 chunks) length -= len(' (0/0)') parts = [] string = string.strip() while string: if len(string) <= length: parts.append(str...
93
1,340
265
1,605
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,714
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/util.py
46,48
43,84
sorted_by_kind
TrackSubClasses
48,50
48,50
class TrackSubClasses(type): """A metaclass that stores subclass name-to-class mappings in the base class""" @staticmethod def sorted_by_kind(cls): FILL_FUNC_BODY def __init__(cls, name, bases, namespace): for base in bases: if base == object: continue fo...
class TrackSubClasses(type): """A metaclass that stores subclass name-to-class mappings in the base class""" @staticmethod def sorted_by_kind(cls): FILL_FUNC_BODY def __init__(cls, name, bases, namespace): for base in bases: if base == object: continue fo...
return [item for _, item in sorted((it.__kind__, it) for it in cls.__subclasses__.values())]
return [item for _, item in sorted((it.__kind__, it) for it in cls.__subclasses__.values())]
12
359
34
393
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,715
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/worker.py
53,54
1,114
run_jobs
54,114
54,114
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
if not urlwatcher.urlwatch_config.tags and not all(1 <= idx <= len(urlwatcher.jobs) for idx in urlwatcher.urlwatch_config.idx_set): raise ValueError(f'All job indices must be between 1 and {len(urlwatcher.jobs)}: {urlwatcher.urlwatch_config.joblist}') cache_storage = urlwatcher.cache_storage jobs = ...
if not urlwatcher.urlwatch_config.tags and not all(1 <= idx <= len(urlwatcher.jobs) for idx in urlwatcher.urlwatch_config.idx_set): raise ValueError(f'All job indices must be between 1 and {len(urlwatcher.jobs)}: {urlwatcher.urlwatch_config.joblist}') cache_storage = urlwatcher.cache_storage jobs = ...
212
693
946
1,639
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,716
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/xmpp.py
80,81
1,87
xmpp_set_password
82,87
81,87
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
if keyring is None: raise ImportError("keyring module missing - service unsupported") password = getpass.getpass(prompt="Enter password for {}: ".format(sender)) keyring.set_password("urlwatch_xmpp", sender, password)
""" Set the keyring password for the XMPP connection. Interactive.""" if keyring is None: raise ImportError("keyring module missing - service unsupported") password = getpass.getpass(prompt="Enter password for {}: ".format(sender)) keyring.set_password("urlwatch_xmpp", sender, password)
21
997
74
1,071
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
40,717
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch
/home/hieuvd/dung_repo/raw/stars_02/thp_urlwatch/urlwatch/lib/urlwatch/xmpp.py
53,54
44,76
send
XMPP
54,76
54,76
class XMPP(object): def __init__(self, sender, recipient, insecure_password=None): if aioxmpp is None: raise ImportError('Python module "aioxmpp" not installed') self.sender = sender self.recipient = recipient self.insecure_password = insecure_password async def sen...
class XMPP(object): def __init__(self, sender, recipient, insecure_password=None): if aioxmpp is None: raise ImportError('Python module "aioxmpp" not installed') self.sender = sender self.recipient = recipient self.insecure_password = insecure_password async def sen...
if self.insecure_password: password = self.insecure_password elif keyring is not None: password = keyring.get_password("urlwatch_xmpp", self.sender) if password is None: raise ValueError( "No password available in keyring for {}".fo...
if self.insecure_password: password = self.insecure_password elif keyring is not None: password = keyring.get_password("urlwatch_xmpp", self.sender) if password is None: raise ValueError( "No password available in keyring for {}".fo...
54
108
273
381
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
# -*- coding: utf-8 -*- # # This file is part of urlwatch (https://thp.io/2008/urlwatch/). # Copyright (c) 2008-2023 Thomas Perl <m@thp.io> # 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....
41,061
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter/novelwriter/core/options.py
124,125
79,223
saveSettings
OptionState
126,146
125,146
class OptionState: """Core: GUI Options Storage A class for storing the state of the GUI. The data is stored per project. Settings that should be project-independent are stored in the Config instead. """ def __init__(self, project: NWProject) -> None: self._project = project se...
class OptionState: """Core: GUI Options Storage A class for storing the state of the GUI. The data is stored per project. Settings that should be project-independent are stored in the Config instead. """ def __init__(self, project: NWProject) -> None: self._project = project se...
stateFile = self._project.storage.getMetaFile(nwFiles.OPTS_FILE) if not isinstance(stateFile, Path): return False logger.debug("Saving GUI options file") try: with open(stateFile, mode="w+", encoding="utf-8") as fObj: data = {"novelWriter.guiOptio...
"""Save the options dictionary to the project.""" stateFile = self._project.storage.getMetaFile(nwFiles.OPTS_FILE) if not isinstance(stateFile, Path): return False logger.debug("Saving GUI options file") try: with open(stateFile, mode="w+", encoding="utf-...
43
1,130
184
1,314
""" novelWriter – Project Options Cache =================================== File History: Created: 2019-10-21 [0.3.1] OptionState Rewritten: 2020-02-19 [0.4.5] OptionState This file is a part of novelWriter Copyright 2018–2024, Veronica Berglyd Olsen This program is free software: you can redistribute it and/or mo...
""" novelWriter – Project Options Cache =================================== File History: Created: 2019-10-21 [0.3.1] OptionState Rewritten: 2020-02-19 [0.4.5] OptionState This file is a part of novelWriter Copyright 2018–2024, Veronica Berglyd Olsen This program is free software: you can redistribute it and/or mo...
41,064
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter/novelwriter/core/projectxml.py
489,490
464,584
write
ProjectXMLWriter
491,566
490,566
class ProjectXMLWriter: """Core: Project XML Writer The project writer class will only write a file according to the very latest spec. """ def __init__(self, path: str | Path) -> None: self._path = Path(path) self._error = None return ## # Properties ## @...
class ProjectXMLWriter: """Core: Project XML Writer The project writer class will only write a file according to the very latest spec. """ def __init__(self, path: str | Path) -> None: self._path = Path(path) self._error = None return ## # Properties ## @...
tStart = time() logger.debug("Writing project XML") xRoot = ET.Element("novelWriterXML", attrib={ "appVersion": str(__version__), "hexVersion": str(__hexversion__), "fileVersion": FILE_VERSION, "fileRevision": FILE_REVISION, "timeStamp...
"""Write the project data and content to the XML files.""" tStart = time() logger.debug("Writing project XML") xRoot = ET.Element("novelWriterXML", attrib={ "appVersion": str(__version__), "hexVersion": str(__hexversion__), "fileVersion": FILE_VERSION...
190
420
908
1,328
""" novelWriter – Project XML Read/Write ==================================== File History: Created: 2022-09-28 [2.0rc2] XMLReadState Created: 2022-09-28 [2.0rc2] ProjectXMLReader Created: 2022-10-31 [2.0rc2] ProjectXMLWriter This file is a part of novelWriter Copyright 2018–2024, Veronica Berglyd Olsen This program...
""" novelWriter – Project XML Read/Write ==================================== File History: Created: 2022-09-28 [2.0rc2] XMLReadState Created: 2022-09-28 [2.0rc2] ProjectXMLReader Created: 2022-10-31 [2.0rc2] ProjectXMLWriter This file is a part of novelWriter Copyright 2018–2024, Veronica Berglyd Olsen This program...
41,065
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter/novelwriter/core/sessions.py
74,75
44,140
appendSession
NWSessionLog
76,113
75,113
class NWSessionLog: """Core: Session JSON Lines Log File The class that wraps the session log file, which is in JSON Lines format. That is, one JSON object per line. """ def __init__(self, project: NWProject) -> None: self._project = project self._start = 0.0 return ##...
class NWSessionLog: """Core: Session JSON Lines Log File The class that wraps the session log file, which is in JSON Lines format. That is, one JSON object per line. """ def __init__(self, project: NWProject) -> None: self._project = project self._start = 0.0 return ##...
sessFile = self._project.storage.getMetaFile(nwFiles.SESS_FILE) if not isinstance(sessFile, Path): return False now = time() iNovel, iNotes = self._project.data.initCounts cNovel, cNotes = self._project.data.currCounts iTotal = iNovel + iNotes wDiff =...
"""Append session statistics to the sessions log file.""" sessFile = self._project.storage.getMetaFile(nwFiles.SESS_FILE) if not isinstance(sessFile, Path): return False now = time() iNovel, iNotes = self._project.data.initCounts cNovel, cNotes = self._projec...
102
542
401
943
""" novelWriter – Project Session Log Class ======================================= File History: Created: 2023-06-11 [2.1b1] NWSessionLog This file is a part of novelWriter Copyright 2018–2024, Veronica Berglyd Olsen This program is free software: you can redistribute it and/or modify it under the terms of the GNU ...
""" novelWriter – Project Session Log Class ======================================= File History: Created: 2023-06-11 [2.1b1] NWSessionLog This file is a part of novelWriter Copyright 2018–2024, Veronica Berglyd Olsen This program is free software: you can redistribute it and/or modify it under the terms of the GNU ...
41,069
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter
/home/hieuvd/dung_repo/raw/stars_02/vkbo_novelWriter/novelWriter/novelwriter/text/counting.py
74,75
1,139
standardCounter
79,124
75,124
""" novelWriter – Text Counting Functions ===================================== File History: Created: 2019-04-22 [0.0.1] standardCounter Rewritten: 2024-02-27 [2.4b1] preProcessText, standardCounter Created: 2024-02-27 [2.4b1] bodyTextCounter This file is a part of novelWriter Copyright 2018–2024, Veronica Bergl...
""" novelWriter – Text Counting Functions ===================================== File History: Created: 2019-04-22 [0.0.1] standardCounter Rewritten: 2024-02-27 [2.4b1] preProcessText, standardCounter Created: 2024-02-27 [2.4b1] bodyTextCounter This file is a part of novelWriter Copyright 2018–2024, Veronica Bergl...
cCount = 0 wCount = 0 pCount = 0 prevEmpty = True for line in preProcessText(text): countPara = True if not line: prevEmpty = True continue if line[0] == "#": if line[:5] == "#### ": line = line[5:] countP...
"""A counter that counts paragraphs, words and characters. This is the standard counter that includes headings in the word and character counts. """ cCount = 0 wCount = 0 pCount = 0 prevEmpty = True for line in preProcessText(text): countPara = True if not line: ...
128
980
356
1,336
""" novelWriter – Text Counting Functions ===================================== File History: Created: 2019-04-22 [0.0.1] standardCounter Rewritten: 2024-02-27 [2.4b1] preProcessText, standardCounter Created: 2024-02-27 [2.4b1] bodyTextCounter This file is a part of novelWriter Copyright 2018–2024, Veronica Bergl...
""" novelWriter – Text Counting Functions ===================================== File History: Created: 2019-04-22 [0.0.1] standardCounter Rewritten: 2024-02-27 [2.4b1] preProcessText, standardCounter Created: 2024-02-27 [2.4b1] bodyTextCounter This file is a part of novelWriter Copyright 2018–2024, Veronica Bergl...
41,071
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi/pyVim/connect.py
100,101
86,200
_doLogin
VimSessionOrientedStub
101,106
101,106
class VimSessionOrientedStub(SessionOrientedStub): """A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information. """ # The set of exceptions that should trigger a relogin by the session stub. SESSION_EXCEPTIONS = (vim.fault.NotAuthenticate...
class VimSessionOrientedStub(SessionOrientedStub): """A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information. """ # The set of exceptions that should trigger a relogin by the session stub. SESSION_EXCEPTIONS = (vim.fault.NotAuthenticate...
si = vim.ServiceInstance("ServiceInstance", soapStub) sm = si.content.sessionManager if not sm.currentSession: si.content.sessionManager.Login(username, password, locale)
si = vim.ServiceInstance("ServiceInstance", soapStub) sm = si.content.sessionManager if not sm.currentSession: si.content.sessionManager.Login(username, password, locale)
13
1,200
59
1,259
############################################################# # Copyright (c) 2005-2024 Broadcom. All Rights Reserved. # The term "Broadcom" refers to Broadcom Inc. # and/or its subsidiaries. ############################################################# # @file connect.py # @brief Connect to a VMOMI ServiceInstance. #...
############################################################# # Copyright (c) 2005-2024 Broadcom. All Rights Reserved. # The term "Broadcom" refers to Broadcom Inc. # and/or its subsidiaries. ############################################################# # @file connect.py # @brief Connect to a VMOMI ServiceInstance. #...
41,072
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi/pyVmomi/Cache.py
9,10
1,31
Cache
11,31
10,31
""" Copyright (c) 2008-2022 VMware, Inc. This module implements the cache decorator """ __author__ = "VMware, Inc" def Cache(fn): FILL_FUNC_BODY
""" Copyright (c) 2008-2022 VMware, Inc. This module implements the cache decorator """ __author__ = "VMware, Inc" def Cache(fn): """ Function cache decorator """ FILL_FUNC_BODY
def fnCache(*args, **kwargs): """ Cache function """ key = (args and tuple(args) or None, kwargs and frozenset(list(kwargs.items())) or None) if key not in fn.__cached__: fn.__cached__[key] = cache = fn(*args, **kwargs) else: cache = fn.__cached...
""" Function cache decorator """ def fnCache(*args, **kwargs): """ Cache function """ key = (args and tuple(args) or None, kwargs and frozenset(list(kwargs.items())) or None) if key not in fn.__cached__: fn.__cached__[key] = cache = fn(*args, **kwargs) ...
60
70
223
293
""" Copyright (c) 2008-2022 VMware, Inc. This module implements the cache decorator """ __author__ = "VMware, Inc" def Cache(fn): FILL_FUNC_BODY
""" Copyright (c) 2008-2022 VMware, Inc. This module implements the cache decorator """ __author__ = "VMware, Inc" def Cache(fn): """ Function cache decorator """ FILL_FUNC_BODY
41,073
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi/pyVmomi/Feature.py
27,28
1,37
set_feature_state
28,37
28,37
""" Copyright (c) 2021-2022 VMware, Inc. This module handles pyVmomi features states """ from collections import namedtuple from . import _assert_not_initialized # pyVmomi features along with their default states. # e.g., 'newFeature': False _features = { } Features = namedtuple('Features', _features.keys()) flags =...
""" Copyright (c) 2021-2022 VMware, Inc. This module handles pyVmomi features states """ from collections import namedtuple from . import _assert_not_initialized # pyVmomi features along with their default states. # e.g., 'newFeature': False _features = { } Features = namedtuple('Features', _features.keys()) flags =...
_assert_not_initialized() if feature_name not in _features: raise AttributeError("Feature '{0}' is not supported!".format(feature_name)) if not isinstance(feature_name, str): raise TypeError("Feature name should be string!") if not isinstance(state, bool): raise TypeError("Featur...
_assert_not_initialized() if feature_name not in _features: raise AttributeError("Feature '{0}' is not supported!".format(feature_name)) if not isinstance(feature_name, str): raise TypeError("Feature name should be string!") if not isinstance(state, bool): raise TypeError("Featur...
35
174
115
289
""" Copyright (c) 2021-2022 VMware, Inc. This module handles pyVmomi features states """ from collections import namedtuple from . import _assert_not_initialized # pyVmomi features along with their default states. # e.g., 'newFeature': False _features = { } Features = namedtuple('Features', _features.keys()) flags =...
""" Copyright (c) 2021-2022 VMware, Inc. This module handles pyVmomi features states """ from collections import namedtuple from . import _assert_not_initialized # pyVmomi features along with their default states. # e.g., 'newFeature': False _features = { } Features = namedtuple('Features', _features.keys()) flags =...
41,075
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi
/home/hieuvd/dung_repo/raw/stars_02/vmware_pyvmomi/pyvmomi/pyVmomi/Iso8601.py
80,81
59,88
dst
TZInfo
81,88
81,88
class TZInfo(tzinfo): """ Timezone info class """ timedelta0 = timedelta(hours=0) timedelta1 = timedelta(hours=1) def __init__(self, tzname='UTC', utcOffset=None, dst=None): self._tzname = tzname if not utcOffset: utcOffset = self.timedelta0 self._utcOffset = utcOff...
class TZInfo(tzinfo): """ Timezone info class """ timedelta0 = timedelta(hours=0) timedelta1 = timedelta(hours=1) def __init__(self, tzname='UTC', utcOffset=None, dst=None): self._tzname = tzname if not utcOffset: utcOffset = self.timedelta0 self._utcOffset = utcOff...
ret = self.timedelta0 if self._dst: if self._dst[0] <= dt.replace(tzinfo=None) < self._dst[1]: ret = self.timedelta1 return ret
ret = self.timedelta0 if self._dst: if self._dst[0] <= dt.replace(tzinfo=None) < self._dst[1]: ret = self.timedelta1 return ret
16
208
69
277
#!/usr/bin/env python """ Copyright (c) 2009-2022 VMware, Inc. This module is for ISO 8601 parsing """ __author__ = 'VMware, Inc' import re import time from datetime import datetime, timedelta, tzinfo import six # Regular expression to parse a subset of ISO 8601 format _dtExpr = re.compile( # XMLSchema datetime...
#!/usr/bin/env python """ Copyright (c) 2009-2022 VMware, Inc. This module is for ISO 8601 parsing """ __author__ = 'VMware, Inc' import re import time from datetime import datetime, timedelta, tzinfo import six # Regular expression to parse a subset of ISO 8601 format _dtExpr = re.compile( # XMLSchema datetime...