uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
b6a4b43a333b5ec6cb2a9534
train
function
def _infer_column_names(filenames, field_delim, use_quote_delim, file_io_fn): """Infers column names from first rows of files.""" csv_kwargs = { "delimiter": field_delim, "quoting": csv.QUOTE_MINIMAL if use_quote_delim else csv.QUOTE_NONE } with file_io_fn(filenames[0]) as f: try: ...
def _infer_column_names(filenames, field_delim, use_quote_delim, file_io_fn):
"""Infers column names from first rows of files.""" csv_kwargs = { "delimiter": field_delim, "quoting": csv.QUOTE_MINIMAL if use_quote_delim else csv.QUOTE_NONE } with file_io_fn(filenames[0]) as f: try: column_names = next(csv.reader(f, **csv_kwargs)) except StopIteration: ...
inferred_types] # Default to 0 or '' for null values return [ constant_op.constant([0 if t is not dtypes.string else ""], dtype=t) for t in inferred_types ] def _infer_column_names(filenames, field_delim, use_quote_delim, file_io_fn):
67
68
228
21
46
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_infer_column_names
_infer_column_names
159
181
159
159
2a36b1d06d10acddaa3da30bcdc2291b152b2bc0
bigcode/the-stack
train
01b770ca3b947263197e0b46
train
function
def _is_valid_int64(str_val): try: dtypes.int64.as_numpy_dtype(str_val) return True except (ValueError, OverflowError): return False
def _is_valid_int64(str_val):
try: dtypes.int64.as_numpy_dtype(str_val) return True except (ValueError, OverflowError): return False
32(str_val): try: # Checks equality to prevent int32 overflow return dtypes.int32.as_numpy_dtype(str_val) == dtypes.int64.as_numpy_dtype( str_val) except (ValueError, OverflowError): return False def _is_valid_int64(str_val):
64
64
40
9
54
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_is_valid_int64
_is_valid_int64
60
65
60
60
59b50853c057248daa8a5167361aaeac08fd4ab4
bigcode/the-stack
train
133120ec15306efefc55b093
train
function
def _infer_type(str_val, na_value, prev_type): """Given a string, infers its tensor type. Infers the type of a value by picking the least 'permissive' type possible, while still allowing the previous type inference for this column to be valid. Args: str_val: String value to infer the type of. ...
def _infer_type(str_val, na_value, prev_type):
"""Given a string, infers its tensor type. Infers the type of a value by picking the least 'permissive' type possible, while still allowing the previous type inference for this column to be valid. Args: str_val: String value to infer the type of. na_value: Additional string to recognize as a NA...
OverflowError): return False def _is_valid_int64(str_val): try: dtypes.int64.as_numpy_dtype(str_val) return True except (ValueError, OverflowError): return False def _is_valid_float(str_val, float_dtype): try: return float_dtype.as_numpy_dtype(str_val) < np.inf except Val...
97
97
326
13
83
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_infer_type
_infer_type
75
109
75
75
356bfdb88c40339d22685ea306ba551ff17fd4d0
bigcode/the-stack
train
8a2db045c54355a7147ca52d
train
function
def _get_file_names(file_pattern, shuffle): """Parse list of file names from pattern, optionally shuffled. Args: file_pattern: File glob pattern, or list of glob patterns. shuffle: Whether to shuffle the order of file names. Returns: List of file names matching `file_pattern`. Raises: ...
def _get_file_names(file_pattern, shuffle):
"""Parse list of file names from pattern, optionally shuffled. Args: file_pattern: File glob pattern, or list of glob patterns. shuffle: Whether to shuffle the order of file names. Returns: List of file names matching `file_pattern`. Raises: ValueError: If `file_pattern` is empty, o...
shuffle_buffer_size, shuffle_seed, prefetch_buffer_size, reader_num_threads, parser_num_threads, sloppy_ordering, drop_final_batch)) make_batched_features_dataset_v2.__doc__ = ( make_batched_features_dataset_v1.__doc__) def _get_file_names(file_pattern, shuffle):
63
64
202
10
53
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_get_file_names
_get_file_names
915
943
915
915
3843ae3d25b1f8cef940e73087d7acc3aba13029
bigcode/the-stack
train
c6bc8f6e30fb404358a199d1
train
function
def _next_csv_row(filenames, num_cols, field_delim, use_quote_delim, header, file_io_fn): """Generator that yields rows of CSV file(s) in order.""" for fn in filenames: with file_io_fn(fn) as f: rdr = csv.reader( f, delimiter=field_delim, quoting=csv...
def _next_csv_row(filenames, num_cols, field_delim, use_quote_delim, header, file_io_fn):
"""Generator that yields rows of CSV file(s) in order.""" for fn in filenames: with file_io_fn(fn) as f: rdr = csv.reader( f, delimiter=field_delim, quoting=csv.QUOTE_MINIMAL if use_quote_delim else csv.QUOTE_NONE) if header: next(rdr) # Skip header lin...
[i] if validation_fn(str_val) and (prev_type is None or prev_type in type_list[:i + 1]): return type_list[i] def _next_csv_row(filenames, num_cols, field_delim, use_quote_delim, header, file_io_fn):
63
64
155
27
36
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_next_csv_row
_next_csv_row
112
129
112
113
f0c99c58d596ee2e2095c312b3d899e752a515a2
bigcode/the-stack
train
5eed71e0a32393eb0ca55762
train
function
def _is_valid_float(str_val, float_dtype): try: return float_dtype.as_numpy_dtype(str_val) < np.inf except ValueError: return False
def _is_valid_float(str_val, float_dtype):
try: return float_dtype.as_numpy_dtype(str_val) < np.inf except ValueError: return False
except (ValueError, OverflowError): return False def _is_valid_int64(str_val): try: dtypes.int64.as_numpy_dtype(str_val) return True except (ValueError, OverflowError): return False def _is_valid_float(str_val, float_dtype):
64
64
37
11
52
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_is_valid_float
_is_valid_float
68
72
68
68
1bdd6cf768f70c952c96d731770016b08a047911
bigcode/the-stack
train
943475ead09d45f9593ce2aa
train
function
@tf_export(v1=["data.experimental.make_batched_features_dataset"]) def make_batched_features_dataset_v1(file_pattern, # pylint: disable=missing-docstring batch_size, features, reader=core_readers.TFRecord...
@tf_export(v1=["data.experimental.make_batched_features_dataset"]) def make_batched_features_dataset_v1(file_pattern, # pylint: disable=missing-docstring batch_size, features, reader=core_readers.TFRecord...
return dataset_ops.DatasetV1Adapter(make_batched_features_dataset_v2( file_pattern, batch_size, features, reader, label_key, reader_args, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed, prefetch_buffer_size, reader_num_threads, parser_num_threads, sloppy_ordering, drop_final_batch)...
@tf_export(v1=["data.experimental.make_batched_features_dataset"]) def make_batched_features_dataset_v1(file_pattern, # pylint: disable=missing-docstring batch_size, features, reader=core_readers.TFRecord...
125
64
194
125
0
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
make_batched_features_dataset_v1
make_batched_features_dataset_v1
890
910
890
905
a1aaa7603d3e664a04cf4628e85937f4228b4835
bigcode/the-stack
train
54ed103ad93f27ef4ec04d87
train
class
@tf_export("data.experimental.CsvDataset", v1=[]) class CsvDatasetV2(dataset_ops.DatasetSource): """A Dataset comprising lines from one or more CSV files.""" def __init__(self, filenames, record_defaults, compression_type=None, buffer_size=None, ...
@tf_export("data.experimental.CsvDataset", v1=[]) class CsvDatasetV2(dataset_ops.DatasetSource):
"""A Dataset comprising lines from one or more CSV files.""" def __init__(self, filenames, record_defaults, compression_type=None, buffer_size=None, header=False, field_delim=",", use_quote_delim=True,...
=None, select_columns=None, field_delim=",", use_quote_delim=True, na_value="", header=True, num_epochs=None, shuffle=True, shuffle_buffer_size=10000, shuffle_seed=None, prefetch_buffer_size=dataset_ops.AUTOTUNE, num_parallel_reads=1, sloppy=False, num_ro...
256
256
1,295
24
231
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
CsvDatasetV2
CsvDatasetV2
576
706
576
577
a0f60ebf31ad09e9a238f98c5379fb06f1f3c99d
bigcode/the-stack
train
30005bb543c6a087b50f5a1d
train
function
@tf_export("data.experimental.make_csv_dataset", v1=[]) def make_csv_dataset_v2( file_pattern, batch_size, column_names=None, column_defaults=None, label_name=None, select_columns=None, field_delim=",", use_quote_delim=True, na_value="", header=True, num_epochs=No...
@tf_export("data.experimental.make_csv_dataset", v1=[]) def make_csv_dataset_v2( file_pattern, batch_size, column_names=None, column_defaults=None, label_name=None, select_columns=None, field_delim=",", use_quote_delim=True, na_value="", header=True, num_epochs=No...
"""Reads CSV files into a dataset. Reads CSV files into a dataset, where each element is a (features, labels) tuple that corresponds to a batch of CSV rows. The features dictionary maps feature column names to `Tensor`s containing the corresponding feature data, and labels is a `Tensor` containing the b...
= dataset.batch(batch_size, drop_remainder=drop_final_batch) else: # TODO(josh11b): if num_parallel_parser_calls is None, use some function # of num cores instead of map_and_batch's default behavior of one batch. dataset = dataset.apply(batching.map_and_batch( parser_fn, batch_size, num_para...
256
256
2,357
137
119
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
make_csv_dataset_v2
make_csv_dataset_v2
314
538
314
336
38705c18822f2cba25eba932cadea858633da43b
bigcode/the-stack
train
f9e7c637b9ab5830b2a55620
train
function
def _infer_column_defaults(filenames, num_cols, field_delim, use_quote_delim, na_value, header, num_rows_for_inference, select_columns, file_io_fn): """Infers column types from the first N valid CSV records of files.""" if select_columns is None: select...
def _infer_column_defaults(filenames, num_cols, field_delim, use_quote_delim, na_value, header, num_rows_for_inference, select_columns, file_io_fn):
"""Infers column types from the first N valid CSV records of files.""" if select_columns is None: select_columns = range(num_cols) inferred_types = [None] * len(select_columns) for i, csv_row in enumerate( _next_csv_row(filenames, num_cols, field_delim, use_quote_delim, header, ...
num_cols: raise ValueError( "Problem inferring types: CSV row has different number of fields " "than expected.") yield csv_row def _infer_column_defaults(filenames, num_cols, field_delim, use_quote_delim, na_value, header, num_rows_for_infer...
73
73
244
40
32
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
_infer_column_defaults
_infer_column_defaults
132
156
132
134
f9b6584a59f90502b6e80846e849c8482dc55459
bigcode/the-stack
train
e38895686d14d4631a7f6da8
train
class
@tf_export("data.experimental.SqlDataset", v1=[]) class SqlDatasetV2(dataset_ops.DatasetSource): """A `Dataset` consisting of the results from a SQL query.""" def __init__(self, driver_name, data_source_name, query, output_types): """Creates a `SqlDataset`. `SqlDataset` allows a user to read data f...
@tf_export("data.experimental.SqlDataset", v1=[]) class SqlDatasetV2(dataset_ops.DatasetSource):
"""A `Dataset` consisting of the results from a SQL query.""" def __init__(self, driver_name, data_source_name, query, output_types): """Creates a `SqlDataset`. `SqlDataset` allows a user to read data from the result set of a SQL query. For example: ```python tf.compat.v1.enable_eage...
, list): if not file_pattern: raise ValueError("File pattern is empty.") file_names = [] for entry in file_pattern: file_names.extend(gfile.Glob(entry)) else: file_names = list(gfile.Glob(file_pattern)) if not file_names: raise ValueError("No files match %s." % file_patter...
131
131
439
23
107
uve/tensorflow
tensorflow/python/data/experimental/ops/readers.py
Python
SqlDatasetV2
SqlDatasetV2
946
991
946
947
f221dc7bf83919146db8780532a795b5c6d08e44
bigcode/the-stack
train
150c84e5589be08c4421c1ff
train
function
def stats(): lines = open(Path.proc_meminfo()).readlines() results = {} for key, value in mapping.items(): for line in lines: if line.startswith(key + ': '): results[value] = int(line.split()[1]) * 1024 return results
def stats():
lines = open(Path.proc_meminfo()).readlines() results = {} for key, value in mapping.items(): for line in lines: if line.startswith(key + ': '): results[value] = int(line.split()[1]) * 1024 return results
mapping = { 'MemFree': 'free', 'MemTotal': 'total', 'MemAvailable': 'available', 'Active': 'active', 'Cached': 'cached', 'SwapTotal': 'swap_total', 'SwapFree': 'swap_free' } def stats():
64
64
63
3
61
kallisti5/skep
stats/stats/memory.py
Python
stats
stats
13
20
13
13
0151206ebfecadf68945bc324f59019df0807920
bigcode/the-stack
train
67c9b3aaa36e0c2c48ca1cee
train
function
def preprocess_input(x): """Preprocesses a numpy array encoding a batch of images. Arguments: x: a 4D numpy array consists of RGB values within [0, 255]. Returns: Preprocessed array. """ return imagenet_utils.preprocess_input(x, mode='tf')
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images. Arguments: x: a 4D numpy array consists of RGB values within [0, 255]. Returns: Preprocessed array. """ return imagenet_utils.preprocess_input(x, mode='tf')
impl.keras.layers import MaxPooling2D from tensorflow.python.keras._impl.keras.models import Model from tensorflow.python.keras._impl.keras.utils.data_utils import get_file BASE_WEIGHT_URL = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.7/' def preprocess_input(x):
63
64
66
5
58
ryorda/tensorflow-viennacl
tensorflow/python/keras/_impl/keras/applications/inception_resnet_v2.py
Python
preprocess_input
preprocess_input
48
57
48
48
d472856eeb64748e07fda943c20d234d541249e6
bigcode/the-stack
train
fb192948ac86078d40e573b7
train
function
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'): """Adds a Inception-ResNet block. This function builds 3 types of Inception-ResNet blocks mentioned in the paper, controlled by the `block_type` argument (which is the block name used in the official TF-slim implementation): ...
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'):
"""Adds a Inception-ResNet block. This function builds 3 types of Inception-ResNet blocks mentioned in the paper, controlled by the `block_type` argument (which is the block name used in the official TF-slim implementation): - Inception-ResNet-A: `block_type='block35'` - Inception-ResNet-B: `block_...
`Conv2D`. padding: padding mode in `Conv2D`. activation: activation in `Conv2D`. use_bias: whether to use a bias in `Conv2D`. name: name of the ops; will become `name + '_ac'` for the activation and `name + '_bn'` for the batch norm layer. Returns: Output tensor after applyin...
256
256
976
19
236
ryorda/tensorflow-viennacl
tensorflow/python/keras/_impl/keras/applications/inception_resnet_v2.py
Python
inception_resnet_block
inception_resnet_block
102
183
102
102
4b3e1d1547a8280f8236d1768c14cdebb807ed35
bigcode/the-stack
train
ae35c575efa876faf6faea72
train
function
def conv2d_bn(x, filters, kernel_size, strides=1, padding='same', activation='relu', use_bias=False, name=None): """Utility function to apply conv + BN. Arguments: x: input tensor. filters: filters in `Con...
def conv2d_bn(x, filters, kernel_size, strides=1, padding='same', activation='relu', use_bias=False, name=None):
"""Utility function to apply conv + BN. Arguments: x: input tensor. filters: filters in `Conv2D`. kernel_size: kernel size as in `Conv2D`. strides: strides in `Conv2D`. padding: padding mode in `Conv2D`. activation: activation in `Conv2D`. use_bias: whether to use a bias i...
processes a numpy array encoding a batch of images. Arguments: x: a 4D numpy array consists of RGB values within [0, 255]. Returns: Preprocessed array. """ return imagenet_utils.preprocess_input(x, mode='tf') def conv2d_bn(x, filters, kernel_size, strides=...
96
96
322
38
58
ryorda/tensorflow-viennacl
tensorflow/python/keras/_impl/keras/applications/inception_resnet_v2.py
Python
conv2d_bn
conv2d_bn
60
99
60
67
9a4bd8a18e9f4e55d708b81167a0870b6fb1cfe4
bigcode/the-stack
train
305186fa500ddf905cdee504
train
function
def InceptionResNetV2(include_top=True, # pylint: disable=invalid-name weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the Inception-ResNet v2 architectu...
def InceptionResNetV2(include_top=True, # pylint: disable=invalid-name weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000):
"""Instantiates the Inception-ResNet v2 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `"image_data_format": "channels_last"` in your Keras config at `~/.keras/keras.json`. The model and the weights are compatible with T...
: raise ValueError('Unknown Inception-ResNet block type. ' 'Expects "block35", "block17" or "block8", ' 'but got: ' + str(block_type)) block_name = block_type + '_' + str(block_idx) channel_axis = 1 if K.image_data_format() == 'channels_first' else 3 mixed = Concaten...
256
256
2,170
46
209
ryorda/tensorflow-viennacl
tensorflow/python/keras/_impl/keras/applications/inception_resnet_v2.py
Python
InceptionResNetV2
InceptionResNetV2
186
369
186
191
0d2e6b49d3851b26441acbeb4bee92e1356eaad7
bigcode/the-stack
train
c9f45a3bb099dfd94cf042e1
train
class
class AwsHelper: session = None session_valid = False iot_client = None thing = None def __init__(self, args): profile = "default" if "aws-profile" in args: profile = args.aws_profile region = None if "aws-region" in args: region = args.aws_r...
class AwsHelper:
session = None session_valid = False iot_client = None thing = None def __init__(self, args): profile = "default" if "aws-profile" in args: profile = args.aws_profile region = None if "aws-region" in args: region = args.aws_region ac...
in self._staged_config: return self._staged_config[key].decode("UTF-8") elif key in self._running_config: return self._running_config[key].decode("UTF-8") else: return None def conf_get_all(self): assert self._running_config assert self._staged_c...
256
256
924
4
251
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
AwsHelper
AwsHelper
331
468
331
331
7b69a46400dbac243f1683779a9c57ff90c0a9be
bigcode/the-stack
train
8aaa55fcf29c8e212d4475fa
train
function
def main(): parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) # "Interactive mode" for asking about config details. parser.add_argument("-i", "--interactive", action="store_true") parser.add_argument("-v", "--verbose", action="store_true") # Default to stlink vid/pid if only one...
def main():
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) # "Interactive mode" for asking about config details. parser.add_argument("-i", "--interactive", action="store_true") parser.add_argument("-v", "--verbose", action="store_true") # Default to stlink vid/pid if only one is connecte...
"pem": None, }, ] AmazonTrustRepositoryUrl = "https://www.amazontrust.com/repository/" if not os.path.exists(".cache"): os.mkdir(".cache") for i in range(len(AmazonTrustRootCAs)): cert = AmazonTrustRootCAs[i] cacheFile = os.path.join(".cache", cert["label"] + ".pem") ...
256
256
856
3
252
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
main
main
673
782
673
673
e9cb056f5c46adcc193c459fdc97f8d123f27590
bigcode/the-stack
train
8fd943b479ffb1d5c0d47b33
train
function
def find_serial_port(usbVendorId=0x0483, usbProductId=0x374E): ports = serial.tools.list_ports.comports() matches = [] device = None for port in ports: attrs = dir(port) if ( "vid" in attrs and port.vid and "pid" in attrs and port.pid ...
def find_serial_port(usbVendorId=0x0483, usbProductId=0x374E):
ports = serial.tools.list_ports.comports() matches = [] device = None for port in ports: attrs = dir(port) if ( "vid" in attrs and port.vid and "pid" in attrs and port.pid and "device" in attrs and port.device ...
"] ) self.thing["certificatePem"] = bytes( self.thing["certificatePem"].replace("\\n", "\n"), "ascii" ) return self.thing.copy() def find_serial_port(usbVendorId=0x0483, usbProductId=0x374E):
64
64
200
23
41
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
find_serial_port
find_serial_port
471
496
471
471
b8bbf4e56883364be14b93d1df38647190d4e732
bigcode/the-stack
train
eefc1957c102f6f918335367
train
function
def get_unix_timestamp(): import time return int(time.time())
def get_unix_timestamp():
import time return int(time.time())
) if port.vid == usbVendorId and port.pid == usbProductId: matches.append(port.device) # default to an empty string if no match was found. if len(matches) > 0: device = matches[0] return device def get_unix_timestamp():
64
64
16
6
57
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
get_unix_timestamp
get_unix_timestamp
499
502
499
499
128371505a98f18ae78de9caef0e07d329f2ea96
bigcode/the-stack
train
0e4d4ad699ae92f15c8572ad
train
function
def validate_csr(csr_pem, pub_key_pem, thing_name): result = True pubkey = None csr = None try: pubkey = load_pem_public_key(pub_key_pem) except ValueError: result = False try: csr = x509.load_pem_x509_csr(csr_pem) except ValueError: result = False if re...
def validate_csr(csr_pem, pub_key_pem, thing_name):
result = True pubkey = None csr = None try: pubkey = load_pem_public_key(pub_key_pem) except ValueError: result = False try: csr = x509.load_pem_x509_csr(csr_pem) except ValueError: result = False if result: # Check that public key matches ...
R1) ): logging.error("Error: EC keys must of type secp256r1 or secp384r1.") result = False elif result: logging.error("Error: Public keys must be either RSA or EC type") result = False return result def validate_csr(csr_pem, pub_key_pem, thing_name):
79
79
266
17
61
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
validate_csr
validate_csr
541
577
541
541
c089b7aa7955c6edc0921e4337f76e60723f3829
bigcode/the-stack
train
0d634299ee8b8f6ee97d1dc4
train
function
def interactive_config(target): print( "Interactive configuration mode: Press return to use defaults (displayed in brackets)" ) cfg = target.conf_get_all() for key, value in cfg.items(): new_value = str(input("{}[{}]: ".format(key, value))) if len(new_value) > 0: targ...
def interactive_config(target):
print( "Interactive configuration mode: Press return to use defaults (displayed in brackets)" ) cfg = target.conf_get_all() for key, value in cfg.items(): new_value = str(input("{}[{}]: ".format(key, value))) if len(new_value) > 0: target.conf_set(key, new_value)
usbProductId: matches.append(port.device) # default to an empty string if no match was found. if len(matches) > 0: device = matches[0] return device def get_unix_timestamp(): import time return int(time.time()) def interactive_config(target):
64
64
79
5
59
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
interactive_config
interactive_config
505
513
505
505
996838f69abf660dd6be6f44452f69410758bb2d
bigcode/the-stack
train
bae870bc9b860e4a84179613
train
function
def get_amazon_rootca_certs(): AmazonTrustRootCAs = [ { "CN": "Amazon Root CA 1", "O": "Amazon", "label": "AmazonRootCA1", "pem": None, }, { "CN": "Amazon Root CA 2", "O": "Amazon", "label": "AmazonRootCA2", ...
def get_amazon_rootca_certs():
AmazonTrustRootCAs = [ { "CN": "Amazon Root CA 1", "O": "Amazon", "label": "AmazonRootCA1", "pem": None, }, { "CN": "Amazon Root CA 2", "O": "Amazon", "label": "AmazonRootCA2", "pem": None, ...
= attr.rfc4514_string() logging.debug("Parsed Cert Attribute: {}".format(rfc4514_str)) if not ("CN=" in rfc4514_str and attr.value == cert["CN"]): result = False for attr in x509Cert.subject.get_attributes_for_oid(NameOID.ORGANIZATION_NAME): rfc4514_str = at...
138
138
463
9
128
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
get_amazon_rootca_certs
get_amazon_rootca_certs
606
670
606
606
c419c012e89628dc8be90733e79aed9bdcc6c816
bigcode/the-stack
train
01c0a1f2acb46d9d4c532cc2
train
function
def validate_ca_certificate(cert): result = True try: x509Cert = x509.load_pem_x509_certificate(cert["pem"]) except ValueError: logging.error( "Failed to parse certificate: CN: {}, O: {}".format(cert["CN"], cert["O"]) ) result = False if result: for a...
def validate_ca_certificate(cert):
result = True try: x509Cert = x509.load_pem_x509_certificate(cert["pem"]) except ValueError: logging.error( "Failed to parse certificate: CN: {}, O: {}".format(cert["CN"], cert["O"]) ) result = False if result: for attr in x509Cert.subject.get_attribu...
logging.debug("Parsed CSR Attribute: {}".format(rfc4514_str)) if attr.value == thing_name: thingNameFound = True if not thingNameFound: logging.error("Error: Did not find thing name in CSR") result = False return result def validate_ca_certifi...
67
67
226
6
60
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
validate_ca_certificate
validate_ca_certificate
580
603
580
580
e27a5cceb085a62f1ad0f32f7d0873f9dedc87fa
bigcode/the-stack
train
2ce61b005ecb8efc168db4a6
train
class
class TargetDevice: _running_config = None _staged_config = None _error_bstr = (b"error", b"Error", b"ERROR", b"<ERR>") _timeout = 2.0 class ReadbackError(Exception): """Raised when the command readback received from the target does not match the command sent.""" pass class Re...
class TargetDevice:
_running_config = None _staged_config = None _error_bstr = (b"error", b"Error", b"ERROR", b"<ERR>") _timeout = 2.0 class ReadbackError(Exception): """Raised when the command readback received from the target does not match the command sent.""" pass class ResponseTimeout(Except...
# # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR P...
256
256
1,874
4
252
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
TargetDevice
TargetDevice
48
328
48
48
84af5f69648e3cea3bfbdcbad094ad66738e16ce
bigcode/the-stack
train
62c82d9aaf9a4305fc4a9de4
train
function
def validate_pubkey(pub_key): result = True key = None try: key = load_pem_public_key(pub_key) except ValueError: result = False if result and isinstance(key, rsa.RSAPublicKey): if key.key_size < 2048: logging.error("Error: RSA key size must be >= 2048 bits") ...
def validate_pubkey(pub_key):
result = True key = None try: key = load_pem_public_key(pub_key) except ValueError: result = False if result and isinstance(key, rsa.RSAPublicKey): if key.key_size < 2048: logging.error("Error: RSA key size must be >= 2048 bits") result = False el...
in brackets)" ) cfg = target.conf_get_all() for key, value in cfg.items(): new_value = str(input("{}[{}]: ".format(key, value))) if len(new_value) > 0: target.conf_set(key, new_value) def validate_pubkey(pub_key):
64
64
191
7
57
mfkiwl/lab-iot-reference-stm32u5
tools/provision.py
Python
validate_pubkey
validate_pubkey
516
538
516
516
6cc363b6b86d4717997a8b87d897ef40eefb07cc
bigcode/the-stack
train
fbc6a53f1aaa32dd3e14229d
train
function
def SoftRuleVioCorrectionDisallowed(vim, *args, **kwargs): '''The current DRS migration priority setting prevents generating a recommendation to correct the soft VM/Host affinity rules constraint violation for the VM so the violation will not be corrected.''' obj = vim.client.factory.create('{urn:vim25...
def SoftRuleVioCorrectionDisallowed(vim, *args, **kwargs):
'''The current DRS migration priority setting prevents generating a recommendation to correct the soft VM/Host affinity rules constraint violation for the VM so the violation will not be corrected.''' obj = vim.client.factory.create('{urn:vim25}SoftRuleVioCorrectionDisallowed') # do some validatio...
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def SoftRuleVioCorrectionDisallowed(vim, *args, **kwargs):
53
69
233
17
36
Infinidat/pyvisdk
pyvisdk/do/soft_rule_vio_correction_disallowed.py
Python
SoftRuleVioCorrectionDisallowed
SoftRuleVioCorrectionDisallowed
11
34
11
11
9e46cd75d6a8ae2336957c4ed2a422898b8b6060
bigcode/the-stack
train
7776198a2d4b3378d0e16dde
train
function
def predict_similarity_score(corpus: Corpus, name: str, model="german-uncased"): if model == "german-uncased": embedder = uncased_embedder else: embedder = multilingual_embedder for d in tqdm(corpus.documents): doc_embedding = np.mean(embedder.encode(d.text), axis=0) for s i...
def predict_similarity_score(corpus: Corpus, name: str, model="german-uncased"):
if model == "german-uncased": embedder = uncased_embedder else: embedder = multilingual_embedder for d in tqdm(corpus.documents): doc_embedding = np.mean(embedder.encode(d.text), axis=0) for s in d.gen_summaries: summary_embedding = np.mean(embedder.encode(s.text...
.get_word_embedding_dimension(), pooling_mode_mean_tokens=False, pooling_mode_cls_token=False, pooling_mode_max_tokens=True) uncased_embedder = SentenceTransformer(modules=[word_embedding_model, pooling_model]) def predict_simi...
64
64
131
21
43
fraunhofer-iais/hybrid_summarization_eval
src/konvens2020_summarization/predictors/sbert_predictor.py
Python
predict_similarity_score
predict_similarity_score
18
30
18
18
629e21ee83043079fa107cb6793a8cba66e07c29
bigcode/the-stack
train
4ed6c7e8d98381788e25ea83
train
class
class Inertia(SimpleBlock): """Inertia block with definitions for standard inertia sources. **The following parts of the objective function are created:** If :attr:`inertia_costs` are set by the user: .. math:: \sum_{(i,o)} \sum_t source_inertia(i, o, t) \cdot sources\_inertia(i,...
class Inertia(SimpleBlock):
"""Inertia block with definitions for standard inertia sources. **The following parts of the objective function are created:** If :attr:`inertia_costs` are set by the user: .. math:: \sum_{(i,o)} \sum_t source_inertia(i, o, t) \cdot sources\_inertia(i, o).moment_of_inertia(t) \cd...
## Copyright 2021 Henning Thiesen ## OpInMod is released under the open source MIT License, see ## https://github.com/hnnngt/OpInMod/blob/main/LICENSE """Creating sets, variables, constraints and parts of the objective function for Inertia objects. """ from pyomo.core.base.block import SimpleBlock class Inertia(Sim...
79
89
298
6
72
hnnngt/OpInMod
opinmod/blocks/inertia_inertia.py
Python
Inertia
Inertia
14
57
14
14
61981371b3446117a352e3637b81fcfe2e5982f2
bigcode/the-stack
train
3b8d071c8b2ee6b4df0aeed0
train
class
class _ScalaMutableWrapper: __slots__ = ("_ctor", "_data") def __init__(self, ji, o, template=None, ctor=None, data=None): if ctor is None: ctor = o.__class__ if data is None: if template: data = type(template)(template) else: data = ji.getSomeKindOfImmutableObjectTemplate(o.__class__) f...
class _ScalaMutableWrapper:
__slots__ = ("_ctor", "_data") def __init__(self, ji, o, template=None, ctor=None, data=None): if ctor is None: ctor = o.__class__ if data is None: if template: data = type(template)(template) else: data = ji.getSomeKindOfImmutableObjectTemplate(o.__class__) for p in data.keys(): v =...
import typing import re from JAbs import SelectedJVMInitializer, ClassPathT, ClassesImportSpecT from collections import OrderedDict, defaultdict import warnings import sys decodeScalaSignature = None class _ScalaMutableWrapper:
50
72
242
6
43
kaitaiStructCompile/ScalaJVMInitializer.py
ScalaJVMInitializer/__init__.py
Python
_ScalaMutableWrapper
_ScalaMutableWrapper
11
41
11
11
19dec61df631d3207f5ba1ec565dea5ab1561cc1
bigcode/the-stack
train
711cdf50b5cc0994f0902a47
train
class
class ScalaMutableWrapper(_ScalaMutableWrapper): __slots__ = () def _revertIter(self): return self._data.values() def _revert(self): return self._ctor(*tuple(self._revertIter_())) def __getattr__(self, k): return self._data[k] def __setattr__(self, k, v): self._data[k] = v def __dir__(self): return...
class ScalaMutableWrapper(_ScalaMutableWrapper):
__slots__ = () def _revertIter(self): return self._data.values() def _revert(self): return self._ctor(*tuple(self._revertIter_())) def __getattr__(self, k): return self._data[k] def __setattr__(self, k, v): self._data[k] = v def __dir__(self): return self._data.keys()
def _revert(self): return self._ctor(list(self._revertIter())) def __repr__(self): return self.__class__.__name__ + "<" + self._ctor.__name__ + ">(" + repr(self._data) + ")" class ScalaMutableWrapper(_ScalaMutableWrapper):
64
64
98
9
54
kaitaiStructCompile/ScalaJVMInitializer.py
ScalaJVMInitializer/__init__.py
Python
ScalaMutableWrapper
ScalaMutableWrapper
44
60
44
44
bbc947af3fe234657c27249594c7009af557a41a
bigcode/the-stack
train
0b8929f1887d2a69ac39cb23
train
class
class ScalaCollectionMutableWrapper(_ScalaMutableWrapper): __slots__ = () def __init__(self, ji, o, template=None, ctor=None, data=None): super().__init__(ji, o, ctor=ji.scalaSeq, data=[ji.scalaWrapSomeKindOfImmutableObject(el) for el in ji.JavaConverters.asJavaCollection(o)]) def __getitem__(self, k): return...
class ScalaCollectionMutableWrapper(_ScalaMutableWrapper):
__slots__ = () def __init__(self, ji, o, template=None, ctor=None, data=None): super().__init__(ji, o, ctor=ji.scalaSeq, data=[ji.scalaWrapSomeKindOfImmutableObject(el) for el in ji.JavaConverters.asJavaCollection(o)]) def __getitem__(self, k): return self._data[k] def __setitem__(self, k, v): self._data[...
revertIter_())) def __getattr__(self, k): return self._data[k] def __setattr__(self, k, v): self._data[k] = v def __dir__(self): return self._data.keys() class ScalaCollectionMutableWrapper(_ScalaMutableWrapper):
64
64
141
10
54
kaitaiStructCompile/ScalaJVMInitializer.py
ScalaJVMInitializer/__init__.py
Python
ScalaCollectionMutableWrapper
ScalaCollectionMutableWrapper
64
80
64
64
5101ae33eae6b498f68aa39c713a4cb61b6d78f9
bigcode/the-stack
train
4fd881f9d56625c086182e2c
train
class
class ScalaJVMInitializer: __slots__ = ("ji", "scalaVersion") def __init__(self, classPathz: ClassPathT, classes2import: ClassesImportSpecT) -> None: self.__class__.ji.__set__(self, SelectedJVMInitializer(classPathz, classes2import)) self.loadScala() def __getattr__(self, k): return getattr(self.ji, k) def ...
class ScalaJVMInitializer:
__slots__ = ("ji", "scalaVersion") def __init__(self, classPathz: ClassPathT, classes2import: ClassesImportSpecT) -> None: self.__class__.ji.__set__(self, SelectedJVMInitializer(classPathz, classes2import)) self.loadScala() def __getattr__(self, k): return getattr(self.ji, k) def __setattr__(self, k, v): ...
>(" + repr(self._data) + ")" class ScalaMutableWrapper(_ScalaMutableWrapper): __slots__ = () def _revertIter(self): return self._data.values() def _revert(self): return self._ctor(*tuple(self._revertIter_())) def __getattr__(self, k): return self._data[k] def __setattr__(self, k, v): self._data[k] = ...
255
256
1,251
6
249
kaitaiStructCompile/ScalaJVMInitializer.py
ScalaJVMInitializer/__init__.py
Python
ScalaJVMInitializer
ScalaJVMInitializer
85
228
85
85
a054eecb03eef3755b90f5d8444746b53d340588
bigcode/the-stack
train
b24762aed4edb0de20746066
train
function
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} ...
def render(pieces, style):
"""Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "d...
' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, s...
78
78
260
7
70
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render
render
445
474
445
445
930892a99868150d540c69d8477df76e6496af2a
bigcode/the-stack
train
7c5491233a73d32c50d44b83
train
function
def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[...
def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["cl...
"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces):
64
64
216
9
54
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render_pep440_post
render_pep440_post
356
380
356
356
9e2eecbd5bfd1b01f575f39434f71060139bf1cb
bigcode/the-stack
train
cd30da7d34dbe4d50d93f3e1
train
function
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on w...
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
"""Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, ...
the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, ...
87
87
293
22
64
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
run_command
run_command
70
104
70
71
0bba8431e29e33877c8cce5511404052c7219fc2
bigcode/the-stack
train
77df45c850cd695832b20e57
train
function
def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versio...
def get_config():
"""Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "Mo...
_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config():
63
64
101
4
59
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
get_config
get_config
37
48
37
37
188efc774a6bee730d9948b6517d238a1ebbb2b1
bigcode/the-stack
train
bc9002593bdfc214e5d175c8
train
function
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] ...
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["di...
pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces):
64
64
133
9
54
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render_git_describe_long
render_git_describe_long
425
442
425
425
5e4bff692adb192739763d5a533f5bcc0732f3f4
bigcode/the-stack
train
90af901cb4c0e83b39ec10da
train
function
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an ap...
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] ...
!= 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose):
64
64
204
13
50
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
versions_from_parentdir
versions_from_parentdir
107
129
107
107
43e05a663fbea3783a2c67b82fd35bad9a9ef28f
bigcode/the-stack
train
bab0bbdce6088bae8b4abd1d
train
function
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exce...
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0....
rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces):
64
64
104
9
54
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render_pep440_pre
render_pep440_pre
340
353
340
340
c6c4ff64dd83fe1cefa9d0205d5bfcf382058796
bigcode/the-stack
train
cc32adcb85101bb3485f82eb
train
function
@register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been ...
@register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if ...
)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag...
256
256
875
34
222
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
git_pieces_from_vcs
git_pieces_from_vcs
216
305
216
217
7e492a17adf1befe9c93b7056873cc07a673d681
bigcode/the-stack
train
76a00f2709f13f3102b12f9b
train
function
@register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a r...
@register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs):
"""Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} ...
os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfi...
77
77
259
20
57
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
git_get_keywords
git_get_keywords
132
158
132
133
04b5a6d19ca3d22d0e7e9a65df90187d2ebfde59
bigcode/the-stack
train
e049cc3b594bfef6cd47cd94
train
function
def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHE...
def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pi...
).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces):
63
64
213
8
55
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render_pep440
render_pep440
315
337
315
315
68d7ccd160ed451a6dc4fdbd8fe09be136102e6e
bigcode/the-stack
train
00581fe09fed52eb85efb594
train
function
def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keyword...
def get_keywords():
"""Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refname...
the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords():
64
64
131
4
59
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
get_keywords
get_keywords
20
30
20
20
469718b2e0436724ddd20fba9e7cbdc15bc48baa
bigcode/the-stack
train
6d3018023db572616a8acc39
train
function
def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered +=...
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"],...
pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces):
64
64
129
8
55
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render_git_describe
render_git_describe
405
422
405
405
223b07609e73d4d8f3a7e7f56bac470548fcc640
bigcode/the-stack
train
21dd44cc17b138ae5a5a70a7
train
function
@register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%...
@register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands...
we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: ...
214
214
714
24
189
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
git_versions_from_keywords
git_versions_from_keywords
161
213
161
162
258bec4042f67b04a452ff5b0dab5edb6266331e
bigcode/the-stack
train
26e31aaf615e8f9dd89e9ee0
train
class
class VersioneerConfig: """Container for Versioneer configuration parameters."""
class VersioneerConfig:
"""Container for Versioneer configuration parameters."""
(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig:
64
64
14
5
58
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
VersioneerConfig
VersioneerConfig
33
34
33
33
f68b42475e4e512eb76a6e114aeca1e46ffc7801
bigcode/the-stack
train
3bd2a242e267c4d575f3624f
train
function
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which #...
def get_versions():
"""Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only us...
= render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": p...
108
109
366
4
104
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
get_versions
get_versions
477
520
477
477
b78ae74a11925f2c0fbd22dfabbdc7d52b417187
bigcode/the-stack
train
0d5cf8af6f8085e7ec733ce5
train
class
class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario."""
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "MolBuilder/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception):
64
64
21
6
57
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
NotThisMethod
NotThisMethod
51
52
51
51
e079db8a1cef60e672393bd70abd3dc5c2787e10
bigcode/the-stack
train
b31bf3dedbfeecca6df588e7
train
function
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+"
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+"
= run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces):
64
64
43
7
56
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
plus_or_dot
plus_or_dot
308
312
308
308
e66ee6ec1a8d4f40272fa193cbd32446fc176795
bigcode/the-stack
train
d6bf1f8966a0189393fc8ccb
train
function
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pie...
def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if ...
pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces):
64
64
145
9
54
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
render_pep440_old
render_pep440_old
383
402
383
383
a62a9f8f75c0be14c98316b48d886e021a1c5f2b
bigcode/the-stack
train
341b544089f71c2abaa18c6f
train
function
def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return ...
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate
MolBuilder/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator
63
64
87
14
49
KirillShmilovich/MolBuilder
MolBuilder/_version.py
Python
register_vcs_handler
register_vcs_handler
59
67
59
59
ed9726848b45d214b93361a4ec9112702345e96c
bigcode/the-stack
train
2496291fe335e1c07aa9c197
train
class
class Box(object): """ A box in a floor packing problem. """ ASPECT_RATIO = 5.0 def __init__(self, min_area): self.min_area = min_area self.height = Variable() self.width = Variable() self.x = Variable() self.y = Variable() @property def position(self): ...
class Box(object):
""" A box in a floor packing problem. """ ASPECT_RATIO = 5.0 def __init__(self, min_area): self.min_area = min_area self.height = Variable() self.width = Variable() self.x = Variable() self.y = Variable() @property def position(self): return (round(se...
from cvxpy import * import pylab import math # Based on http://cvxopt.org/examples/book/floorplan.html class Box(object):
33
64
181
4
28
quantopian/cvxpy
examples/floor_packing.py
Python
Box
Box
6
38
6
6
32fe9f0b2100243fd9cb8a7bf4fa0bc9f96f04ff
bigcode/the-stack
train
ba9963721f70ad3fac71be47
train
class
class FloorPlan(object): """ A minimum perimeter floor plan. """ MARGIN = 1.0 ASPECT_RATIO = 5.0 def __init__(self, boxes): self.boxes = boxes self.height = Variable() self.width = Variable() self.horizontal_orderings = [] self.vertical_orderings = [] @proper...
class FloorPlan(object):
""" A minimum perimeter floor plan. """ MARGIN = 1.0 ASPECT_RATIO = 5.0 def __init__(self, boxes): self.boxes = boxes self.height = Variable() self.width = Variable() self.horizontal_orderings = [] self.vertical_orderings = [] @property def size(self): ...
problem. """ ASPECT_RATIO = 5.0 def __init__(self, min_area): self.min_area = min_area self.height = Variable() self.width = Variable() self.x = Variable() self.y = Variable() @property def position(self): return (round(self.x.value,2), round(self.y.valu...
174
174
580
5
168
quantopian/cvxpy
examples/floor_packing.py
Python
FloorPlan
FloorPlan
40
110
40
40
853daca3fafb39c0f5b2222c43e5a308b9c0b4a1
bigcode/the-stack
train
5ef077eb187dfa0b1d75ab28
train
class
class restartOssRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'OssAdmin', '2014-03-26', 'restartOss') def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_ResourceOwnerAccount(self): retur...
class restartOssRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'OssAdmin', '2014-03-26', 'restartOss') def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_ResourceOwnerAccount(self): return self.get_query_params().get('Resourc...
in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest cla...
75
75
251
9
65
DataDog/aliyun-openapi-python-sdk
aliyun-python-sdk-ossadmin/aliyunsdkossadmin/request/v20140326/restartOssRequest.py
Python
restartOssRequest
restartOssRequest
21
54
21
22
44a8cb2261c9b95bf373e2e76ac5abeff3588033
bigcode/the-stack
train
8f58020b4641999f52eb2e55
train
class
class BDBody(BulletRigidBodyNode): def __init__(self, objinit, cdtype="triangle", mass=.3, restitution=0, allowdeactivation=False, allowccd=True, friction=.2, dynamic=True, name="rbd"): """ :param objinit: could be itself (copy), or an instance of collision model :param type...
class BDBody(BulletRigidBodyNode):
def __init__(self, objinit, cdtype="triangle", mass=.3, restitution=0, allowdeactivation=False, allowccd=True, friction=.2, dynamic=True, name="rbd"): """ :param objinit: could be itself (copy), or an instance of collision model :param type: triangle or convex :param...
from panda3d.bullet import BulletRigidBodyNode from panda3d.bullet import BulletTriangleMesh from panda3d.bullet import BulletTriangleMeshShape from panda3d.bullet import BulletConvexHullShape from panda3d.core import TransformState, Vec3, GeomVertexRewriter import copy import modeling.geometricmodel as gm import basis...
101
256
1,405
10
90
Photon26/wrs-main-210414
modeling/dynamics/bullet/bdbody.py
Python
BDBody
BDBody
12
142
12
12
3ee7af9f23b8294c632156c6ce8256697edd3249
bigcode/the-stack
train
7cf8341c0c0c2ab24f04c52f
train
function
def dmp_fateman_poly_F_3(n, K): """Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ u = dup_from_raw_dict({n + 1: K.one}, K) for i in range(0, n - 1): u = dmp_add_term([u], dmp_one(i, K), n + 1, i + 1, K) v = dmp_add_term(u, dmp_ground(K(2), n - 2), 0, n, K) f = dmp_sqr( ...
def dmp_fateman_poly_F_3(n, K):
"""Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ u = dup_from_raw_dict({n + 1: K.one}, K) for i in range(0, n - 1): u = dmp_add_term([u], dmp_one(i, K), n + 1, i + 1, K) v = dmp_add_term(u, dmp_ground(K(2), n - 2), 0, n, K) f = dmp_sqr( dmp_add_term([dmp_neg(v, n - 1...
+ u + 1)**2, *Y) F = Poly((y_0**(n + 1) - u - 2)**2, *Y) G = Poly((y_0**(n + 1) + u + 2)**2, *Y) return H*F, H*G, H def dmp_fateman_poly_F_3(n, K):
89
89
299
14
74
clyring/sympy
sympy/polys/specialpolys.py
Python
dmp_fateman_poly_F_3
dmp_fateman_poly_F_3
274
291
274
274
ec19c0ed1cc820da2453f0f1ff231ed3feca2b58
bigcode/the-stack
train
b2eef38fff61fce4a51f8860
train
function
@public def cyclotomic_poly(n, x=None, polys=False): """Generates cyclotomic polynomial of order `n` in `x`. Parameters ---------- n : int `n` decides the order of polynomial x : optional polys : bool, optional ``polys=True`` returns an expression, otherwise (default) re...
@public def cyclotomic_poly(n, x=None, polys=False):
"""Generates cyclotomic polynomial of order `n` in `x`. Parameters ---------- n : int `n` decides the order of polynomial x : optional polys : bool, optional ``polys=True`` returns an expression, otherwise (default) returns an expression. """ if n <= 0: r...
elif n == 3: ex = x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576 return PurePoly(ex, x) if polys else ex @public def cyclotomic_poly(n, x=None, polys=False):
64
64
177
16
47
clyring/sympy
sympy/polys/specialpolys.py
Python
cyclotomic_poly
cyclotomic_poly
77
101
77
78
1403b67ea44f325ad958389f41750f1cd485d187
bigcode/the-stack
train
7c900b9c6819c8ffb47ce327
train
function
def fateman_poly_F_3(n): """Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0 = Y[0] u = Add(*[y**(n + 1) for y in Y[1:]]) H = Poly((y_0**(n + 1) + u + 1)**2, *Y) F = Poly((y_0**(n + 1) - u - 2)**2, *Y) G = Poly((y_0**(n + 1...
def fateman_poly_F_3(n):
"""Fateman's GCD benchmark: sparse inputs (deg f ~ vars f) """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0 = Y[0] u = Add(*[y**(n + 1) for y in Y[1:]]) H = Poly((y_0**(n + 1) + u + 1)**2, *Y) F = Poly((y_0**(n + 1) - u - 2)**2, *Y) G = Poly((y_0**(n + 1) + u + 2)**2, *Y) r...
), 0, n, K) h = dmp_sqr([dmp_one(m, K), v], n, K) return dmp_mul(f, h, n, K), dmp_mul(g, h, n, K), h def fateman_poly_F_3(n):
64
64
170
9
54
clyring/sympy
sympy/polys/specialpolys.py
Python
fateman_poly_F_3
fateman_poly_F_3
258
271
258
258
b959a0b8d203d73ee2148ccd98e1ec0ed90cc242
bigcode/the-stack
train
0583c4776091ec8ec6ca1bd7
train
function
def w_polys(): return _w_1(), _w_2()
def w_polys():
return _w_1(), _w_2()
2*y**3 + 48*x**2 - 12*y**3 def f_polys(): return _f_0(), _f_1(), _f_2(), _f_3(), _f_4(), _f_5(), _f_6() def w_polys():
64
64
17
5
59
clyring/sympy
sympy/polys/specialpolys.py
Python
w_polys
w_polys
336
337
336
336
a2868c1a4d3bf0f254cd53ec4d0ec25cc93218d7
bigcode/the-stack
train
d03b9afdb6f3fd6b4721b57b
train
function
def dmp_fateman_poly_F_2(n, K): """Fateman's GCD benchmark: linearly dense quartic inputs """ u = [K(1), K(0)] for i in range(n - 1): u = [dmp_one(i, K), u] m = n - 1 v = dmp_add_term(u, dmp_ground(K(2), m - 1), 0, n, K) f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K) g = dm...
def dmp_fateman_poly_F_2(n, K):
"""Fateman's GCD benchmark: linearly dense quartic inputs """ u = [K(1), K(0)] for i in range(n - 1): u = [dmp_one(i, K), u] m = n - 1 v = dmp_add_term(u, dmp_ground(K(2), m - 1), 0, n, K) f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K) g = dmp_sqr([dmp_one(m, K), v], n, K) ...
Y) F = Poly((y_0 - u - 2)**2, *Y) G = Poly((y_0 + u + 2)**2, *Y) return H*F, H*G, H def dmp_fateman_poly_F_2(n, K):
66
66
223
14
51
clyring/sympy
sympy/polys/specialpolys.py
Python
dmp_fateman_poly_F_2
dmp_fateman_poly_F_2
237
255
237
237
40e8bdc9e2c514eab747352da3c9aef1dbac1f6c
bigcode/the-stack
train
cda1d3831e3e95d1fd955b6b
train
function
def fateman_poly_F_1(n): """Fateman's GCD benchmark: trivial GCD """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0, y_1 = Y[0], Y[1] u = y_0 + Add(*[y for y in Y[1:]]) v = y_0**2 + Add(*[y**2 for y in Y[1:]]) F = ((u + 1)*(u + 2)).as_poly(*Y) G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 -...
def fateman_poly_F_1(n):
"""Fateman's GCD benchmark: trivial GCD """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0, y_1 = Y[0], Y[1] u = y_0 + Add(*[y for y in Y[1:]]) v = y_0**2 + Add(*[y**2 for y in Y[1:]]) F = ((u + 1)*(u + 2)).as_poly(*Y) G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 - 1)).as_poly(*Y) H =...
[i]) denom = Mul(*[(X[i] - X[j]) for j in range(n) if i != j]) coeffs.append(numer/denom) return Add(*[coeff*y for coeff, y in zip(coeffs, Y)]) def fateman_poly_F_1(n):
63
64
173
9
54
clyring/sympy
sympy/polys/specialpolys.py
Python
fateman_poly_F_1
fateman_poly_F_1
174
188
174
174
f8b920c6cf0768117579261265438a6d26db739d
bigcode/the-stack
train
7524558a2cde7d7492712cf0
train
function
@public def interpolating_poly(n, x, X='x', Y='y'): """Construct Lagrange interpolating polynomial for ``n`` data points. """ if isinstance(X, str): X = symbols("%s:%s" % (X, n)) if isinstance(Y, str): Y = symbols("%s:%s" % (Y, n)) coeffs = [] numert = Mul(*[(x - u) for u in X]) ...
@public def interpolating_poly(n, x, X='x', Y='y'):
"""Construct Lagrange interpolating polynomial for ``n`` data points. """ if isinstance(X, str): X = symbols("%s:%s" % (X, n)) if isinstance(Y, str): Y = symbols("%s:%s" % (Y, n)) coeffs = [] numert = Mul(*[(x - u) for u in X]) for i in range(n): numer = numert/(x - X[...
expression, otherwise (default) returns an expression. """ poly = Poly(dup_random(n, inf, sup, domain), x, domain=domain) return poly if polys else poly.as_expr() @public def interpolating_poly(n, x, X='x', Y='y'):
64
64
171
19
45
clyring/sympy
sympy/polys/specialpolys.py
Python
interpolating_poly
interpolating_poly
154
171
154
155
29bbf4111010826110d65c21021564703914c96b
bigcode/the-stack
train
2b4279180c9dae7beed8407c
train
function
def dmp_fateman_poly_F_1(n, K): """Fateman's GCD benchmark: trivial GCD """ u = [K(1), K(0)] for i in range(n): u = [dmp_one(i, K), u] v = [K(1), K(0), K(0)] for i in range(0, n): v = [dmp_one(i, K), dmp_zero(i), v] m = n - 1 U = dmp_add_term(u, dmp_ground(K(1), m), 0, n...
def dmp_fateman_poly_F_1(n, K):
"""Fateman's GCD benchmark: trivial GCD """ u = [K(1), K(0)] for i in range(n): u = [dmp_one(i, K), u] v = [K(1), K(0), K(0)] for i in range(0, n): v = [dmp_one(i, K), dmp_zero(i), v] m = n - 1 U = dmp_add_term(u, dmp_ground(K(1), m), 0, n, K) V = dmp_add_term(u, dmp...
((u + 1)*(u + 2)).as_poly(*Y) G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 - 1)).as_poly(*Y) H = Poly(1, *Y) return F, G, H def dmp_fateman_poly_F_1(n, K):
82
82
276
14
67
clyring/sympy
sympy/polys/specialpolys.py
Python
dmp_fateman_poly_F_1
dmp_fateman_poly_F_1
191
218
191
191
3e8d2d6e6b5c07abbaa1d479ff7dc40d790fd5ef
bigcode/the-stack
train
ca163e1855e01615fe6dcdc1
train
function
def _f_0(): R, x, y, z = ring("x,y,z", ZZ) return x**2*y*z**2 + 2*x**2*y*z + 3*x**2*y + 2*x**2 + 3*x + 4*y**2*z**2 + 5*y**2*z + 6*y**2 + y*z**2 + 2*y*z + y + 1
def _f_0():
R, x, y, z = ring("x,y,z", ZZ) return x**2*y*z**2 + 2*x**2*y*z + 3*x**2*y + 2*x**2 + 3*x + 4*y**2*z**2 + 5*y**2*z + 6*y**2 + y*z**2 + 2*y*z + y + 1
, n, K), n, K) return dmp_mul(f, h, n, K), dmp_mul(g, h, n, K), h # A few useful polynomials from Wang's paper ('78). from sympy.polys.rings import ring def _f_0():
64
64
95
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_0
_f_0
297
299
297
297
886a0c8402ed4ce9d6fc329f97f29e4add737ca5
bigcode/the-stack
train
124f26a8508557dfe74696bd
train
function
@public def symmetric_poly(n, *gens, **args): """Generates symmetric polynomial of order `n`. Returns a Poly object when ``polys=True``, otherwise (default) returns an expression. """ # TODO: use an explicit keyword argument when Python 2 support is dropped gens = _analyze_gens(gens) if n ...
@public def symmetric_poly(n, *gens, **args):
"""Generates symmetric polynomial of order `n`. Returns a Poly object when ``polys=True``, otherwise (default) returns an expression. """ # TODO: use an explicit keyword argument when Python 2 support is dropped gens = _analyze_gens(gens) if n < 0 or n > len(gens) or not gens: rais...
omic_poly(int(n), ZZ), ZZ) if x is not None: poly = Poly.new(poly, x) else: poly = PurePoly.new(poly, Dummy('x')) return poly if polys else poly.as_expr() @public def symmetric_poly(n, *gens, **args):
64
64
178
14
50
clyring/sympy
sympy/polys/specialpolys.py
Python
symmetric_poly
symmetric_poly
104
124
104
105
b3556551e729bab52110fcb5d6287dfdc9ea66c1
bigcode/the-stack
train
d9f3c4d817d159a62c24e0aa
train
function
def _f_4(): R, x, y, z = ring("x,y,z", ZZ) return -x**9*y**8*z - x**8*y**5*z**3 - x**7*y**12*z**2 - 5*x**7*y**8 - x**6*y**9*z**4 + x**6*y**7*z**3 + 3*x**6*y**7*z - 5*x**6*y**5*z**2 - x**6*y**4*z**3 + x**5*y**4*z**5 + 3*x**5*y**4*z**3 - x**5*y*z**5 + x**4*y**11*z**4 + 3*x**4*y**11*z**2 - x**4*y**8*z**4 + 5*x**4*...
def _f_4():
R, x, y, z = ring("x,y,z", ZZ) return -x**9*y**8*z - x**8*y**5*z**3 - x**7*y**12*z**2 - 5*x**7*y**8 - x**6*y**9*z**4 + x**6*y**7*z**3 + 3*x**6*y**7*z - 5*x**6*y**5*z**2 - x**6*y**4*z**3 + x**5*y**4*z**5 + 3*x**5*y**4*z**3 - x**5*y*z**5 + x**4*y**11*z**4 + 3*x**4*y**11*z**2 - x**4*y**8*z**4 + 5*x**4*y**7*z**2 + ...
", ZZ) return x**5*y**2 + x**4*z**4 + x**4 + x**3*y**3*z + x**3*z + x**2*y**4 + x**2*y**3*z**3 + x**2*y*z**5 + x**2*y*z + x*y**2*z**4 + x*y**2 + x*y*z**7 + x*y*z**3 + x*y*z**2 + y**2*z + y*z**4 def _f_4():
114
114
380
6
107
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_4
_f_4
313
315
313
313
02865de91635b562b826adbbd7af0d8b7b1374b6
bigcode/the-stack
train
7a0fe477e7b9cb9a999ec50e
train
function
@public def swinnerton_dyer_poly(n, x=None, polys=False): """Generates n-th Swinnerton-Dyer polynomial in `x`. Parameters ---------- n : int `n` decides the order of polynomial x : optional polys : bool, optional ``polys=True`` returns an expression, otherwise (default) ...
@public def swinnerton_dyer_poly(n, x=None, polys=False):
"""Generates n-th Swinnerton-Dyer polynomial in `x`. Parameters ---------- n : int `n` decides the order of polynomial x : optional polys : bool, optional ``polys=True`` returns an expression, otherwise (default) returns an expression. """ from .numberfields impo...
mp_neg, dmp_mul, dmp_sqr ) from sympy.polys.factortools import ( dup_zz_cyclotomic_poly ) from sympy.polys.domains import ZZ from sympy.ntheory import nextprime from sympy.utilities import subsets, public from sympy.core.compatibility import range @public def swinnerton_dyer_poly(n, x=None, polys=False):
90
90
303
18
71
clyring/sympy
sympy/polys/specialpolys.py
Python
swinnerton_dyer_poly
swinnerton_dyer_poly
36
74
36
37
db944f0569d1d02970bb38227e3feac08c24ac4e
bigcode/the-stack
train
04e784ab8a3e05bc7f0feefc
train
function
def f_polys(): return _f_0(), _f_1(), _f_2(), _f_3(), _f_4(), _f_5(), _f_6()
def f_polys():
return _f_0(), _f_1(), _f_2(), _f_3(), _f_4(), _f_5(), _f_6()
**4*y**3 + 292*x**4*y**2 - x**3*y**6 + 3*x**3*y**3 - x**2*y**5 + 12*x**2*y**3 + 48*x**2 - 12*y**3 def f_polys():
64
64
42
5
58
clyring/sympy
sympy/polys/specialpolys.py
Python
f_polys
f_polys
333
334
333
333
90f80df35556fbd3126b70c88fca32a277ae691d
bigcode/the-stack
train
12f39250118750a8a9b86222
train
function
def _f_1(): R, x, y, z = ring("x,y,z", ZZ) return x**3*y*z + x**2*y**2*z**2 + x**2*y**2 + 20*x**2*y*z + 30*x**2*y + x**2*z**2 + 10*x**2*z + x*y**3*z + 30*x*y**2*z + 20*x*y**2 + x*y*z**3 + 10*x*y*z**2 + x*y*z + 610*x*y + 20*x*z**2 + 230*x*z + 300*x + y**2*z**2 + 10*y**2*z + 30*y*z**2 + 320*y*z + 200*y + 600*z + ...
def _f_1():
R, x, y, z = ring("x,y,z", ZZ) return x**3*y*z + x**2*y**2*z**2 + x**2*y**2 + 20*x**2*y*z + 30*x**2*y + x**2*z**2 + 10*x**2*z + x*y**3*z + 30*x*y**2*z + 20*x*y**2 + x*y*z**3 + 10*x*y*z**2 + x*y*z + 610*x*y + 20*x*z**2 + 230*x*z + 300*x + y**2*z**2 + 10*y**2*z + 30*y*z**2 + 320*y*z + 200*y + 600*z + 6000
2*y*z + 3*x**2*y + 2*x**2 + 3*x + 4*y**2*z**2 + 5*y**2*z + 6*y**2 + y*z**2 + 2*y*z + y + 1 def _f_1():
64
64
175
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_1
_f_1
301
303
301
301
5e805657906e4c992e2aa40448542175001fb1f7
bigcode/the-stack
train
534ae77cee9e5bf07bc910d2
train
function
def _f_5(): R, x, y, z = ring("x,y,z", ZZ) return -x**3 - 3*x**2*y + 3*x**2*z - 3*x*y**2 + 6*x*y*z - 3*x*z**2 - y**3 + 3*y**2*z - 3*y*z**2 + z**3
def _f_5():
R, x, y, z = ring("x,y,z", ZZ) return -x**3 - 3*x**2*y + 3*x**2*z - 3*x*y**2 + 6*x*y*z - 3*x*z**2 - y**3 + 3*y**2*z - 3*y*z**2 + z**3
3*x*y**7*z**4 + 5*x*y**3*z**4 + 15*x*y**3*z**2 + y**4*z**8 + 3*y**4*z**6 + 5*z**6 + 15*z**4 def _f_5():
64
64
86
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_5
_f_5
317
319
317
317
8291dbede8495de28fafb398c374f5d0f26fb5a8
bigcode/the-stack
train
b30ce499cb6974eef4c18612
train
function
@public def random_poly(x, n, inf, sup, domain=ZZ, polys=False): """Generates a polynomial of degree ``n`` with coefficients in ``[inf, sup]``. Parameters ---------- x `x` is the independent term of polynomial n : int `n` decides the order of polynomial inf Lower lim...
@public def random_poly(x, n, inf, sup, domain=ZZ, polys=False):
"""Generates a polynomial of degree ``n`` with coefficients in ``[inf, sup]``. Parameters ---------- x `x` is the independent term of polynomial n : int `n` decides the order of polynomial inf Lower limit of range in which coefficients lie sup Upper limit...
(*[Mul(*s) for s in subsets(gens, int(n))]) if not args.get('polys', False): return poly else: return Poly(poly, *gens) @public def random_poly(x, n, inf, sup, domain=ZZ, polys=False):
64
64
190
21
43
clyring/sympy
sympy/polys/specialpolys.py
Python
random_poly
random_poly
127
151
127
128
f895702872e164c003fe5a08ddd273db75987edc
bigcode/the-stack
train
7c7fa5101f445304e78f6b98
train
function
def _w_1(): R, x, y, z = ring("x,y,z", ZZ) return 4*x**6*y**4*z**2 + 4*x**6*y**3*z**3 - 4*x**6*y**2*z**4 - 4*x**6*y*z**5 + x**5*y**4*z**3 + 12*x**5*y**3*z - x**5*y**2*z**5 + 12*x**5*y**2*z**2 - 12*x**5*y*z**3 - 12*x**5*z**4 + 8*x**4*y**4 + 6*x**4*y**3*z**2 + 8*x**4*y**3*z - 4*x**4*y**2*z**4 + 4*x**4*y**2*z**3 -...
def _w_1():
R, x, y, z = ring("x,y,z", ZZ) return 4*x**6*y**4*z**2 + 4*x**6*y**3*z**3 - 4*x**6*y**2*z**4 - 4*x**6*y*z**5 + x**5*y**4*z**3 + 12*x**5*y**3*z - x**5*y**2*z**5 + 12*x**5*y**2*z**2 - 12*x**5*y*z**3 - 12*x**5*z**4 + 8*x**4*y**4 + 6*x**4*y**3*z**2 + 8*x**4*y**3*z - 4*x**4*y**2*z**4 + 4*x**4*y**2*z**3 - 8*x**4*y**2...
45*x**3*z**3*t**2 - 45*x**3*t**2 - 423*x*y**4 - 47*x*y**3 + 141*x*y*z**3 + 94*x*y*z*t - 9*y**3*z**3*t**2 + 9*y**3*t**2 - y**2*z**3*t**2 + y**2*t**2 + 3*z**6*t**2 + 2*z**4*t**3 - 3*z**3*t**2 - 2*z*t**3 def _w_1():
127
127
424
6
120
clyring/sympy
sympy/polys/specialpolys.py
Python
_w_1
_w_1
325
327
325
325
2b997667f141cd1c34eb4af69dbf587628b3c0c1
bigcode/the-stack
train
4723caae1568e974af12c3b7
train
function
def _f_2(): R, x, y, z = ring("x,y,z", ZZ) return x**5*y**3 + x**5*y**2*z + x**5*y*z**2 + x**5*z**3 + x**3*y**2 + x**3*y*z + 90*x**3*y + 90*x**3*z + x**2*y**2*z - 11*x**2*y**2 + x**2*z**3 - 11*x**2*z**2 + y*z - 11*y + 90*z - 990
def _f_2():
R, x, y, z = ring("x,y,z", ZZ) return x**5*y**3 + x**5*y**2*z + x**5*y*z**2 + x**5*z**3 + x**3*y**2 + x**3*y*z + 90*x**3*y + 90*x**3*z + x**2*y**2*z - 11*x**2*y**2 + x**2*z**3 - 11*x**2*z**2 + y*z - 11*y + 90*z - 990
610*x*y + 20*x*z**2 + 230*x*z + 300*x + y**2*z**2 + 10*y**2*z + 30*y*z**2 + 320*y*z + 200*y + 600*z + 6000 def _f_2():
64
64
129
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_2
_f_2
305
307
305
305
b25964c09a8a71caa622243975b0b47a78f5e919
bigcode/the-stack
train
9cc2c17cd45246304fc79f27
train
function
def _f_3(): R, x, y, z = ring("x,y,z", ZZ) return x**5*y**2 + x**4*z**4 + x**4 + x**3*y**3*z + x**3*z + x**2*y**4 + x**2*y**3*z**3 + x**2*y*z**5 + x**2*y*z + x*y**2*z**4 + x*y**2 + x*y*z**7 + x*y*z**3 + x*y*z**2 + y**2*z + y*z**4
def _f_3():
R, x, y, z = ring("x,y,z", ZZ) return x**5*y**2 + x**4*z**4 + x**4 + x**3*y**3*z + x**3*z + x**2*y**4 + x**2*y**3*z**3 + x**2*y*z**5 + x**2*y*z + x*y**2*z**4 + x*y**2 + x*y*z**7 + x*y*z**3 + x*y*z**2 + y**2*z + y*z**4
**3*y + 90*x**3*z + x**2*y**2*z - 11*x**2*y**2 + x**2*z**3 - 11*x**2*z**2 + y*z - 11*y + 90*z - 990 def _f_3():
64
64
128
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_3
_f_3
309
311
309
309
0fe1152a8417d9ca20c3a205820ef46c5c72dd3c
bigcode/the-stack
train
baf7d1acdac5a89073231076
train
function
def fateman_poly_F_2(n): """Fateman's GCD benchmark: linearly dense quartic inputs """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0 = Y[0] u = Add(*[y for y in Y[1:]]) H = Poly((y_0 + u + 1)**2, *Y) F = Poly((y_0 - u - 2)**2, *Y) G = Poly((y_0 + u + 2)**2, *Y) return H*F, H...
def fateman_poly_F_2(n):
"""Fateman's GCD benchmark: linearly dense quartic inputs """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0 = Y[0] u = Add(*[y for y in Y[1:]]) H = Poly((y_0 + u + 1)**2, *Y) F = Poly((y_0 - u - 2)**2, *Y) G = Poly((y_0 + u + 2)**2, *Y) return H*F, H*G, H
(f, m, 1, K) F = dmp_mul(U, V, n, K) G = dmp_mul(W, Y, n, K) H = dmp_one(n, K) return F, G, H def fateman_poly_F_2(n):
64
64
139
9
54
clyring/sympy
sympy/polys/specialpolys.py
Python
fateman_poly_F_2
fateman_poly_F_2
221
234
221
221
527329374f72ee00ca9b0aed834f64c305968c8a
bigcode/the-stack
train
7389256917f0d9330059a0a8
train
function
def _f_6(): R, x, y, z, t = ring("x,y,z,t", ZZ) return 2115*x**4*y + 45*x**3*z**3*t**2 - 45*x**3*t**2 - 423*x*y**4 - 47*x*y**3 + 141*x*y*z**3 + 94*x*y*z*t - 9*y**3*z**3*t**2 + 9*y**3*t**2 - y**2*z**3*t**2 + y**2*t**2 + 3*z**6*t**2 + 2*z**4*t**3 - 3*z**3*t**2 - 2*z*t**3
def _f_6():
R, x, y, z, t = ring("x,y,z,t", ZZ) return 2115*x**4*y + 45*x**3*z**3*t**2 - 45*x**3*t**2 - 423*x*y**4 - 47*x*y**3 + 141*x*y*z**3 + 94*x*y*z*t - 9*y**3*z**3*t**2 + 9*y**3*t**2 - y**2*z**3*t**2 + y**2*t**2 + 3*z**6*t**2 + 2*z**4*t**3 - 3*z**3*t**2 - 2*z*t**3
3 - 3*x**2*y + 3*x**2*z - 3*x*y**2 + 6*x*y*z - 3*x*z**2 - y**3 + 3*y**2*z - 3*y*z**2 + z**3 def _f_6():
64
64
158
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_f_6
_f_6
321
323
321
321
1995d67f32c2c66a40dec18990ced67570394b30
bigcode/the-stack
train
c1dbf874c8be6a1e74c94655
train
function
def _w_2(): R, x, y = ring("x,y", ZZ) return 24*x**8*y**3 + 48*x**8*y**2 + 24*x**7*y**5 - 72*x**7*y**2 + 25*x**6*y**4 + 2*x**6*y**3 + 4*x**6*y + 8*x**6 + x**5*y**6 + x**5*y**3 - 12*x**5 + x**4*y**5 - x**4*y**4 - 2*x**4*y**3 + 292*x**4*y**2 - x**3*y**6 + 3*x**3*y**3 - x**2*y**5 + 12*x**2*y**3 + 48*x**2 - 12*y**3...
def _w_2():
R, x, y = ring("x,y", ZZ) return 24*x**8*y**3 + 48*x**8*y**2 + 24*x**7*y**5 - 72*x**7*y**2 + 25*x**6*y**4 + 2*x**6*y**3 + 4*x**6*y + 8*x**6 + x**5*y**6 + x**5*y**3 - 12*x**5 + x**4*y**5 - x**4*y**4 - 2*x**4*y**3 + 292*x**4*y**2 - x**3*y**6 + 3*x**3*y**3 - x**2*y**5 + 12*x**2*y**3 + 48*x**2 - 12*y**3
*z**3 + 2*x**2*y*z**2 + 2*x*y**3*z - 2*x*y**2*z**3 - 3*x*y*z + 3*x*z**3 - 2*y**2 + 2*y*z**2 def _w_2():
64
64
185
6
57
clyring/sympy
sympy/polys/specialpolys.py
Python
_w_2
_w_2
329
331
329
329
283bcd34d9f27aa5769cb4d125764d2ea096e22e
bigcode/the-stack
train
1bf36d96182e8f14d478a932
train
function
def main(config="../../config.yaml", namespace=""): # obtain config if isinstance(config, str): config = load_job_config(config) parties = config.parties guest = parties.guest[0] host_0 = parties.host[0] host_1 = parties.host[1] arbiter = parties.arbiter[0] backend = config.ba...
def main(config="../../config.yaml", namespace=""): # obtain config
if isinstance(config, str): config = load_job_config(config) parties = config.parties guest = parties.guest[0] host_0 = parties.host[0] host_1 = parties.host[1] arbiter = parties.arbiter[0] backend = config.backend work_mode = config.work_mode guest_train_data = {"name": "...
# # Copyright 2019 The FATE 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 appli...
239
256
903
16
222
hubert-he/FATE
examples/pipeline/homo_sbt/pipeline-homo-sbt-binary-multi-host.py
Python
main
main
31
98
31
33
d83c86151bfd2297839fb2808a1ac602e7e9eb5d
bigcode/the-stack
train
4b4f07fcee38cea4d9554bb8
train
class
class ProjectedOperator(OperatorBase): """Genric |Operator| for representing the projection of an |Operator| to a subspace. This class is not intended to be instantiated directly. Instead, you should use the :meth:`~pymor.operators.interfaces.OperatorInterface.projected` method of the given |Operator|....
class ProjectedOperator(OperatorBase):
"""Genric |Operator| for representing the projection of an |Operator| to a subspace. This class is not intended to be instantiated directly. Instead, you should use the :meth:`~pymor.operators.interfaces.OperatorInterface.projected` method of the given |Operator|. Parameters ---------- ope...
return VectorArrayOperator(V, transposed=True, copy=False, name=name) else: if range_basis is None: V = self.apply(source_basis) if self.range.type == NumpyVectorArray: from pymor.operators.numpy import ...
256
256
1,005
8
248
sdrave/pymor
src/pymor/operators/basic.py
Python
ProjectedOperator
ProjectedOperator
166
258
166
166
2edbdc0790b0b2d398ed1eb358c224c59edd298c
bigcode/the-stack
train
4a1101c17c6acf3da953d9b4
train
class
class OperatorBase(OperatorInterface): """Base class for |Operators| providing some default implementations. When implementing a new operator, it is usually advisable to derive from this class. """ def apply2(self, V, U, U_ind=None, V_ind=None, mu=None, product=None): mu = self.parse_param...
class OperatorBase(OperatorInterface):
"""Base class for |Operators| providing some default implementations. When implementing a new operator, it is usually advisable to derive from this class. """ def apply2(self, V, U, U_ind=None, V_ind=None, mu=None, product=None): mu = self.parse_parameter(mu) assert isinstance(V, V...
# -*- coding: utf-8 -*- # This file is part of the pyMOR project (http://www.pymor.org). # Copyright Holders: Rene Milk, Stephan Rave, Felix Schindler # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) # # Contributors: Michael Laier <m_laie01@uni-muenster.de> from __future__ import absolute...
162
256
1,406
7
154
sdrave/pymor
src/pymor/operators/basic.py
Python
OperatorBase
OperatorBase
20
163
20
20
19ee7e83e472627efcf0ca5bc3a23ec17a07d4c1
bigcode/the-stack
train
a9c9b965f06a718ecc5d0888
train
class
class ActionDispatcher: @classmethod def dispatch(cls, action_template): action = action_template['action'] if action == ACTIONS_LIST['create_user']: return CreateUserAction.execute(action_template['payload']) elif action == ACTIONS_LIST['create_recommendation_for_me']: ...
class ActionDispatcher: @classmethod
def dispatch(cls, action_template): action = action_template['action'] if action == ACTIONS_LIST['create_user']: return CreateUserAction.execute(action_template['payload']) elif action == ACTIONS_LIST['create_recommendation_for_me']: return CreateRecommendationForMe.e...
AcceptRecommendationFromAnotherUser from .actions.view_list import ViewList from .actions.ask_from_another_user import AskFromAnotherUser from .actions.delete_from_list import DeleteFromList from .actions.add_context_to_recommendation import AddContextToRecommendation from .actions.view_single_recommendation import Vi...
86
86
289
8
77
karllhughes/-
recommendations/action_dispatcher.py
Python
ActionDispatcher
ActionDispatcher
14
39
14
15
9c10e16bb80fc72ee1fcf9de0edbd857479066c8
bigcode/the-stack
train
e6850008174af255ec7525d0
train
class
class ModelTrainerBase(abc.ABC): def __init__(self, loss_function, train_data, test_data=None, metric=None, verbose=False): self.device = get_device() self.metric = metric self.verbose = verbose self...
class ModelTrainerBase(abc.ABC):
def __init__(self, loss_function, train_data, test_data=None, metric=None, verbose=False): self.device = get_device() self.metric = metric self.verbose = verbose self.loss_function = loss_function ...
import sys from copy import deepcopy from functools import reduce import numpy as np import torch from torchvision import utils as vutils from tqdm import trange from autokeras.constant import Constant from autokeras.utils import EarlyStop, get_device class ModelTrainerBase(abc.ABC):
64
64
121
9
54
luofei2018/autokeras
autokeras/model_trainer.py
Python
ModelTrainerBase
ModelTrainerBase
14
32
14
14
d082f4d9e0c573f6330c9c15105e03965cdfdf9e
bigcode/the-stack
train
75fce8051010f5cba5f37eee
train
class
class GANModelTrainer(ModelTrainerBase): def __init__(self, g_model, d_model, train_data, loss_function, verbose, gen_training_result=None): """Init the ModelTrainer with `model`, `x_train`, `y_train`, `x_t...
class GANModelTrainer(ModelTrainerBase):
def __init__(self, g_model, d_model, train_data, loss_function, verbose, gen_training_result=None): """Init the ModelTrainer with `model`, `x_train`, `y_train`, `x_test`, `y_test`, `verbose`""" supe...
.step() def _test(self): self.model.eval() test_loss = 0 all_targets = [] all_predicted = [] loader = self.test_loader with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(deepcopy(loader)): inputs, targets = inputs.to(self....
187
187
626
8
179
luofei2018/autokeras
autokeras/model_trainer.py
Python
GANModelTrainer
GANModelTrainer
144
217
144
144
dca6cc7b1f38d2088f7c38021b327d4365b85b3e
bigcode/the-stack
train
f02935aff7dc4eece906b51e
train
class
class ModelTrainer(ModelTrainerBase): """A class that is used to train the model. This class can train a Pytorch model with the given data loaders. The metric, loss_function, and model must be compatible with each other. Please see the details in the Attributes. Attributes: device: A strin...
class ModelTrainer(ModelTrainerBase):
"""A class that is used to train the model. This class can train a Pytorch model with the given data loaders. The metric, loss_function, and model must be compatible with each other. Please see the details in the Attributes. Attributes: device: A string. Indicating the device to use. 'cuda...
import abc import sys from copy import deepcopy from functools import reduce import numpy as np import torch from torchvision import utils as vutils from tqdm import trange from autokeras.constant import Constant from autokeras.utils import EarlyStop, get_device class ModelTrainerBase(abc.ABC): def __init__(self...
186
256
981
7
178
luofei2018/autokeras
autokeras/model_trainer.py
Python
ModelTrainer
ModelTrainer
35
141
35
35
301b12a253cf03033f1e969fcc9b1f1900d9070a
bigcode/the-stack
train
8d830ae0c43a5db1424228ed
train
function
def contractuser(string, old_cache_name=__NCC_DIR__, new_cache_name=__NCC_DIR__): # linux string = str.replace(string, '.ncc', 'ncc_data') # dst_dir = string.rsplit(old_cache_name, maxsplit=1)[-1] # if str.startswith(dst_dir, os.path.sep): # dst_dir = dst_dir[len(os.path.sep):] # contract_st...
def contractuser(string, old_cache_name=__NCC_DIR__, new_cache_name=__NCC_DIR__): # linux
string = str.replace(string, '.ncc', 'ncc_data') # dst_dir = string.rsplit(old_cache_name, maxsplit=1)[-1] # if str.startswith(dst_dir, os.path.sep): # dst_dir = dst_dir[len(os.path.sep):] # contract_string = os.path.join('~', new_cache_name, dst_dir) contract_string = '~' + string.split('nc...
for i, val in enumerate(obj): if isinstance(val, str) and val.startswith('~/'): obj[i] = PathManager.expanduser(val) return obj def contractuser(string, old_cache_name=__NCC_DIR__, new_cache_name=__NCC_DIR__): # linux
64
64
135
28
35
iwangyuezhang/naturalcc
ncc/utils/file_ops/yaml_io.py
Python
contractuser
contractuser
25
33
25
26
718c2c2a3a961a7d56e0607c75d4e06c2c1405d4
bigcode/the-stack
train
e3f7af2d6ba00925ed9bb6c0
train
function
def recursive_expanduser(obj): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_expanduser(value) elif isinstance(obj, str) and obj.startswith('~/'): obj = PathManager.expanduser(obj) elif isinstance(obj, list): for i, val in enumerate(obj): ...
def recursive_expanduser(obj):
if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_expanduser(value) elif isinstance(obj, str) and obj.startswith('~/'): obj = PathManager.expanduser(obj) elif isinstance(obj, list): for i, val in enumerate(obj): if isinstance(val, s...
# -*- coding: utf-8 -*- import os from typing import Dict import ruamel.yaml as yaml from ncc import __NCC_DIR__ from ncc.utils.path_manager import PathManager def recursive_expanduser(obj):
48
64
98
6
41
iwangyuezhang/naturalcc
ncc/utils/file_ops/yaml_io.py
Python
recursive_expanduser
recursive_expanduser
12
22
12
12
fe5d3193d0a7e5c275148644d7af2d9c98f36546
bigcode/the-stack
train
348049ea5b8aa01b6ddec0f6
train
function
def recursive_contractuser(obj, old_cache_name=__NCC_DIR__, new_cache_name=__NCC_DIR__): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_contractuser(value, old_cache_name=old_cache_name, new_cache_name=new_cache_name) elif isinstance(obj, str) and (str.startswi...
def recursive_contractuser(obj, old_cache_name=__NCC_DIR__, new_cache_name=__NCC_DIR__):
if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_contractuser(value, old_cache_name=old_cache_name, new_cache_name=new_cache_name) elif isinstance(obj, str) and (str.startswith(obj, '/')): obj = contractuser(obj, old_cache_name=old_cache_name, new_cache_n...
.path.join('~', new_cache_name, dst_dir) contract_string = '~' + string.split('ncc_data', maxsplit=1)[-1] return contract_string def recursive_contractuser(obj, old_cache_name=__NCC_DIR__, new_cache_name=__NCC_DIR__):
64
64
148
25
38
iwangyuezhang/naturalcc
ncc/utils/file_ops/yaml_io.py
Python
recursive_contractuser
recursive_contractuser
36
45
36
36
cd9c70fc002be301d666a3764043f87c393fbc5f
bigcode/the-stack
train
67ab61caa338ab3e502ddbc1
train
function
def load_yaml(yaml_file: str) -> Dict: ''' read yaml file :param yaml_file: ''' with open(yaml_file, 'r', encoding='utf-8') as reader: args = yaml.safe_load(reader) recursive_expanduser(args) return args
def load_yaml(yaml_file: str) -> Dict:
''' read yaml file :param yaml_file: ''' with open(yaml_file, 'r', encoding='utf-8') as reader: args = yaml.safe_load(reader) recursive_expanduser(args) return args
new_cache_name=new_cache_name) elif isinstance(obj, list): for i, val in enumerate(obj): obj[i] = recursive_contractuser(val, old_cache_name=old_cache_name, new_cache_name=new_cache_name) return obj def load_yaml(yaml_file: str) -> Dict:
64
64
64
12
51
iwangyuezhang/naturalcc
ncc/utils/file_ops/yaml_io.py
Python
load_yaml
load_yaml
48
56
48
48
ca0ab5b2cef42e8c281595d5f018452f2363384d
bigcode/the-stack
train
99e0d6d6a85b52460f8efb91
train
function
def solve1(code): return simulate(code)[1]
def solve1(code):
return simulate(code)[1]
= "jmp" elif inst == "jmp": inst = "nop" if inst == "nop": at += 1 continue elif inst == "acc": at += 1 acc += val else: at += val def solve1(code):
64
64
12
5
58
zed-b/advent-of-code
2020/src/day08.py
Python
solve1
solve1
28
29
28
28
2f268ae32727360aef46ef34085e4164f780c33a
bigcode/the-stack
train
fcfd96d450ce9849cd1709c7
train
function
def solve2(code): for i in range(len(code)): at,acc = simulate(code,i) if at >= len(code): return acc
def solve2(code):
for i in range(len(code)): at,acc = simulate(code,i) if at >= len(code): return acc
inst = "nop" if inst == "nop": at += 1 continue elif inst == "acc": at += 1 acc += val else: at += val def solve1(code): return simulate(code)[1] def solve2(code):
64
64
33
5
59
zed-b/advent-of-code
2020/src/day08.py
Python
solve2
solve2
31
35
31
31
56d24d8173f93d48d511dbf2fcd2f096ade07aaf
bigcode/the-stack
train
0ead26661b8675cd3bfe677e
train
function
def simulate(code, change_at=-1): vis = set() at, acc = 0, 0 while (True): if at >= len(code) or at in vis: return (at, acc) vis.add(at) inst,val = code[at] if change_at == at: if inst == "nop": inst = "jmp" elif inst == "...
def simulate(code, change_at=-1):
vis = set() at, acc = 0, 0 while (True): if at >= len(code) or at in vis: return (at, acc) vis.add(at) inst,val = code[at] if change_at == at: if inst == "nop": inst = "jmp" elif inst == "jmp": inst = "nop"...
import sys def simulate(code, change_at=-1):
12
64
137
9
2
zed-b/advent-of-code
2020/src/day08.py
Python
simulate
simulate
3
26
3
3
21812ccdbfca8adc7a8863fb94d512a21d84f5e4
bigcode/the-stack
train
c9211176812a1bbc6a06dae1
train
class
class _DummyPositionEncoder(position.PositionEncoder): """Encoder that simply forwards the position indices.""" def _encode(self, positions, depth): positions = tf.expand_dims(positions, 2) positions = tf.tile(positions, [1, 1, depth]) return tf.cast(positions, self.dtype)
class _DummyPositionEncoder(position.PositionEncoder):
"""Encoder that simply forwards the position indices.""" def _encode(self, positions, depth): positions = tf.expand_dims(positions, 2) positions = tf.tile(positions, [1, 1, depth]) return tf.cast(positions, self.dtype)
import tensorflow as tf from parameterized import parameterized from opennmt.layers import position class _DummyPositionEncoder(position.PositionEncoder):
29
64
67
9
19
gcervantes8/OpenNMT-tf
opennmt/tests/position_test.py
Python
_DummyPositionEncoder
_DummyPositionEncoder
8
14
8
8
1fd8f210dcb706f2adf08726b23ca45c01e78450
bigcode/the-stack
train
21d41a9559fe6c8b0226cc0e
train
class
class PositionTest(tf.test.TestCase): def testApplyOneEncoding(self): encoder = _DummyPositionEncoder() inputs = tf.zeros([2, 1, 3]) outputs = encoder(inputs, 2) outputs = self.evaluate(outputs) self.assertAllEqual(outputs, [[[2, 2, 2]], [[2, 2, 2]]]) def testApplyPositi...
class PositionTest(tf.test.TestCase):
def testApplyOneEncoding(self): encoder = _DummyPositionEncoder() inputs = tf.zeros([2, 1, 3]) outputs = encoder(inputs, 2) outputs = self.evaluate(outputs) self.assertAllEqual(outputs, [[[2, 2, 2]], [[2, 2, 2]]]) def testApplyPositionEncoding(self): encoder = _D...
import tensorflow as tf from parameterized import parameterized from opennmt.layers import position class _DummyPositionEncoder(position.PositionEncoder): """Encoder that simply forwards the position indices.""" def _encode(self, positions, depth): positions = tf.expand_dims(positions, 2) p...
95
146
489
8
87
gcervantes8/OpenNMT-tf
opennmt/tests/position_test.py
Python
PositionTest
PositionTest
17
64
17
17
5de39ad3bd0ec710208c1b1052a28f2bcc9d5922
bigcode/the-stack
train
cc2d0d49a0d5ab98e09fe24e
train
class
class CircularLinkedList: def __init__(self, key): z = Node(key) z.next = z self.last = z
class CircularLinkedList:
def __init__(self, key): z = Node(key) z.next = z self.last = z
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList:
29
64
32
5
23
pranjalkumar153/algo_ds_101
Data_Structures/Linked_List/Circular_Linked_List/circularLinkedList.py
Python
CircularLinkedList
CircularLinkedList
6
10
6
6
cb026d8d4b613ca76d8fa4a8cc5a33b0dfc0bc8c
bigcode/the-stack
train
49c550311c4940f53bace483
train
function
def traversal(l): temp = l.last a = str(temp.data)+"\t" temp = temp.next while temp != l.last: a = a + str(temp.data) + "\t" temp = temp.next print(a)
def traversal(l):
temp = l.last a = str(temp.data)+"\t" temp = temp.next while temp != l.last: a = a + str(temp.data) + "\t" temp = temp.next print(a)
#only one node l.last = NULL else: #more than one node and last node temp.next = n.next l.last = temp #updating last pointer else: #not last node temp.next = n.next del n def traversal(l):
64
64
56
4
59
pranjalkumar153/algo_ds_101
Data_Structures/Linked_List/Circular_Linked_List/circularLinkedList.py
Python
traversal
traversal
36
44
36
36
ab58029df1efc993a0ba2ecab7d0161f173647f4
bigcode/the-stack
train
540889c05d82bf9922f4f4ae
train
function
def insert_at_last(l, n): n.next = l.last.next l.last.next = n l.last = n
def insert_at_last(l, n):
n.next = l.last.next l.last.next = n l.last = n
.next = None class CircularLinkedList: def __init__(self, key): z = Node(key) z.next = z self.last = z def insert_after(n, a): n.next = a.next a.next = n def insert_at_last(l, n):
64
64
29
8
55
pranjalkumar153/algo_ds_101
Data_Structures/Linked_List/Circular_Linked_List/circularLinkedList.py
Python
insert_at_last
insert_at_last
16
19
16
16
30321585c8db32ea641de71fde91bdd425b0ffdc
bigcode/the-stack
train
edf354332301bb621d8781e6
train
class
class Node: def __init__(self, data): self.data = data self.next = None
class Node:
def __init__(self, data): self.data = data self.next = None
class Node:
3
64
24
3
0
pranjalkumar153/algo_ds_101
Data_Structures/Linked_List/Circular_Linked_List/circularLinkedList.py
Python
Node
Node
1
4
1
1
94a39e95343f29a669455bef62560d7a969982fc
bigcode/the-stack
train
d31c7de71e24dcf036a69ee9
train
function
def delete(l, n): temp = l.last while temp.next != n: temp = temp.next if n == l.last: #last node if n.next == n: #only one node l.last = NULL else: #more than one node and last node temp.next = n.next l.last = temp #updating last pointer else: #not last node temp.next = n.nex...
def delete(l, n):
temp = l.last while temp.next != n: temp = temp.next if n == l.last: #last node if n.next == n: #only one node l.last = NULL else: #more than one node and last node temp.next = n.next l.last = temp #updating last pointer else: #not last node temp.next = n.next del n
= z self.last = z def insert_after(n, a): n.next = a.next a.next = n def insert_at_last(l, n): n.next = l.last.next l.last.next = n l.last = n def delete(l, n):
64
64
103
6
57
pranjalkumar153/algo_ds_101
Data_Structures/Linked_List/Circular_Linked_List/circularLinkedList.py
Python
delete
delete
21
34
21
21
c04bcd645338c85d6a4609627cc7385d62d4e7a8
bigcode/the-stack
train
3d31fa16714b464452c7f324
train
function
def insert_after(n, a): n.next = a.next a.next = n
def insert_after(n, a):
n.next = a.next a.next = n
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self, key): z = Node(key) z.next = z self.last = z def insert_after(n, a):
63
64
20
7
55
pranjalkumar153/algo_ds_101
Data_Structures/Linked_List/Circular_Linked_List/circularLinkedList.py
Python
insert_after
insert_after
12
14
12
12
c9a6adca99ac832d9c7faaf16bfef8526a2e13cf
bigcode/the-stack
train