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
d50e684bb4de1631ce7553b7
train
function
def _log_info(msg): _LOGGER.info(msg)
def _log_info(msg):
_LOGGER.info(msg)
@wraps(func) def wrapper(msg): nonlocal msg_normalized if msg.strip() == '': msg = ''.join(msg_normalized) msg_normalized = [] return func(msg) else: msg_normalized.append(msg) return wrapper def _log_info(msg):
64
64
12
6
57
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_log_info
_log_info
78
79
78
78
4a8daf06c9d447c1aa66421877a7aee099062ff0
bigcode/the-stack
train
e416c6de3fc0f6c47220d2df
train
function
def cint32_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int32 pointer')
def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int32 pointer')
ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected double pointer') def cint32_array_to_numpy(cptr, length):
64
64
70
11
53
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
cint32_array_to_numpy
cint32_array_to_numpy
199
204
199
199
30919ed66d1461f5f353fc45aadfe25a898758e6
bigcode/the-stack
train
40d120e6f874c9c556d41fac
train
function
def convert_from_sliced_object(data): """Fix the memory of multi-dimensional sliced object.""" if isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray): if not data.flags.c_contiguous: _log_warning("Usage of np.ndarray subset (sliced data) is not recommended " ...
def convert_from_sliced_object(data):
"""Fix the memory of multi-dimensional sliced object.""" if isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray): if not data.flags.c_contiguous: _log_warning("Usage of np.ndarray subset (sliced data) is not recommended " "due to it will double the peak...
_API_DTYPE_FLOAT64, "group": C_API_DTYPE_INT32} """String name to int feature importance type mapper""" FEATURE_IMPORTANCE_TYPE_MAPPER = {"split": C_API_FEATURE_IMPORTANCE_SPLIT, "gain": C_API_FEATURE_IMPORTANCE_GAIN} def convert_from_sliced_object(data):
64
64
89
8
56
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
convert_from_sliced_object
convert_from_sliced_object
454
461
454
454
439757f026300331cea9bcaecf47171f11ab5b5e
bigcode/the-stack
train
38c3595531b82abdfae39a9b
train
function
def _load_lib(): """Load LightGBM library.""" lib_path = find_lib_path() if len(lib_path) == 0: return None lib = ctypes.cdll.LoadLibrary(lib_path[0]) lib.LGBM_GetLastError.restype = ctypes.c_char_p callback = ctypes.CFUNCTYPE(None, ctypes.c_char_p) lib.callback = callback(_log_callb...
def _load_lib():
"""Load LightGBM library.""" lib_path = find_lib_path() if len(lib_path) == 0: return None lib = ctypes.cdll.LoadLibrary(lib_path[0]) lib.LGBM_GetLastError.restype = ctypes.c_char_p callback = ctypes.CFUNCTYPE(None, ctypes.c_char_p) lib.callback = callback(_log_callback) if lib.L...
def _log_warning(msg): _LOGGER.warning(msg) @_normalize_native_string def _log_native(msg): _LOGGER.info(msg) def _log_callback(msg): """Redirect logs from native library into Python.""" _log_native(str(msg.decode('utf-8'))) def _load_lib():
63
64
127
5
58
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_load_lib
_load_lib
96
107
96
96
a942229e1ef47f0557a0b7891d29b1a21fb4f682
bigcode/the-stack
train
ec1b1647ada4ae89c7933ad0
train
function
def _dump_pandas_categorical(pandas_categorical, file_name=None): categorical_json = json.dumps(pandas_categorical, default=json_default_with_numpy) pandas_str = f'\npandas_categorical:{categorical_json}\n' if file_name is not None: with open(file_name, 'a') as f: f.write(pandas_str) ...
def _dump_pandas_categorical(pandas_categorical, file_name=None):
categorical_json = json.dumps(pandas_categorical, default=json_default_with_numpy) pandas_str = f'\npandas_categorical:{categorical_json}\n' if file_name is not None: with open(file_name, 'a') as f: f.write(pandas_str) return pandas_str
_bad_pandas_dtypes(label.dtypes): raise ValueError('DataFrame.dtypes for label must be int, float or bool') label = np.ravel(label.values.astype(np.float32, copy=False)) return label def _dump_pandas_categorical(pandas_categorical, file_name=None):
64
64
82
16
47
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_dump_pandas_categorical
_dump_pandas_categorical
570
576
570
570
a09f497971c8bf2163513b8ab0bec70ae310cf67
bigcode/the-stack
train
532bc75d08d4b8fa8dfeb67e
train
class
class LightGBMError(Exception): """Error thrown by LightGBM.""" pass
class LightGBMError(Exception):
"""Error thrown by LightGBM.""" pass
gbm_tmp_", delete=True) as f: self.name = f.name self.path = Path(self.name) return self def __exit__(self, exc_type, exc_val, exc_tb): if self.path.is_file(): self.path.unlink() class LightGBMError(Exception):
64
64
19
7
57
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
LightGBMError
LightGBMError
269
272
269
269
ba60a9eb1f0af1c02807f62ec24c0b25aeaa09ae
bigcode/the-stack
train
e1bf382a60fb6f0faa1f7559
train
function
def is_1d_list(data): """Check whether data is a 1-D list.""" return isinstance(data, list) and (not data or is_numeric(data[0]))
def is_1d_list(data):
"""Check whether data is a 1-D list.""" return isinstance(data, list) and (not data or is_numeric(data[0]))
and shape[1] == 1 def cast_numpy_1d_array_to_dtype(array, dtype): """Cast numpy 1d array to given dtype.""" if array.dtype == dtype: return array return array.astype(dtype=dtype, copy=False) def is_1d_list(data):
64
64
38
8
56
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
is_1d_list
is_1d_list
159
161
159
159
d290058b418d7832b654064b905bb2f4ce960cd4
bigcode/the-stack
train
741cb31057b8fd125c9d1e21
train
class
class _DummyLogger: def info(self, msg): print(msg) def warning(self, msg): warnings.warn(msg, stacklevel=3)
class _DummyLogger:
def info(self, msg): print(msg) def warning(self, msg): warnings.warn(msg, stacklevel=3)
: int, params: str): sample_cnt = ctypes.c_int(0) _safe_call(_LIB.LGBM_GetSampleCount( ctypes.c_int32(total_nrow), c_str(params), ctypes.byref(sample_cnt), )) return sample_cnt.value class _DummyLogger:
64
64
33
5
58
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_DummyLogger
_DummyLogger
36
41
36
36
9a7625ff21351c7751d8865510f75a1ba34447f7
bigcode/the-stack
train
158806aa9047da79fe17cdf1
train
function
def _log_warning(msg): _LOGGER.warning(msg)
def _log_warning(msg):
_LOGGER.warning(msg)
local msg_normalized if msg.strip() == '': msg = ''.join(msg_normalized) msg_normalized = [] return func(msg) else: msg_normalized.append(msg) return wrapper def _log_info(msg): _LOGGER.info(msg) def _log_warning(msg):
64
64
12
6
58
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_log_warning
_log_warning
82
83
82
82
e04885bae41ae84494a73d42c2e0c7e0af4d46db
bigcode/the-stack
train
7466428bd3a82ef76e412d6e
train
function
def _choose_param_value(main_param_name: str, params: Dict[str, Any], default_value: Any) -> Dict[str, Any]: """Get a single parameter value, accounting for aliases. Parameters ---------- main_param_name : str Name of the main parameter to get a value for. One of the keys of ``_ConfigAliases``....
def _choose_param_value(main_param_name: str, params: Dict[str, Any], default_value: Any) -> Dict[str, Any]:
"""Get a single parameter value, accounting for aliases. Parameters ---------- main_param_name : str Name of the main parameter to get a value for. One of the keys of ``_ConfigAliases``. params : dict Dictionary of LightGBM parameters. default_value : Any Default value t...
"use_two_round_loading"}, "verbosity": {"verbosity", "verbose"}, "weight_column": {"weight_column", "weight"}} @classmethod def get(cls, *args): ret = set() for i in args: ret |= cls.aliases...
99
99
332
29
69
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_choose_param_value
_choose_param_value
378
415
378
378
424f41cc94b040ddccddbca6c4dde0ca7384b6b3
bigcode/the-stack
train
9766a766127f5b338c8238a8
train
class
class Dataset: """Dataset in LightGBM.""" def __init__(self, data, label=None, reference=None, weight=None, group=None, init_score=None, silent=False, feature_name='auto', categorical_feature='auto', params=None, free_raw_data=True): """Initialize Data...
class Dataset:
"""Dataset in LightGBM.""" def __init__(self, data, label=None, reference=None, weight=None, group=None, init_score=None, silent=False, feature_name='auto', categorical_feature='auto', params=None, free_raw_data=True): """Initialize Dataset. P...
.LGBM_BoosterPredictForCSC( self.handle, ptr_indptr, ctypes.c_int(type_ptr_indptr), csc_indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int64(len(csc.indptr)), ctypes.c...
256
256
11,485
3
252
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
Dataset
Dataset
1,122
2,459
1,122
1,122
a677af7275fbbb827030bb5ab3cdb0c058ea5fd0
bigcode/the-stack
train
081e246e1e1a6012522bd5e8
train
function
def c_float_array(data): """Get pointer of float numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.float32: ptr_data ...
def c_float_array(data):
"""Get pointer of float numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.float32: ptr_data = data.ctypes.data_as(cty...
, np.ndarray): if not data.flags.c_contiguous: _log_warning("Usage of np.ndarray subset (sliced data) is not recommended " "due to it will double the peak memory cost in LightGBM.") return np.copy(data) return data def c_float_array(data):
64
64
209
6
57
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
c_float_array
c_float_array
464
481
464
464
5c517b08f8fc39b441e8d04fb03090b9d99f8714
bigcode/the-stack
train
9f74718378d1a4c453234364
train
function
def list_to_1d_numpy(data, dtype=np.float32, name='list'): """Convert data to numpy 1-D array.""" if is_numpy_1d_array(data): return cast_numpy_1d_array_to_dtype(data, dtype) elif is_numpy_column_array(data): _log_warning('Converting column-vector to 1d array') array = data.ravel() ...
def list_to_1d_numpy(data, dtype=np.float32, name='list'):
"""Convert data to numpy 1-D array.""" if is_numpy_1d_array(data): return cast_numpy_1d_array_to_dtype(data, dtype) elif is_numpy_column_array(data): _log_warning('Converting column-vector to 1d array') array = data.ravel() return cast_numpy_1d_array_to_dtype(array, dtype) ...
array.astype(dtype=dtype, copy=False) def is_1d_list(data): """Check whether data is a 1-D list.""" return isinstance(data, list) and (not data or is_numeric(data[0])) def list_to_1d_numpy(data, dtype=np.float32, name='list'):
65
66
222
18
47
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
list_to_1d_numpy
list_to_1d_numpy
164
180
164
164
3f7ca4391cbb74325b0f37d917a17b403c1f9609
bigcode/the-stack
train
b49468eea6207254d38395e6
train
function
def _data_from_pandas(data, feature_name, categorical_feature, pandas_categorical): if isinstance(data, pd_DataFrame): if len(data.shape) != 2 or data.shape[0] < 1: raise ValueError('Input data must be 2 dimensional and non empty.') if feature_name == 'auto' or feature_name is None: ...
def _data_from_pandas(data, feature_name, categorical_feature, pandas_categorical):
if isinstance(data, pd_DataFrame): if len(data.shape) != 2 or data.shape[0] < 1: raise ValueError('Input data must be 2 dimensional and non empty.') if feature_name == 'auto' or feature_name is None: data = data.rename(columns=str) cat_cols = list(data.select_dtypes(i...
= {'int8': 'int', 'int16': 'int', 'int32': 'int', 'int64': 'int', 'uint8': 'int', 'uint16': 'int', 'uint32': 'int', 'uint64': 'int', 'bool': 'int', 'float16': 'float', 'float32': 'float', 'float64': 'float'} bad_indices = [i for i, dt...
156
156
521
18
137
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_data_from_pandas
_data_from_pandas
515
557
515
515
4b1d85b1c2c455a01fcc1add4961e1aa47cd90cb
bigcode/the-stack
train
82ce9b491dc57c6d9805758e
train
function
def _load_pandas_categorical(file_name=None, model_str=None): pandas_key = 'pandas_categorical:' offset = -len(pandas_key) if file_name is not None: max_offset = -getsize(file_name) with open(file_name, 'rb') as f: while True: if offset < max_offset: ...
def _load_pandas_categorical(file_name=None, model_str=None):
pandas_key = 'pandas_categorical:' offset = -len(pandas_key) if file_name is not None: max_offset = -getsize(file_name) with open(file_name, 'rb') as f: while True: if offset < max_offset: offset = max_offset f.seek(offset, SEEK...
) pandas_str = f'\npandas_categorical:{categorical_json}\n' if file_name is not None: with open(file_name, 'a') as f: f.write(pandas_str) return pandas_str def _load_pandas_categorical(file_name=None, model_str=None):
65
65
217
15
49
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_load_pandas_categorical
_load_pandas_categorical
579
602
579
579
dc427ed58c014d7135718f335466d1c1ff5e9dad
bigcode/the-stack
train
59ec31acbdd4a83acb2ae6b5
train
function
def _normalize_native_string(func): """Join log messages from native library which come by chunks.""" msg_normalized = [] @wraps(func) def wrapper(msg): nonlocal msg_normalized if msg.strip() == '': msg = ''.join(msg_normalized) msg_normalized = [] re...
def _normalize_native_string(func):
"""Join log messages from native library which come by chunks.""" msg_normalized = [] @wraps(func) def wrapper(msg): nonlocal msg_normalized if msg.strip() == '': msg = ''.join(msg_normalized) msg_normalized = [] return func(msg) else: ...
_logger(logger): """Register custom logger. Parameters ---------- logger : logging.Logger Custom logger. """ if not isinstance(logger, Logger): raise TypeError("Logger should inherit logging.Logger class") global _LOGGER _LOGGER = logger def _normalize_native_string(func...
64
64
85
7
56
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_normalize_native_string
_normalize_native_string
61
75
61
61
bf110d537b672dbec6870cba069d8f3166c79907
bigcode/the-stack
train
5c9b0cd768d3ba12924ed99b
train
function
def cfloat32_array_to_numpy(cptr, length): """Convert a ctypes float pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_float)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected float pointer')
def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_float)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected float pointer')
) # SparseArray should be supported as well else: raise TypeError(f"Wrong type({type(data).__name__}) for {name}.\n" "It should be list, numpy 1-D array or pandas Series") def cfloat32_array_to_numpy(cptr, length):
64
64
69
12
52
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
cfloat32_array_to_numpy
cfloat32_array_to_numpy
183
188
183
183
4155bb903f9ff1fb018b95f369c302d63361e5dd
bigcode/the-stack
train
a7fae985cda0a26b89a6e47c
train
function
def c_array(ctype, values): """Convert a Python array to C array.""" return (ctype * len(values))(*values)
def c_array(ctype, values):
"""Convert a Python array to C array.""" return (ctype * len(values))(*values)
ypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int64 pointer') def c_str(string): """Convert a Python string to C string.""" return ctypes.c_char_p(string.encode('utf-8')) def c_array(ctype, values):
63
64
29
8
55
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
c_array
c_array
220
222
220
220
b32ff3b40cfe203b99a9be3d8ecba0b948ec4f3d
bigcode/the-stack
train
eed8556fbd04cdcd0f45b7c0
train
class
class _TempFile: """Proxy class to workaround errors on Windows.""" def __enter__(self): with NamedTemporaryFile(prefix="lightgbm_tmp_", delete=True) as f: self.name = f.name self.path = Path(self.name) return self def __exit__(self, exc_type, exc_val, exc_tb): ...
class _TempFile:
"""Proxy class to workaround errors on Windows.""" def __enter__(self): with NamedTemporaryFile(prefix="lightgbm_tmp_", delete=True) as f: self.name = f.name self.path = Path(self.name) return self def __exit__(self, exc_type, exc_val, exc_tb): if self.path....
str, Path, NUMERIC_TYPES)) or is_numeric(val): pairs.append(f"{key}={val}") elif val is not None: raise TypeError(f'Unknown type of parameter:{key}, got:{type(val).__name__}') return ' '.join(pairs) class _TempFile:
64
64
87
5
59
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_TempFile
_TempFile
255
266
255
255
7e6ae05dce0a3a0a1d29a08db7d4f26097a71437
bigcode/the-stack
train
3d21446563ebee599be4979f
train
function
def _get_sample_count(total_nrow: int, params: str): sample_cnt = ctypes.c_int(0) _safe_call(_LIB.LGBM_GetSampleCount( ctypes.c_int32(total_nrow), c_str(params), ctypes.byref(sample_cnt), )) return sample_cnt.value
def _get_sample_count(total_nrow: int, params: str):
sample_cnt = ctypes.c_int(0) _safe_call(_LIB.LGBM_GetSampleCount( ctypes.c_int32(total_nrow), c_str(params), ctypes.byref(sample_cnt), )) return sample_cnt.value
.sparse from .compat import PANDAS_INSTALLED, concat, dt_DataTable, is_dtype_sparse, pd_DataFrame, pd_Series from .libpath import find_lib_path ZERO_THRESHOLD = 1e-35 def _get_sample_count(total_nrow: int, params: str):
64
64
67
15
48
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_get_sample_count
_get_sample_count
26
33
26
26
61034164f1d5e51196561fc94f660f62d5e3f4a0
bigcode/the-stack
train
1713b3f3082ca4e9e55cd8b7
train
function
def _log_callback(msg): """Redirect logs from native library into Python.""" _log_native(str(msg.decode('utf-8')))
def _log_callback(msg):
"""Redirect logs from native library into Python.""" _log_native(str(msg.decode('utf-8')))
(msg) else: msg_normalized.append(msg) return wrapper def _log_info(msg): _LOGGER.info(msg) def _log_warning(msg): _LOGGER.warning(msg) @_normalize_native_string def _log_native(msg): _LOGGER.info(msg) def _log_callback(msg):
64
64
28
6
58
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_log_callback
_log_callback
91
93
91
91
57daa15ad06f9af79aa3b0d596d6df1be8b3b804
bigcode/the-stack
train
d7f334530636e71d76e9f8dc
train
function
def cint64_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int64)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int64 pointer')
def cint64_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int64)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int64 pointer')
pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int32 pointer') def cint64_array_to_numpy(cptr, length):
64
64
70
11
53
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
cint64_array_to_numpy
cint64_array_to_numpy
207
212
207
207
fe9078ea91caed1d02131a9587c2044b51cab5a4
bigcode/the-stack
train
a03d35142cb4e18120579451
train
function
@_normalize_native_string def _log_native(msg): _LOGGER.info(msg)
@_normalize_native_string def _log_native(msg):
_LOGGER.info(msg)
_normalized) msg_normalized = [] return func(msg) else: msg_normalized.append(msg) return wrapper def _log_info(msg): _LOGGER.info(msg) def _log_warning(msg): _LOGGER.warning(msg) @_normalize_native_string def _log_native(msg):
64
64
18
12
52
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_log_native
_log_native
86
88
86
87
be25ebe15831c945ad8f7c5d791850ac3d40d29c
bigcode/the-stack
train
a8fd7045e67b31581f8c673b
train
class
class _InnerPredictor: """_InnerPredictor of LightGBM. Not exposed to user. Used only for prediction, usually used for continued training. .. note:: Can be converted from Booster, but cannot be converted to Booster. """ def __init__(self, model_file=None, booster_handle=None, pred_pa...
class _InnerPredictor:
"""_InnerPredictor of LightGBM. Not exposed to user. Used only for prediction, usually used for continued training. .. note:: Can be converted from Booster, but cannot be converted to Booster. """ def __init__(self, model_file=None, booster_handle=None, pred_parameter=None): ...
: .. code-block:: python if isinstance(idx, numbers.Integral): return self._get_one_line(idx) elif isinstance(idx, slice): return np.stack([self._get_one_line(i) for i in range(idx.start, idx.stop)]) elif isinstance(idx, list): ...
256
256
4,898
6
250
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_InnerPredictor
_InnerPredictor
671
1,119
671
671
6902dcf632c1cd827dc24ed83eda219a65494741
bigcode/the-stack
train
8e7a94227ee74c03deb71533
train
function
def param_dict_to_str(data): """Convert Python dictionary to string, which is passed to C API.""" if data is None or not data: return "" pairs = [] for key, val in data.items(): if isinstance(val, (list, tuple, set)) or is_numpy_1d_array(val): def to_string(x): ...
def param_dict_to_str(data):
"""Convert Python dictionary to string, which is passed to C API.""" if data is None or not data: return "" pairs = [] for key, val in data.items(): if isinstance(val, (list, tuple, set)) or is_numpy_1d_array(val): def to_string(x): if isinstance(x, list): ...
_with_numpy(obj): """Convert numpy classes to JSON serializable objects.""" if isinstance(obj, (np.integer, np.floating, np.bool_)): return obj.item() elif isinstance(obj, np.ndarray): return obj.tolist() else: return obj def param_dict_to_str(data):
64
64
185
7
56
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
param_dict_to_str
param_dict_to_str
235
252
235
235
543ff4edcf1621748e18fd63624143700fbf73a3
bigcode/the-stack
train
491611e17d67e2c56c90a3a9
train
function
def _label_from_pandas(label): if isinstance(label, pd_DataFrame): if len(label.columns) > 1: raise ValueError('DataFrame for label cannot have multiple columns') if _get_bad_pandas_dtypes(label.dtypes): raise ValueError('DataFrame.dtypes for label must be int, float or bool'...
def _label_from_pandas(label):
if isinstance(label, pd_DataFrame): if len(label.columns) > 1: raise ValueError('DataFrame for label cannot have multiple columns') if _get_bad_pandas_dtypes(label.dtypes): raise ValueError('DataFrame.dtypes for label must be int, float or bool') label = np.ravel(labe...
64: data = data.astype(np.float32) else: if feature_name == 'auto': feature_name = None if categorical_feature == 'auto': categorical_feature = None return data, feature_name, categorical_feature, pandas_categorical def _label_from_pandas(label):
64
64
93
8
55
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_label_from_pandas
_label_from_pandas
560
567
560
560
445ed3729cf9b8ad30e8a2329562179e0befc9ad
bigcode/the-stack
train
0bcd35893b61712a637d0916
train
function
def _get_bad_pandas_dtypes(dtypes): pandas_dtype_mapper = {'int8': 'int', 'int16': 'int', 'int32': 'int', 'int64': 'int', 'uint8': 'int', 'uint16': 'int', 'uint32': 'int', 'uint64': 'int', 'bool': 'int', 'float16': 'float', 'float32': ...
def _get_bad_pandas_dtypes(dtypes):
pandas_dtype_mapper = {'int8': 'int', 'int16': 'int', 'int32': 'int', 'int64': 'int', 'uint8': 'int', 'uint16': 'int', 'uint32': 'int', 'uint64': 'int', 'bool': 'int', 'float16': 'float', 'float32': 'float', 'float64': 'float'} bad...
64, met type({data.dtype})") else: raise TypeError(f"Unknown type({type(data).__name__})") return (ptr_data, type_data, data) # return `data` to avoid the temporary copy is freed def _get_bad_pandas_dtypes(dtypes):
64
64
153
11
52
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_get_bad_pandas_dtypes
_get_bad_pandas_dtypes
504
512
504
504
19d701a010b4c7082abd47b4f4fd84e2fab77ab9
bigcode/the-stack
train
545fd678e801b61d94ba7bb5
train
class
class _ConfigAliases: aliases = {"bin_construct_sample_cnt": {"bin_construct_sample_cnt", "subsample_for_bin"}, "boosting": {"boosting", "boosting_type", "boost"}, "categorical_feature":...
class _ConfigAliases:
aliases = {"bin_construct_sample_cnt": {"bin_construct_sample_cnt", "subsample_for_bin"}, "boosting": {"boosting", "boosting_type", "boost"}, "categorical_feature": {"categorical_feature...
: raise TypeError(f'Unknown type of parameter:{key}, got:{type(val).__name__}') return ' '.join(pairs) class _TempFile: """Proxy class to workaround errors on Windows.""" def __enter__(self): with NamedTemporaryFile(prefix="lightgbm_tmp_", delete=True) as f: self.name = f....
182
182
609
5
176
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_ConfigAliases
_ConfigAliases
282
375
282
282
9acd5a628eb6b8110ca85c18b847e7ed0c8bf70c
bigcode/the-stack
train
6cf5f82a4e46316aa69175a9
train
function
def c_int_array(data): """Get pointer of int numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.int32: ptr_data = data...
def c_int_array(data):
"""Get pointer of int numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.int32: ptr_data = data.ctypes.data_as(ctypes....
.float32 or np.float64, met type({data.dtype})") else: raise TypeError(f"Unknown type({type(data).__name__})") return (ptr_data, type_data, data) # return `data` to avoid the temporary copy is freed def c_int_array(data):
64
64
211
6
57
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
c_int_array
c_int_array
484
501
484
484
45af34c222536987169c13adbcf372483257b7c0
bigcode/the-stack
train
83830a4bc0f2ece92b40a85b
train
function
def cfloat64_array_to_numpy(cptr, length): """Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected double pointer')
def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected double pointer')
float pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_float)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected float pointer') def cfloat64_array_to_numpy(cptr, length):
64
64
69
12
52
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
cfloat64_array_to_numpy
cfloat64_array_to_numpy
191
196
191
191
341aebfb13d3e7d08632770009958d4d8f4f4af5
bigcode/the-stack
train
cacb212ac465eedb1aebafbe
train
function
def is_numeric(obj): """Check whether object is a number or not, include numpy number, etc.""" try: float(obj) return True except (TypeError, ValueError): # TypeError: obj is not a string or a number # ValueError: invalid literal return False
def is_numeric(obj):
"""Check whether object is a number or not, include numpy number, etc.""" try: float(obj) return True except (TypeError, ValueError): # TypeError: obj is not a string or a number # ValueError: invalid literal return False
Check the return value from C API call. Parameters ---------- ret : int The return value from C API calls. """ if ret != 0: raise LightGBMError(_LIB.LGBM_GetLastError().decode('utf-8')) def is_numeric(obj):
63
64
68
5
58
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
is_numeric
is_numeric
128
136
128
128
7d2cfa72478fc4da9c364b91938c79b49f76c977
bigcode/the-stack
train
4a319657b086547666d52831
train
function
def cast_numpy_1d_array_to_dtype(array, dtype): """Cast numpy 1d array to given dtype.""" if array.dtype == dtype: return array return array.astype(dtype=dtype, copy=False)
def cast_numpy_1d_array_to_dtype(array, dtype):
"""Cast numpy 1d array to given dtype.""" if array.dtype == dtype: return array return array.astype(dtype=dtype, copy=False)
_column_array(data): """Check whether data is a column numpy array.""" if not isinstance(data, np.ndarray): return False shape = data.shape return len(shape) == 2 and shape[1] == 1 def cast_numpy_1d_array_to_dtype(array, dtype):
64
64
47
13
50
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
cast_numpy_1d_array_to_dtype
cast_numpy_1d_array_to_dtype
152
156
152
152
9194b833ef2d6f1b95c2aee8afd06c0588cfb793
bigcode/the-stack
train
5f96ee5e8113e53b31a1d9e8
train
function
def register_logger(logger): """Register custom logger. Parameters ---------- logger : logging.Logger Custom logger. """ if not isinstance(logger, Logger): raise TypeError("Logger should inherit logging.Logger class") global _LOGGER _LOGGER = logger
def register_logger(logger):
"""Register custom logger. Parameters ---------- logger : logging.Logger Custom logger. """ if not isinstance(logger, Logger): raise TypeError("Logger should inherit logging.Logger class") global _LOGGER _LOGGER = logger
c_str(params), ctypes.byref(sample_cnt), )) return sample_cnt.value class _DummyLogger: def info(self, msg): print(msg) def warning(self, msg): warnings.warn(msg, stacklevel=3) _LOGGER = _DummyLogger() def register_logger(logger):
64
64
59
5
59
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
register_logger
register_logger
47
58
47
47
e1b56e22510c057b4f329651723611b038d3fe11
bigcode/the-stack
train
082945a7554c1251f75fa3e4
train
function
def _safe_call(ret): """Check the return value from C API call. Parameters ---------- ret : int The return value from C API calls. """ if ret != 0: raise LightGBMError(_LIB.LGBM_GetLastError().decode('utf-8'))
def _safe_call(ret):
"""Check the return value from C API call. Parameters ---------- ret : int The return value from C API calls. """ if ret != 0: raise LightGBMError(_LIB.LGBM_GetLastError().decode('utf-8'))
) if lib.LGBM_RegisterLogCallback(lib.callback) != 0: raise LightGBMError(lib.LGBM_GetLastError().decode('utf-8')) return lib _LIB = _load_lib() NUMERIC_TYPES = (int, float, bool) def _safe_call(ret):
64
64
66
6
58
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
_safe_call
_safe_call
116
125
116
116
68a2183f4222bcbd33d887e76ee18207575265d1
bigcode/the-stack
train
73d0144479333196a147cbb9
train
function
def json_default_with_numpy(obj): """Convert numpy classes to JSON serializable objects.""" if isinstance(obj, (np.integer, np.floating, np.bool_)): return obj.item() elif isinstance(obj, np.ndarray): return obj.tolist() else: return obj
def json_default_with_numpy(obj):
"""Convert numpy classes to JSON serializable objects.""" if isinstance(obj, (np.integer, np.floating, np.bool_)): return obj.item() elif isinstance(obj, np.ndarray): return obj.tolist() else: return obj
c_str(string): """Convert a Python string to C string.""" return ctypes.c_char_p(string.encode('utf-8')) def c_array(ctype, values): """Convert a Python array to C array.""" return (ctype * len(values))(*values) def json_default_with_numpy(obj):
64
64
60
7
57
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
json_default_with_numpy
json_default_with_numpy
225
232
225
225
167f6a78f59bdb8a1c9ca4f90eeaf40adaa43b4e
bigcode/the-stack
train
a99152dcf91afdba7baf6c02
train
function
def c_str(string): """Convert a Python string to C string.""" return ctypes.c_char_p(string.encode('utf-8'))
def c_str(string):
"""Convert a Python string to C string.""" return ctypes.c_char_p(string.encode('utf-8'))
"""Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int64)): return np.ctypeslib.as_array(cptr, shape=(length,)).copy() else: raise RuntimeError('Expected int64 pointer') def c_str(string):
64
64
28
5
59
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
c_str
c_str
215
217
215
215
cde604911ce974e8ba00f828107a1880d9d7a62a
bigcode/the-stack
train
38608944afc7e94ace85c42d
train
function
def is_numpy_1d_array(data): """Check whether data is a numpy 1-D array.""" return isinstance(data, np.ndarray) and len(data.shape) == 1
def is_numpy_1d_array(data):
"""Check whether data is a numpy 1-D array.""" return isinstance(data, np.ndarray) and len(data.shape) == 1
or not, include numpy number, etc.""" try: float(obj) return True except (TypeError, ValueError): # TypeError: obj is not a string or a number # ValueError: invalid literal return False def is_numpy_1d_array(data):
64
64
39
9
54
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
is_numpy_1d_array
is_numpy_1d_array
139
141
139
139
57825fd4e716d3abeba8bc1a39cbda375ec59cf7
bigcode/the-stack
train
a7056343a7042973f88125b4
train
class
class Booster: """Booster in LightGBM.""" def __init__(self, params=None, train_set=None, model_file=None, model_str=None, silent=False): """Initialize the Booster. Parameters ---------- params : dict or None, optional (default=None) Parameters for Booster. ...
class Booster:
"""Booster in LightGBM.""" def __init__(self, params=None, train_set=None, model_file=None, model_str=None, silent=False): """Initialize the Booster. Parameters ---------- params : dict or None, optional (default=None) Parameters for Booster. train_set : Dat...
self.data = None if self.data is None: err_msg = (f"Cannot add features from {type(other.data).__name__} type of raw data to " f"{old_self_data_type} type of raw data.\n") err_msg += ("Set free_raw_data=False when construct Dataset to avoid this" ...
256
256
11,834
3
252
AWSjswinney/LightGBM
python-package/lightgbm/basic.py
Python
Booster
Booster
2,462
3,842
2,462
2,462
782f8fd50af7993ed1286b908bc53f38f9a68fd1
bigcode/the-stack
train
f023686b3a7f05fc9fcfa44c
train
function
def count_string(str1, str2): same_list = [] for i in str1: for j in str2: if i == j: same_list.append(i) same_list = ' '.join(same_list).split() same_list = set(same_list) print(f"your common letters are {same_list}") num = len(same_list) print(f...
def count_string(str1, str2):
same_list = [] for i in str1: for j in str2: if i == j: same_list.append(i) same_list = ' '.join(same_list).split() same_list = set(same_list) print(f"your common letters are {same_list}") num = len(same_list) print(f"Your words have {num} of the ...
def count_string(str1, str2):
9
64
100
9
0
cjw0621/Growing-Python
Same letter counter.py
Python
count_string
count_string
1
12
1
1
c405906aae89cc3533a3ece3bd86c078315057d0
bigcode/the-stack
train
57bd1e2ebd3900f597fef674
train
function
def ascii_drawer(program, padlen=4, rebind={}): """Creates an ascii circuit from a pyquil program. Idea is to store a single line (a wire) for each qubit as a diciontary to a string. Then a final string is contructed with \n between qubits for printing. Inputs -------------------------------------...
def ascii_drawer(program, padlen=4, rebind={}):
"""Creates an ascii circuit from a pyquil program. Idea is to store a single line (a wire) for each qubit as a diciontary to a string. Then a final string is contructed with \n between qubits for printing. Inputs ------------------------------------------ program: pyquil program padlen: de...
agate = gate if gate in asym: agate += ' ' circ[count][0] += (pad + agate + pad) else: midpad = ''.join('-' for n in range(len(gate))) if gate in asym:...
256
256
973
15
240
obliviateandsurrender/nisqai-dev
src/nisqai/utils/_program_utils.py
Python
ascii_drawer
ascii_drawer
136
233
136
136
84220c008e4b8c5724c7691bb1c9ac29609899ab
bigcode/the-stack
train
b6802dffbb4b099b0e79533a
train
function
def ascii_drawer_simple(program, padlen=2, rebind={'MEASURE': 'MSR'}): """Creates an ascii circuit from a pyquil program. Idea is to store a single line (a wire) for each qubit. Then, we the lists of lists into a string that has gates in order listed in program. Inputs ----------------------------...
def ascii_drawer_simple(program, padlen=2, rebind={'MEASURE': 'MSR'}):
"""Creates an ascii circuit from a pyquil program. Idea is to store a single line (a wire) for each qubit. Then, we the lists of lists into a string that has gates in order listed in program. Inputs ------------------------------------------ program: pyquil program padlen: determines numbe...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
221
256
963
23
198
obliviateandsurrender/nisqai-dev
src/nisqai/utils/_program_utils.py
Python
ascii_drawer_simple
ascii_drawer_simple
24
133
24
24
cc77064fa4206d6eeddb7741cc4a53f1584b82be
bigcode/the-stack
train
a7f5b56b58fa912b5b9d76f5
train
function
def order(program): """Orders Quil instructions into a nominal form.""" # TODO: define nominal form and add more ordering conditions # TODO: right now, this just means all DECLARE statements are at the top return percolate_declares(program)
def order(program):
"""Orders Quil instructions into a nominal form.""" # TODO: define nominal form and add more ordering conditions # TODO: right now, this just means all DECLARE statements are at the top return percolate_declares(program)
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 pyquil.quil import percolate_declares import pyquil def order(program):
64
64
55
4
59
obliviateandsurrender/nisqai-dev
src/nisqai/utils/_program_utils.py
Python
order
order
17
21
17
17
52314a64dfd0aaa5828ac52dd2b4df9e3af7418d
bigcode/the-stack
train
167ea6c5b51135bafade73d6
train
function
def get_menu_option(): """Reads menu option from sys.argv or console. Returns choosen option""" try: if (len(sys.argv) >= 3): op = sys.argv[2] return op else: op = int(input("Option: ")) return op except (ValueError): print ('\nInvalid ...
def get_menu_option():
"""Reads menu option from sys.argv or console. Returns choosen option""" try: if (len(sys.argv) >= 3): op = sys.argv[2] return op else: op = int(input("Option: ")) return op except (ValueError): print ('\nInvalid option. Option should b...
) else: filename = input("\nWhat file do you want to edit? : ") im = Image.open(filename) return (im, filename) except (IOError): print ("\nFile " + filename + " does not exist") exit(0) def get_menu_option():
64
64
83
5
59
Karkanius/MIECT
Ano_1/LabI/Projeto Final - Moura/repositoryContent/simpleImageEditor.py
Python
get_menu_option
get_menu_option
58
68
58
58
676448eab9cff8174ddf9fc577c244aa2d507966
bigcode/the-stack
train
737d2ad7f3f3fa31f7583b22
train
function
def main(): print ("------------------------------") print ("100CÉREBROS - SIMPLE IMAGE EDITOR") option = 0 im, filename = get_file() new_im = prepare_image(filename) while option != -1: # runs indefinitely. Saving the final edited image exits the program directly. print(menu)...
def main():
print ("------------------------------") print ("100CÉREBROS - SIMPLE IMAGE EDITOR") option = 0 im, filename = get_file() new_im = prepare_image(filename) while option != -1: # runs indefinitely. Saving the final edited image exits the program directly. print(menu) opt...
try: if (len(sys.argv) >= 3): op = sys.argv[2] return op else: op = int(input("Option: ")) return op except (ValueError): print ('\nInvalid option. Option should be a number') def main():
64
64
98
3
61
Karkanius/MIECT
Ano_1/LabI/Projeto Final - Moura/repositoryContent/simpleImageEditor.py
Python
main
main
71
84
71
71
7c78003d71b32de6d07207b4fd29f85b30583469
bigcode/the-stack
train
8ebad9201b7bf3e3a34bad42
train
function
def get_file(): """Creates image object from sys.argv or from console. Returns image and filename""" try: if (len(sys.argv) >= 2): filename = sys.argv[1] im = Image.open(filename) return (im, filename) else: filename = input("\nWhat file do you wan...
def get_file():
"""Creates image object from sys.argv or from console. Returns image and filename""" try: if (len(sys.argv) >= 2): filename = sys.argv[1] im = Image.open(filename) return (im, filename) else: filename = input("\nWhat file do you want to edit? : ") ...
S 21 - Old photo 22 - Pencil drawing 23 - Color drawing 24 - Circles black 25 - Circles white CONTROLS 0 - SAVE IMAGE and CLOSE ---------------------------------------- """ def get_file():
63
64
115
4
59
Karkanius/MIECT
Ano_1/LabI/Projeto Final - Moura/repositoryContent/simpleImageEditor.py
Python
get_file
get_file
42
55
42
42
30b1f766e1349f43a017169de3ff756545c97a8f
bigcode/the-stack
train
95a7d6202e1d9bb782514305
train
function
def grid_to_triangle(grid): grid_shape = grid.size() num = (grid_shape[0] - 1) * (grid_shape[1] - 1) upper_triangle = grid[:-1, :-1, :, None] upper_triangle = torch.cat(( upper_triangle, grid[1:, :-1, :, None]), dim = 3) upper_triangle = torch.cat(( upper_triangle, grid[:-1, 1:, :, None]), dim = 3)...
def grid_to_triangle(grid):
grid_shape = grid.size() num = (grid_shape[0] - 1) * (grid_shape[1] - 1) upper_triangle = grid[:-1, :-1, :, None] upper_triangle = torch.cat(( upper_triangle, grid[1:, :-1, :, None]), dim = 3) upper_triangle = torch.cat(( upper_triangle, grid[:-1, 1:, :, None]), dim = 3) upper_triangle = upper_...
3,:2,:2] = 0 image = torch.unsqueeze(image, 0).to(device) grid_merge = torch.unsqueeze(grid_merge, 0) image = torch.nn.functional.grid_sample(image, grid_merge) # default bilinear image = torch.squeeze(image, 0) return image.cpu() def grid_to_triangle(grid):
74
74
249
6
68
laoyuer/deep-stabilization
dvs/warp/rasterizer.py
Python
grid_to_triangle
grid_to_triangle
73
89
73
73
97c281711a875f1db1f74290414ff560d52eb3ac
bigcode/the-stack
train
539223d16ae637530f596daf
train
function
def Rasterization(image, grid, get_mesh_only = False): # grid xy WH shape = image.size() height = shape[1] width = shape[2] wapper_upper_triangle, wapper_lower_triangle = grid_to_triangle(grid[:,:,:2]) origin_upper_triangle, origin_lower_triangle = grid_to_triangle(grid[:,:,2:]) [xmax, xmi...
def Rasterization(image, grid, get_mesh_only = False): # grid xy WH
shape = image.size() height = shape[1] width = shape[2] wapper_upper_triangle, wapper_lower_triangle = grid_to_triangle(grid[:,:,:2]) origin_upper_triangle, origin_lower_triangle = grid_to_triangle(grid[:,:,2:]) [xmax, xmin, ymax, ymin], xlength, ylength = grid_size(wapper_upper_triangle, wapp...
import numpy as np import matplotlib.pyplot as plt from numpy import array import torch import cv2 import time device = torch.device("cuda") def Rasterization(image, grid, get_mesh_only = False): # grid xy WH
52
243
810
19
33
laoyuer/deep-stabilization
dvs/warp/rasterizer.py
Python
Rasterization
Rasterization
10
71
10
11
16f24c93f5210b967dae82c12de515156a6d8422
bigcode/the-stack
train
2b1636bdbea364a2b677d10f
train
function
def triangle2mask(d, height, width): # d: [N x T x 3 x 2] N = d.size()[0] # batch size T = d.size()[1] # triangle number P = height * width # The number of pixels in the output image. area = edgefunc(d[:, :, 1, :], d[:, :, 2, :], d[:, :, None, 0, :]) gridcpu = generate_mesh_grid(height, width) ...
def triangle2mask(d, height, width): # d: [N x T x 3 x 2]
N = d.size()[0] # batch size T = d.size()[1] # triangle number P = height * width # The number of pixels in the output image. area = edgefunc(d[:, :, 1, :], d[:, :, 2, :], d[:, :, None, 0, :]) gridcpu = generate_mesh_grid(height, width) gridcpu = np.reshape(gridcpu, (height*width, 2)) ...
Create a grid of sampling positions xs = np.linspace(0, 1, width, endpoint=False) ys = np.linspace(0, 1, height, endpoint=False) xmesh, ymesh = np.meshgrid(xs, ys) # Reshape the sampling positions to a H x W x 2 tensor return np.moveaxis(array(list(zip(xmesh, ymesh))), 1, 2) def triangle2mask(d, he...
114
114
381
24
90
laoyuer/deep-stabilization
dvs/warp/rasterizer.py
Python
triangle2mask
triangle2mask
111
141
111
111
bfba8eb40d360fb1b702bb047f7bbabe625366ba
bigcode/the-stack
train
d41ffb9cbd1c1d8d5e7f7872
train
function
def generate_mesh_grid(height, width): # Create a grid of sampling positions xs = np.linspace(0, 1, width, endpoint=False) ys = np.linspace(0, 1, height, endpoint=False) xmesh, ymesh = np.meshgrid(xs, ys) # Reshape the sampling positions to a H x W x 2 tensor return np.moveaxis(array(list(zip(xm...
def generate_mesh_grid(height, width): # Create a grid of sampling positions
xs = np.linspace(0, 1, width, endpoint=False) ys = np.linspace(0, 1, height, endpoint=False) xmesh, ymesh = np.meshgrid(xs, ys) # Reshape the sampling positions to a H x W x 2 tensor return np.moveaxis(array(list(zip(xmesh, ymesh))), 1, 2)
1)[0]) xlength = int(torch.max(xmax - xmin)) ylength = int(torch.max(ymax - ymin)) return [xmax, xmin, ymax, ymin], xlength, ylength def generate_mesh_grid(height, width): # Create a grid of sampling positions
64
64
100
17
46
laoyuer/deep-stabilization
dvs/warp/rasterizer.py
Python
generate_mesh_grid
generate_mesh_grid
103
109
103
104
31673813a17f656a94729459e52bc8787dd94b40
bigcode/the-stack
train
b7b20ded58a0636c47cb71ec
train
function
def edgefunc(v0, v1, p): """ let P = H * W v0 and v1 have vertex positions for all T triangles. Their shapes are [N x T X 2] p is a list of sampling points as a [N x T X P x 2] tensor. Each of the T triangles has an [P x 2] matrix of sampling points. returns a [N x T x P] matrix """ ...
def edgefunc(v0, v1, p):
""" let P = H * W v0 and v1 have vertex positions for all T triangles. Their shapes are [N x T X 2] p is a list of sampling points as a [N x T X P x 2] tensor. Each of the T triangles has an [P x 2] matrix of sampling points. returns a [N x T x P] matrix """ P = p.size()[2] ...
[N x P] mask = (w0 > 0) & (w1 > 0) & (w2 > 0) mask = torch.unsqueeze(mask, 3).type(torch.cuda.FloatTensor) w = torch.stack((w0,w1,w2),dim = 3) * mask return torch.transpose(w, 1, 2) # [N x P x T x 3] def edgefunc(v0, v1, p):
102
103
344
11
91
laoyuer/deep-stabilization
dvs/warp/rasterizer.py
Python
edgefunc
edgefunc
144
170
144
144
9c062e1175c37ffdf879d2554e224c2f901e4722
bigcode/the-stack
train
53faa03701807132d8a7c84e
train
function
def grid_size(upper_triangle, lower_triangle, height, width): wapper_grid = torch.cat((upper_triangle, lower_triangle),dim =1) xmax = torch.floor(torch.max(wapper_grid[:,:,0]*width, 1)[0]) + 1 ymax = torch.floor(torch.max(wapper_grid[:,:,1]*height, 1)[0]) + 1 xmin = torch.floor(torch.min(wapper_grid[:,:...
def grid_size(upper_triangle, lower_triangle, height, width):
wapper_grid = torch.cat((upper_triangle, lower_triangle),dim =1) xmax = torch.floor(torch.max(wapper_grid[:,:,0]*width, 1)[0]) + 1 ymax = torch.floor(torch.max(wapper_grid[:,:,1]*height, 1)[0]) + 1 xmin = torch.floor(torch.min(wapper_grid[:,:,0]*width, 1)[0]) ymin = torch.floor(torch.min(wapper_grid...
= 3) lower_triangle = lower_triangle.view(num, 2, 3) lower_triangle = torch.transpose(lower_triangle, 1, 2) return upper_triangle, lower_triangle # grid * point * xy def grid_size(upper_triangle, lower_triangle, height, width):
64
64
162
14
49
laoyuer/deep-stabilization
dvs/warp/rasterizer.py
Python
grid_size
grid_size
91
101
91
91
94a7404e8401dc03c452b6c284159262f49d336c
bigcode/the-stack
train
b25ef9735123803a7c67d381
train
function
def test_user_maps_info(): """User can get their own identities at /users/{username}/identities""" global AUTH_COOKIE http = httplib2.Http() # auth required response, content = http.request( 'http://0.0.0.0:8080/users/cdent/identities', method='GET') assert response['status'...
def test_user_maps_info():
"""User can get their own identities at /users/{username}/identities""" global AUTH_COOKIE http = httplib2.Http() # auth required response, content = http.request( 'http://0.0.0.0:8080/users/cdent/identities', method='GET') assert response['status'] == '401' # user can get ...
assert 'username exists' in content def test_user_may_not_map_self(): """Make user X can't map user Y to themselves.""" global AUTH_COOKIE second_cookie = make_cookie('tiddlyweb_secondary_user', 'cdent', mac_key=secret) http = httplib2.Http() response, content = http.request( ...
170
170
568
6
163
TiddlySpace/tiddlyspace
test/test_mapuser_validate.py
Python
test_user_maps_info
test_user_maps_info
176
233
176
176
f575837c14574b76a5b7bcc068579ae78091a9c2
bigcode/the-stack
train
267abc3e81a2f77739bd5c35
train
function
def test_user_may_not_map_self(): """Make user X can't map user Y to themselves.""" global AUTH_COOKIE second_cookie = make_cookie('tiddlyweb_secondary_user', 'cdent', mac_key=secret) http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/bags/MAPUSER/t...
def test_user_may_not_map_self():
"""Make user X can't map user Y to themselves.""" global AUTH_COOKIE second_cookie = make_cookie('tiddlyweb_secondary_user', 'cdent', mac_key=secret) http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/cdent', method...
-Type': 'application/json', 'Cookie': 'tiddlyweb_user="%s"; %s' % ( AUTH_COOKIE, second_cookie)}, body='{}') assert response['status'] == '409' assert 'username exists' in content def test_user_may_not_map_self():
64
64
155
9
54
TiddlySpace/tiddlyspace
test/test_mapuser_validate.py
Python
test_user_may_not_map_self
test_user_may_not_map_self
159
173
159
159
5ef123a97179944ae162e771f5112351d5195129
bigcode/the-stack
train
172d7eb2efdf2cb5d37b55cd
train
function
def test_user_may_not_map_user(): """Make user X can't map user Y to themselves.""" global AUTH_COOKIE second_cookie = make_cookie('tiddlyweb_secondary_user', 'fnd', mac_key=secret) http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/bags/MAPUSER/tid...
def test_user_may_not_map_user():
"""Make user X can't map user Y to themselves.""" global AUTH_COOKIE second_cookie = make_cookie('tiddlyweb_secondary_user', 'fnd', mac_key=secret) http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/fnd', method='PU...
': 'application/json', 'Cookie': 'tiddlyweb_user="%s"; %s' % ( AUTH_COOKIE, second_cookie)}, body='{}') assert response['status'] == '403' assert 'may not write' in content def test_user_may_not_map_user():
64
64
155
9
54
TiddlySpace/tiddlyspace
test/test_mapuser_validate.py
Python
test_user_may_not_map_user
test_user_may_not_map_user
142
156
142
142
a1d7b61eef5a0aab35e91468986efa1cdd6e0dfd
bigcode/the-stack
train
eed8951ab3726358be0ff99e
train
function
def test_create_map_uses_user(): global AUTH_COOKIE http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form', body='user=cdent&password=cow', method='POST', headers={'Content-Type': 'appl...
def test_create_map_uses_user():
global AUTH_COOKIE http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form', body='user=cdent&password=cow', method='POST', headers={'Content-Type': 'application/x-www-form-urlencoded'}) ...
plib2 import Cookie import simplejson from wsgi_intercept import httplib2_intercept from tiddlyweb.model.user import User from tiddlyweb.model.tiddler import Tiddler from tiddlyweb.web.util import make_cookie from test.fixtures import make_test_env AUTH_COOKIE = None def setup_module(module): make_test_env(m...
256
256
901
8
248
TiddlySpace/tiddlyspace
test/test_mapuser_validate.py
Python
test_create_map_uses_user
test_create_map_uses_user
54
139
54
54
129d1700e4f569e735aab893357d407ed4c8aeff
bigcode/the-stack
train
443cff04201694d2012b28a2
train
function
def setup_module(module): make_test_env(module) from tiddlyweb.config import config module.secret = config['secret'] httplib2_intercept.install() wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn) user = User('cdent') user.set_password('cow') module.store.put(user) user = Use...
def setup_module(module):
make_test_env(module) from tiddlyweb.config import config module.secret = config['secret'] httplib2_intercept.install() wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn) user = User('cdent') user.set_password('cow') module.store.put(user) user = User('fnd') module.store....
sgi_intercept import httplib2_intercept from tiddlyweb.model.user import User from tiddlyweb.model.tiddler import Tiddler from tiddlyweb.web.util import make_cookie from test.fixtures import make_test_env AUTH_COOKIE = None def setup_module(module):
64
64
97
5
58
TiddlySpace/tiddlyspace
test/test_mapuser_validate.py
Python
setup_module
setup_module
30
40
30
30
2ecf9addf6ee8d793fa8128098022d96c5a8095d
bigcode/the-stack
train
91c6e7aefa284f6f565b5b6e
train
function
def test_create_map_requires_user(): http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing', method='PUT', headers={'Content-Type': 'application/json'}, body='{}') assert response['status'] == '403'
def test_create_map_requires_user():
http = httplib2.Http() response, content = http.request( 'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing', method='PUT', headers={'Content-Type': 'application/json'}, body='{}') assert response['status'] == '403'
_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn) user = User('cdent') user.set_password('cow') module.store.put(user) user = User('fnd') module.store.put(user) def test_create_map_requires_user():
64
64
80
7
57
TiddlySpace/tiddlyspace
test/test_mapuser_validate.py
Python
test_create_map_requires_user
test_create_map_requires_user
43
51
43
43
4ccfc29300361781867633777b1e616d072ea0ad
bigcode/the-stack
train
5d90323848ad08802b9ffa14
train
class
class QueueFairLogger: @staticmethod def log(message): print("QF "+message)
class QueueFairLogger: @staticmethod
def log(message): print("QF "+message)
class QueueFairLogger: @staticmethod
9
64
22
9
0
Queue-Fair/python
queue_fair_adapter/queue_fair_logger.py
Python
QueueFairLogger
QueueFairLogger
1
5
1
3
b4ef61aaae07622b270c48805024667b7c43fbe9
bigcode/the-stack
train
8f11d02dc6f995da51ad7ea8
train
class
class TinySegmenter(object): default_model = {u'BC1':{u'II':-1369,u'IO':1532,u'KK':-1817,u'NO':579,u'OH':1274,u'ON':657,u'OO':-616},u'BC2':{u'AA':-17066,u'IH':-520,u'II':-613,u'KH':919,u'KI':-40,u'KK':-3853,u'NN':-1340,u'OI':92},u'BC3':{u'IK':200,u'IO':39,u'OH':-131},u'BIAS':1188,u'BP1':{u'BB':-41,u'BO':-446,u'OB':...
class TinySegmenter(object):
default_model = {u'BC1':{u'II':-1369,u'IO':1532,u'KK':-1817,u'NO':579,u'OH':1274,u'ON':657,u'OO':-616},u'BC2':{u'AA':-17066,u'IH':-520,u'II':-613,u'KH':919,u'KI':-40,u'KK':-3853,u'NN':-1340,u'OI':92},u'BC3':{u'IK':200,u'IO':39,u'OH':-131},u'BIAS':1188,u'BP1':{u'BB':-41,u'BO':-446,u'OB':95,u'OO':-152,u'UO':5088},u'B...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ TinySegmenter 0.1 -- Super compact Japanese tokenizer in Javascript (c) 2008 Taku Kudo <taku@chasen.org> TinySegmenter is freely distributable under the terms of a new BSD licence. For details, see http://chasen.org/~taku/software/TinySegmenter/LICENCE.txt """ import ...
114
256
5,113
6
107
shinichi-kato/corpusenactor_echo-0.1.1
lib/tinysegmenter.py
Python
TinySegmenter
TinySegmenter
18
129
18
18
118cd747980b937fb4276430f77b4af3dfc2802e
bigcode/the-stack
train
73b2140014136052660f6838
train
function
def main(): """ Startup """ window = arcade.Window(1600, 900, "Asteroids", fullscreen=False) Game_View = GameView() window.show_view(Game_View) arcade.run()
def main():
""" Startup """ window = arcade.Window(1600, 900, "Asteroids", fullscreen=False) Game_View = GameView() window.show_view(Game_View) arcade.run()
.color.WHITE, font_size=25, anchor_x="center") def on_key_press(self, key, _modifiers): """Drücke Leertaste um fortzufahren""" if key == arcade.key.SPACE: self.game_over = True print ("Game Over") def main():
63
64
45
3
60
software-engineering-hsfhh/Asteroids_Team_All-Mann
Test.py
Python
main
main
60
65
60
60
256c5c820b1ec149a3a29a665c03b7969d03efb3
bigcode/the-stack
train
baa5440f5dcf37cd07ad4b05
train
class
class GameView(arcade.View): """ Manage the 'game' view for our program. """ def __init__(self): super().__init__() # Create variables here def setup(self): """ This should set up your game and get it ready to play """ # Replace 'pass' with the code to set up your game ...
class GameView(arcade.View):
""" Manage the 'game' view for our program. """ def __init__(self): super().__init__() # Create variables here def setup(self): """ This should set up your game and get it ready to play """ # Replace 'pass' with the code to set up your game pass def on_show(sel...
, simply create a View with `view = MyView()` and then use the "self.window.set_view(view)" method. If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.view_screens_minimal """ import arcade WIDTH = 1600 HEIGHT = 900 class GameView(arcade.View):
78
78
260
8
69
software-engineering-hsfhh/Asteroids_Team_All-Mann
Test.py
Python
GameView
GameView
27
55
27
27
1ae4144f6decfa0977cb32cf851678ce95a3f912
bigcode/the-stack
train
811639f776e52d10b05c1069
train
class
class LED: ''' Toggle a GPIO pin for led control ''' def __init__(self, pin): self.pin = pin GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) self.blink_changed = 0 self.on = False def toggle(self, condition): if condition: GPIO.o...
class LED:
''' Toggle a GPIO pin for led control ''' def __init__(self, pin): self.pin = pin GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pin, GPIO.OUT) self.blink_changed = 0 self.on = False def toggle(self, condition): if condition: GPIO.output(self....
import time import RPi.GPIO as GPIO class LED:
13
64
207
3
9
tikisi/donkeycar
donkeycar/parts/led_status.py
Python
LED
LED
4
39
4
4
c84cfaf8d16d5c9e926aea352b60f19d882c7ec1
bigcode/the-stack
train
58828fdbe3ab9885bd2bbdf5
train
class
class RGB_LED: ''' Toggle a GPIO pin on at max_duty pwm if condition is true, off if condition is false. Good for LED pwm modulated ''' def __init__(self, pin_r, pin_g, pin_b, invert_flag=False): self.pin_r = pin_r self.pin_g = pin_g self.pin_b = pin_b self.invert = ...
class RGB_LED:
''' Toggle a GPIO pin on at max_duty pwm if condition is true, off if condition is false. Good for LED pwm modulated ''' def __init__(self, pin_r, pin_g, pin_b, invert_flag=False): self.pin_r = pin_r self.pin_g = pin_g self.pin_b = pin_b self.invert = invert_flag ...
, GPIO.OUT) self.blink_changed = 0 self.on = False def toggle(self, condition): if condition: GPIO.output(self.pin, GPIO.HIGH) self.on = True else: GPIO.output(self.pin, GPIO.LOW) self.on = False def blink(self, rate):...
165
165
552
4
161
tikisi/donkeycar
donkeycar/parts/led_status.py
Python
RGB_LED
RGB_LED
42
110
42
42
da22bb1b5a51d53ceb3e6724c04450ce27b070d9
bigcode/the-stack
train
3937b5dd0c0c9a4d57697788
train
function
def read_ctd(file, **kwargs): """Check for file type and call respective reader function.""" print('read CTD file now... ', end='') # select reader function based on first line of file with open(file, 'r') as f: line = f.readline().rstrip() # yields the first non-empty line whi...
def read_ctd(file, **kwargs):
"""Check for file type and call respective reader function.""" print('read CTD file now... ', end='') # select reader function based on first line of file with open(file, 'r') as f: line = f.readline().rstrip() # yields the first non-empty line while not line: line ...
schel.de # Date: 07/03/2019 # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # from __future__ import division, print_function, absolute_import import io import numpy as np import pandas as pd import xmltodict import re def read_ctd(file, **kwargs):
64
64
195
9
54
markusritschel/mpi_icelab_routines
ctds/read_routines.py
Python
read_ctd
read_ctd
20
44
20
20
624b3943f098e18614ab2e18ae26a119e23c9d44
bigcode/the-stack
train
c973286d012ac97e2d0a402e
train
function
def read_rbr(file, nan_flag=-1000., **kwargs): """Read RBR CTD internal log file. Parameters ---------- file : str Path to the log file which shall be parsed. nan_flag : float Float which marks a missing entry in the log file. kwargs['verbose'] : bool Optionally print out...
def read_rbr(file, nan_flag=-1000., **kwargs):
"""Read RBR CTD internal log file. Parameters ---------- file : str Path to the log file which shall be parsed. nan_flag : float Float which marks a missing entry in the log file. kwargs['verbose'] : bool Optionally print out header information of the log file. Retur...
if var in df.columns]] df = df.reindex(sorted(map(str.lower, df.columns)), axis=1) # set nan_flag as NAN df[df == nan_flag] = np.nan if 'verbose' in kwargs: print('{:<11}:'.format('Start time'), start_time) print('{:<11}:'.format('End time '), time_idx[-1]) print('{:<11}:'.f...
192
192
640
15
176
markusritschel/mpi_icelab_routines
ctds/read_routines.py
Python
read_rbr
read_rbr
197
277
197
197
c17b0309e16582b913636e8ca68f62b19ecba7e4
bigcode/the-stack
train
7c53195ac637f790ce1c9761
train
function
def read_seabird_serial_log(file, **kwargs): """Return xarray.Dataset""" with open(file, 'r') as f: lines = filter(None, (line.rstrip() for line in f)) # omit empty lines lines = list((line.lstrip('#') for line in lines)) col_names = ['Temperature', 'Conductivity', 'Pressure', 'date', 'tim...
def read_seabird_serial_log(file, **kwargs):
"""Return xarray.Dataset""" with open(file, 'r') as f: lines = filter(None, (line.rstrip() for line in f)) # omit empty lines lines = list((line.lstrip('#') for line in lines)) col_names = ['Temperature', 'Conductivity', 'Pressure', 'date', 'time'] # Salinity is not included by default...
td_reader_func = read_seabird elif line.startswith('RBR'): ctd_reader_func = read_rbr elif re.match(r"^#\s+(-*\d+\.\d+,\s+)+", line): ctd_reader_func = read_seabird_serial_log df = ctd_reader_func(file, **kwargs) print('done') return df def read_seabird_serial_log(...
98
98
329
12
85
markusritschel/mpi_icelab_routines
ctds/read_routines.py
Python
read_seabird_serial_log
read_seabird_serial_log
47
78
47
47
aad9e668957554e028410753d19c97e397dff6da
bigcode/the-stack
train
b898ddf1c017fe67c7c75794
train
function
def read_seabird(file: str, nan_flag=-9.990e-29, **kwargs): """Read SeaBird CTD internal log file. Parameters ---------- file : str Path to the log file which shall be parsed. nan_flag : float Float which marks a missing entry in the log file. kwargs['verbose'] : bool Opt...
def read_seabird(file: str, nan_flag=-9.990e-29, **kwargs):
"""Read SeaBird CTD internal log file. Parameters ---------- file : str Path to the log file which shall be parsed. nan_flag : float Float which marks a missing entry in the log file. kwargs['verbose'] : bool Optionally print out header information of the log file. R...
. Can be changed in SeaTerm (under Windows) if len(lines[0].split(',')) == 6: col_names.insert(3, 'Salinity') units = {'Temperature': '°C', 'Conductivity': 'S/m', 'Pressure': 'dbar', 'Salinity': 'psu'} df = pd.read_csv(io.StringIO('\n'.join(lines)), ...
256
256
1,024
22
233
markusritschel/mpi_icelab_routines
ctds/read_routines.py
Python
read_seabird
read_seabird
81
194
81
81
65c03d5aa0925fcb3a2d07363141d9139ac31a2d
bigcode/the-stack
train
55d746db110aab351469de78
train
class
class GenericTransfer(BaseOperator): """ Moves data from a connection to another, assuming that they both provide the required methods in their respective hooks. The source hook needs to expose a `get_records` method, and the destination a `insert_rows` method. This is mean to be used on small-...
class GenericTransfer(BaseOperator):
""" Moves data from a connection to another, assuming that they both provide the required methods in their respective hooks. The source hook needs to expose a `get_records` method, and the destination a `insert_rows` method. This is mean to be used on small-ish datasets that fit in memory. ...
"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES...
136
136
454
6
129
Pire66/jedi.bigdata.1
airflow/operators/generic_transfer.py
Python
GenericTransfer
GenericTransfer
22
78
22
22
454fb72ca5e563c3c5b0ee32a7255e89e6b07ddb
bigcode/the-stack
train
6b9e751a12e23bdd128c226a
train
function
def get_count_of_copyrights_of_any_style_any_holder(contents): return len(ANY_COPYRIGHT_COMPILED.findall(contents))
def get_count_of_copyrights_of_any_style_any_holder(contents):
return len(ANY_COPYRIGHT_COMPILED.findall(contents))
_name)) WITHOUT_C_STYLE_COMPILED[holder_name] = ( compile_copyright_regex(COPYRIGHT_WITHOUT_C, ANY_YEAR_STYLE, holder_name)) ################################################################################ # search file contents for copyright message of particular category #...
64
64
27
14
49
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_count_of_copyrights_of_any_style_any_holder
get_count_of_copyrights_of_any_style_any_holder
127
128
127
127
400ba2ce041f0da894cdab78867e92792675aa6a
bigcode/the-stack
train
ed3c4570819ffc44c5a24fa3
train
function
def get_filenames_to_examine(): filenames = call_git_ls() return sorted([filename for filename in filenames if applies_to_file(filename)])
def get_filenames_to_examine():
filenames = call_git_ls() return sorted([filename for filename in filenames if applies_to_file(filename)])
################################################################################ GIT_LS_CMD = 'git ls-files' def call_git_ls(): out = subprocess.check_output(GIT_LS_CMD.split(' ')) return [f for f in out.decode("utf-8").split('\n') if f != ''] def get_filenames_to_examine():
64
64
32
8
56
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_filenames_to_examine
get_filenames_to_examine
58
61
58
58
3087fac2badd6b7aba7cd5672f46d8f2960d1b2b
bigcode/the-stack
train
d205ee66ffbaf89a6b849d33
train
function
def file_has_without_c_style_copyright_for_holder(contents, holder_name): match = WITHOUT_C_STYLE_COMPILED[holder_name].search(contents) return match is not None
def file_has_without_c_style_copyright_for_holder(contents, holder_name):
match = WITHOUT_C_STYLE_COMPILED[holder_name].search(contents) return match is not None
].search(contents) return match is not None def file_has_year_list_style_copyright_for_holder(contents, holder_name): match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents) return match is not None def file_has_without_c_style_copyright_for_holder(contents, holder_name):
64
64
38
15
48
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
file_has_without_c_style_copyright_for_holder
file_has_without_c_style_copyright_for_holder
138
140
138
138
48ba9cf2559a054e752341e562cf49931ff667e6
bigcode/the-stack
train
d589f0e67e0ba9780ecddb8f
train
function
def applies_to_file(filename): return ((EXCLUDE_COMPILED.match(filename) is None) and (INCLUDE_COMPILED.match(filename) is not None))
def applies_to_file(filename):
return ((EXCLUDE_COMPILED.match(filename) is None) and (INCLUDE_COMPILED.match(filename) is not None))
re.compile('|'.join([fnmatch.translate(m) for m in EXCLUDE])) INCLUDE = ['*.h', '*.cpp', '*.cc', '*.c', '*.py'] INCLUDE_COMPILED = re.compile('|'.join([fnmatch.translate(m) for m in INCLUDE])) def applies_to_file(filename):
64
64
36
6
58
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
applies_to_file
applies_to_file
44
46
44
44
a5d4d3741d5ef5d6d1c496ae7feacfb7bc09a285
bigcode/the-stack
train
406b13112bd08c6d5df81b40
train
function
def print_filenames(filenames, verbose): if not verbose: return for filename in filenames: print("\t%s" % filename)
def print_filenames(filenames, verbose):
if not verbose: return for filename in filenames: print("\t%s" % filename)
_list_style or has_without_c_style: info['classified_copyrights'] = info['classified_copyrights'] + 1 return info ################################################################################ # report execution ################################################################################ SEPARAT...
64
64
32
9
55
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
print_filenames
print_filenames
181
185
181
181
c5e86933914a18311363f14dad98181d60e9b2ab
bigcode/the-stack
train
2b55d1ea34e49c2acb4e0ec0
train
function
def exec_update_header_year(base_directory): original_cwd = os.getcwd() os.chdir(base_directory) for filename in get_filenames_to_examine(): update_updatable_copyright(filename) os.chdir(original_cwd)
def exec_update_header_year(base_directory):
original_cwd = os.getcwd() os.chdir(base_directory) for filename in get_filenames_to_examine(): update_updatable_copyright(filename) os.chdir(original_cwd)
print_file_action_message(filename, "Copyright up-to-date.") return file_lines[index] = new_line write_file_lines(filename, file_lines) print_file_action_message(filename, "Copyright updated! -> %s" % last_git_change_year) def exec_update_header_year(base_direct...
64
64
48
8
56
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
exec_update_header_year
exec_update_header_year
399
404
399
399
0c36da64670844167b46a68c0d14c5ec51f61377
bigcode/the-stack
train
3e71bc9304f0ba1c327164d1
train
function
def print_file_action_message(filename, action): print("%-52s %s" % (filename, action))
def print_file_action_message(filename, action):
print("%-52s %s" % (filename, action))
Copyright (c) <year>-<lastModifiedYear> The Bitcoin Core developers where the update is appropriate. Usage: $ ./copyright_header.py update <base_directory> Arguments: <base_directory> - The base directory of a luk source code repository. """ def print_file_action_message(filename, action):
64
64
24
9
55
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
print_file_action_message
print_file_action_message
439
440
439
439
c515f082d61d3fda6af13f8156b15805fb7c188d
bigcode/the-stack
train
20797a9bf76d272ef25647c8
train
function
def compile_copyright_regex(copyright_style, year_style, name): return re.compile('%s %s %s' % (copyright_style, year_style, name))
def compile_copyright_regex(copyright_style, year_style, name):
return re.compile('%s %s %s' % (copyright_style, year_style, name))
(YEAR_RANGE, YEAR_LIST) ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE = ("%s %s" % (ANY_COPYRIGHT_STYLE, ANY_YEAR_STYLE)) ANY_COPYRIGHT_COMPILED = re.compile(ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE) def compile_copyright_regex(copyright_style, year_style, name):
64
64
35
14
50
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
compile_copyright_regex
compile_copyright_regex
81
82
81
81
5411bb081a899acde3acef295b0a3ab1dd8ac85c
bigcode/the-stack
train
301ccc0b57a716c9f4db913b
train
function
def insert_cpp_header(filename, file_lines, start_year, end_year): header_lines = get_cpp_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(0, line) write_file_lines(filename, file_lines)
def insert_cpp_header(filename, file_lines, start_year, end_year):
header_lines = get_cpp_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(0, line) write_file_lines(filename, file_lines)
: insert_idx = 0 header_lines = get_python_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(insert_idx, line) write_file_lines(filename, file_lines) def insert_cpp_header(filename, file_lines, start_year, end_year):
64
64
56
15
49
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
insert_cpp_header
insert_cpp_header
515
519
515
515
b4116632c7cfb822aa8d7143964dfcb5bc194f23
bigcode/the-stack
train
7a988e3381d586513eafc223
train
function
def file_has_year_list_style_copyright_for_holder(contents, holder_name): match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents) return match is not None
def file_has_year_list_style_copyright_for_holder(contents, holder_name):
match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents) return match is not None
ANY_COPYRIGHT_COMPILED.findall(contents)) def file_has_dominant_style_copyright_for_holder(contents, holder_name): match = DOMINANT_STYLE_COMPILED[holder_name].search(contents) return match is not None def file_has_year_list_style_copyright_for_holder(contents, holder_name):
64
64
38
15
48
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
file_has_year_list_style_copyright_for_holder
file_has_year_list_style_copyright_for_holder
134
136
134
134
7eb78cb34faab3f414b628bb73957c2a26ccadce
bigcode/the-stack
train
047593c2b2505062247eb61f
train
function
def insert_cmd(argv): if len(argv) != 3: sys.exit(INSERT_USAGE) filename = argv[2] if not os.path.isfile(filename): sys.exit("*** bad filename: %s" % filename) _, extension = os.path.splitext(filename) if extension not in ['.h', '.cpp', '.cc', '.c', '.py']: sys.exit("*** can...
def insert_cmd(argv):
if len(argv) != 3: sys.exit(INSERT_USAGE) filename = argv[2] if not os.path.isfile(filename): sys.exit("*** bad filename: %s" % filename) _, extension = os.path.splitext(filename) if extension not in ['.h', '.cpp', '.cc', '.c', '.py']: sys.exit("*** cannot insert for file ex...
will be set to be: "<current_year>" If the file already has a copyright for "The Bitcoin Core developers", the script will exit. Usage: $ ./copyright_header.py insert <file> Arguments: <file> - A source file in the luk repository. """ def insert_cmd(argv):
64
64
126
5
59
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
insert_cmd
insert_cmd
561
576
561
561
981af39c3e88dd4737ff0965b8579478a7576f7b
bigcode/the-stack
train
61ca6ac06923da4b9e03b004
train
function
def read_file_lines(filename): f = open(os.path.abspath(filename), 'r') file_lines = f.readlines() f.close() return file_lines
def read_file_lines(filename):
f = open(os.path.abspath(filename), 'r') file_lines = f.readlines() f.close() return file_lines
:32 -0600" return [line.split(' ')[0].split('-')[0] for line in git_log_lines] def get_most_recent_git_change_year(filename): return max(get_git_change_years(filename)) ################################################################################ # read and write to file ###################################...
64
64
34
6
57
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
read_file_lines
read_file_lines
325
329
325
325
a2f58da7a5e0b6423a8d5d893348f73ecbda0ef9
bigcode/the-stack
train
c6633ff554efd2aaf6a7ac31
train
function
def call_git_ls(): out = subprocess.check_output(GIT_LS_CMD.split(' ')) return [f for f in out.decode("utf-8").split('\n') if f != '']
def call_git_ls():
out = subprocess.check_output(GIT_LS_CMD.split(' ')) return [f for f in out.decode("utf-8").split('\n') if f != '']
return ((EXCLUDE_COMPILED.match(filename) is None) and (INCLUDE_COMPILED.match(filename) is not None)) ################################################################################ # obtain list of files in repo according to INCLUDE and EXCLUDE #######################################################...
64
64
42
5
59
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
call_git_ls
call_git_ls
54
56
54
54
b475bde529e241e5f875474eca60b850854c01e5
bigcode/the-stack
train
ad7c5841a08b7e32fd1be9e6
train
function
def report_cmd(argv): if len(argv) == 2: sys.exit(REPORT_USAGE) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad <base_directory>: %s" % base_directory) if len(argv) == 3: verbose = False elif argv[3] == 'verbose': verbose = ...
def report_cmd(argv):
if len(argv) == 2: sys.exit(REPORT_USAGE) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad <base_directory>: %s" % base_directory) if len(argv) == 3: verbose = False elif argv[3] == 'verbose': verbose = True else: ...
of a repository. Usage: $ ./copyright_header.py report <base_directory> [verbose] Arguments: <base_directory> - The base directory of a luk source code repository. [verbose] - Includes a list of every file of each subcategory in the report. """ def report_cmd(argv):
64
64
110
5
59
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
report_cmd
report_cmd
284
299
284
284
f37aae9ef41c333d09b13d8a04f9e31c40dc7e4f
bigcode/the-stack
train
e1a43f867f23d7a16b0ccbfe
train
function
def file_has_hashbang(file_lines): if len(file_lines) < 1: return False if len(file_lines[0]) <= 2: return False return file_lines[0][:2] == '#!'
def file_has_hashbang(file_lines):
if len(file_lines) < 1: return False if len(file_lines[0]) <= 2: return False return file_lines[0][:2] == '#!'
), max(years) ################################################################################ # check for existing core copyright ################################################################################ def file_already_has_core_copyright(file_lines): index, _ = get_updatable_copyright_line(file_lines) ...
64
64
50
8
55
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
file_has_hashbang
file_has_hashbang
498
503
498
498
496b73187c352b3720dd832240e264d3bfc4f22e
bigcode/the-stack
train
2b680bcb5b78230ff318b514
train
function
def parse_year_range(year_range): year_split = year_range.split('-') start_year = year_split[0] if len(year_split) == 1: return start_year, start_year return start_year, year_split[1]
def parse_year_range(year_range):
year_split = year_range.split('-') start_year = year_split[0] if len(year_split) == 1: return start_year, start_year return start_year, year_split[1]
get_updatable_copyright_line(file_lines): index = 0 for line in file_lines: if UPDATEABLE_LINE_COMPILED.search(line) is not None: return index, line index = index + 1 return None, None def parse_year_range(year_range):
64
64
53
7
56
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
parse_year_range
parse_year_range
354
359
354
354
fac4b073254119688abb0b5423bfcfaea477ae19
bigcode/the-stack
train
16c282be0cc958a2bbf8e2e9
train
function
def update_cmd(argv): if len(argv) != 3: sys.exit(UPDATE_USAGE) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad base_directory: %s" % base_directory) exec_update_header_year(base_directory)
def update_cmd(argv):
if len(argv) != 3: sys.exit(UPDATE_USAGE) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad base_directory: %s" % base_directory) exec_update_header_year(base_directory)
is appropriate. Usage: $ ./copyright_header.py update <base_directory> Arguments: <base_directory> - The base directory of a luk source code repository. """ def print_file_action_message(filename, action): print("%-52s %s" % (filename, action)) def update_cmd(argv):
64
64
62
5
59
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
update_cmd
update_cmd
442
449
442
442
7d5de3ea35fbe253740427b4228f38022c7a0427
bigcode/the-stack
train
4ee2b2f6db4ed57379238573
train
function
def print_report(file_infos, verbose): print(SEPARATOR) examined = [i['filename'] for i in file_infos] print("%d files examined according to INCLUDE and EXCLUDE fnmatch rules" % len(examined)) print_filenames(examined, verbose) print(SEPARATOR) print('') zero_copyrights = [i['file...
def print_report(file_infos, verbose):
print(SEPARATOR) examined = [i['filename'] for i in file_infos] print("%d files examined according to INCLUDE and EXCLUDE fnmatch rules" % len(examined)) print_filenames(examined, verbose) print(SEPARATOR) print('') zero_copyrights = [i['filename'] for i in file_infos if ...
info['year_list_style'] = {} info['without_c_style'] = {} for holder_name in EXPECTED_HOLDER_NAMES: has_dominant_style = ( file_has_dominant_style_copyright_for_holder(c, holder_name)) has_year_list_style = ( file_has_year_list_style_copyright_for_holder(c, holder_nam...
251
251
837
8
243
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
print_report
print_report
187
258
187
187
388945ff1db24c23eb5714edf0b5fa2931eee621
bigcode/the-stack
train
b6c1e07e82225c92993e8fe4
train
function
def exec_report(base_directory, verbose): original_cwd = os.getcwd() os.chdir(base_directory) filenames = get_filenames_to_examine() file_infos = [gather_file_info(f) for f in filenames] print_report(file_infos, verbose) os.chdir(original_cwd)
def exec_report(base_directory, verbose):
original_cwd = os.getcwd() os.chdir(base_directory) filenames = get_filenames_to_examine() file_infos = [gather_file_info(f) for f in filenames] print_report(file_infos, verbose) os.chdir(original_cwd)
file_infos if i['classified_copyrights'] < i['all_copyrights']] print("%d with unexpected copyright holder names" % len(unclassified_copyrights)) print_filenames(unclassified_copyrights, verbose) print(SEPARATOR) def exec_report(base_directory, verbose):
64
64
63
8
56
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
exec_report
exec_report
260
266
260
260
2575d4114347be9f65bc0133a969014e417818ae
bigcode/the-stack
train
6cd1f65cc69662700aa6226b
train
function
def insert_python_header(filename, file_lines, start_year, end_year): if file_has_hashbang(file_lines): insert_idx = 1 else: insert_idx = 0 header_lines = get_python_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(insert_idx, line) wr...
def insert_python_header(filename, file_lines, start_year, end_year):
if file_has_hashbang(file_lines): insert_idx = 1 else: insert_idx = 0 header_lines = get_python_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(insert_idx, line) write_file_lines(filename, file_lines)
_has_hashbang(file_lines): if len(file_lines) < 1: return False if len(file_lines[0]) <= 2: return False return file_lines[0][:2] == '#!' def insert_python_header(filename, file_lines, start_year, end_year):
63
64
82
15
48
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
insert_python_header
insert_python_header
505
513
505
505
718b34d334920d2aeff6aa0370bf6346ca4cbe26
bigcode/the-stack
train
07b8b8e9ece014702466165d
train
function
def get_git_change_years(filename): git_log_lines = call_git_log(filename) if len(git_log_lines) == 0: return [datetime.date.today().year] # timestamp is in ISO 8601 format. e.g. "2016-09-05 14:25:32 -0600" return [line.split(' ')[0].split('-')[0] for line in git_log_lines]
def get_git_change_years(filename):
git_log_lines = call_git_log(filename) if len(git_log_lines) == 0: return [datetime.date.today().year] # timestamp is in ISO 8601 format. e.g. "2016-09-05 14:25:32 -0600" return [line.split(' ')[0].split('-')[0] for line in git_log_lines]
################################################################################ GIT_LOG_CMD = "git log --pretty=format:%%ai %s" def call_git_log(filename): out = subprocess.check_output((GIT_LOG_CMD % filename).split(' ')) return out.decode("utf-8").split('\n') def get_git_change_years(filename):
64
64
91
8
56
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_git_change_years
get_git_change_years
311
316
311
311
654de7f0a07f6f7583e879005671e0f471f77955
bigcode/the-stack
train
f537d5fd8f35ad87414449f6
train
function
def gather_file_info(filename): info = {} info['filename'] = filename c = read_file(filename) info['contents'] = c info['all_copyrights'] = get_count_of_copyrights_of_any_style_any_holder(c) info['classified_copyrights'] = 0 info['dominant_style'] = {} info['year_list_style'] = {} ...
def gather_file_info(filename):
info = {} info['filename'] = filename c = read_file(filename) info['contents'] = c info['all_copyrights'] = get_count_of_copyrights_of_any_style_any_holder(c) info['classified_copyrights'] = 0 info['dominant_style'] = {} info['year_list_style'] = {} info['without_c_style'] = {} ...
) return match is not None def file_has_without_c_style_copyright_for_holder(contents, holder_name): match = WITHOUT_C_STYLE_COMPILED[holder_name].search(contents) return match is not None ################################################################################ # get file info ####################...
79
79
264
6
73
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
gather_file_info
gather_file_info
149
173
149
149
45b12a3ccca2c3c1f8ed635bd9ea2fdffd8deafa
bigcode/the-stack
train
a974855db37ae78d36456aaf
train
function
def get_python_header_lines_to_insert(start_year, end_year): return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year))
def get_python_header_lines_to_insert(start_year, end_year):
return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year))
start_year, end_year)) PYTHON_HEADER = ''' # Copyright (c) %s The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' def get_python_header_lines_to_insert(start_year, end_year):
64
64
30
13
51
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_python_header_lines_to_insert
get_python_header_lines_to_insert
475
476
475
475
46041f410bb3648285612ca8f927d1ecdf13bfcc
bigcode/the-stack
train
101eab2896bfb87b8620afab
train
function
def year_range_to_str(start_year, end_year): if start_year == end_year: return start_year return "%s-%s" % (start_year, end_year)
def year_range_to_str(start_year, end_year):
if start_year == end_year: return start_year return "%s-%s" % (start_year, end_year)
def parse_year_range(year_range): year_split = year_range.split('-') start_year = year_split[0] if len(year_split) == 1: return start_year, start_year return start_year, year_split[1] def year_range_to_str(start_year, end_year):
64
64
39
11
53
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
year_range_to_str
year_range_to_str
361
364
361
361
aee12221735e46f41bcd0110600c3288964cfee7
bigcode/the-stack
train
e202beac52e7e7ab99595f1f
train
function
def write_file_lines(filename, file_lines): f = open(os.path.abspath(filename), 'w') f.write(''.join(file_lines)) f.close()
def write_file_lines(filename, file_lines):
f = open(os.path.abspath(filename), 'w') f.write(''.join(file_lines)) f.close()
return max(get_git_change_years(filename)) ################################################################################ # read and write to file ################################################################################ def read_file_lines(filename): f = open(os.path.abspath(filename), 'r') file...
64
64
34
9
54
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
write_file_lines
write_file_lines
331
334
331
331
eea996d8b4fa469f32c10e2b2bf69e995f72c9b9
bigcode/the-stack
train
a6a256e52a8a3d374eb2fa3d
train
function
def get_cpp_header_lines_to_insert(start_year, end_year): return reversed(get_header_lines(CPP_HEADER, start_year, end_year))
def get_cpp_header_lines_to_insert(start_year, end_year):
return reversed(get_header_lines(CPP_HEADER, start_year, end_year))
n' for line in lines] CPP_HEADER = ''' // Copyright (c) %s The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' def get_cpp_header_lines_to_insert(start_year, end_year):
64
64
29
13
51
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_cpp_header_lines_to_insert
get_cpp_header_lines_to_insert
466
467
466
466
733fb7f7bdcd5620197d7a932c7eb7d14e42281b
bigcode/the-stack
train
18ec3ee0727b14e54882f02f
train
function
def get_git_change_year_range(filename): years = get_git_change_years(filename) return min(years), max(years)
def get_git_change_year_range(filename):
years = get_git_change_years(filename) return min(years), max(years)
or http://www.opensource.org/licenses/mit-license.php. ''' def get_python_header_lines_to_insert(start_year, end_year): return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year)) ################################################################################ # query git for year of last change #####...
64
64
28
8
55
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_git_change_year_range
get_git_change_year_range
482
484
482
482
24c74925fe822f868a271175de3cac86f5b06992
bigcode/the-stack
train
994d55a90d955b609628281f
train
function
def get_header_lines(header, start_year, end_year): lines = header.split('\n')[1:-1] lines[0] = lines[0] % year_range_to_str(start_year, end_year) return [line + '\n' for line in lines]
def get_header_lines(header, start_year, end_year):
lines = header.split('\n')[1:-1] lines[0] = lines[0] % year_range_to_str(start_year, end_year) return [line + '\n' for line in lines]
) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad base_directory: %s" % base_directory) exec_update_header_year(base_directory) ################################################################################ # inserted copyright header format ################...
64
64
58
12
51
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_header_lines
get_header_lines
455
458
455
455
63ba3663d9cfde7973e51a77f50f88f06473174a
bigcode/the-stack
train
9bad1fdd3ed8f47d1c8c34f0
train
function
def get_most_recent_git_change_year(filename): return max(get_git_change_years(filename))
def get_most_recent_git_change_year(filename):
return max(get_git_change_years(filename))
year] # timestamp is in ISO 8601 format. e.g. "2016-09-05 14:25:32 -0600" return [line.split(' ')[0].split('-')[0] for line in git_log_lines] def get_most_recent_git_change_year(filename):
64
64
20
10
54
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_most_recent_git_change_year
get_most_recent_git_change_year
318
319
318
318
92035253ff2db05ec1b66199364778cd24704468
bigcode/the-stack
train
7bbb816d11f96f8977cfb95b
train
function
def get_updatable_copyright_line(file_lines): index = 0 for line in file_lines: if UPDATEABLE_LINE_COMPILED.search(line) is not None: return index, line index = index + 1 return None, None
def get_updatable_copyright_line(file_lines):
index = 0 for line in file_lines: if UPDATEABLE_LINE_COMPILED.search(line) is not None: return index, line index = index + 1 return None, None
-9][0-9]" YEAR_RANGE = '(%s)(-%s)?' % (YEAR, YEAR) HOLDER = 'The Bitcoin Core developers' UPDATEABLE_LINE_COMPILED = re.compile(' '.join([COPYRIGHT, YEAR_RANGE, HOLDER])) def get_updatable_copyright_line(file_lines):
64
64
58
10
54
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
get_updatable_copyright_line
get_updatable_copyright_line
346
352
346
346
32bce573e0d4927cac0e681804041ef0eed0eade
bigcode/the-stack
train
fc865fb3a695763f283c02b6
train
function
def update_updatable_copyright(filename): file_lines = read_file_lines(filename) index, line = get_updatable_copyright_line(file_lines) if not line: print_file_action_message(filename, "No updatable copyright.") return last_git_change_year = get_most_recent_git_change_year(filename) ...
def update_updatable_copyright(filename):
file_lines = read_file_lines(filename) index, line = get_updatable_copyright_line(file_lines) if not line: print_file_action_message(filename, "No updatable copyright.") return last_git_change_year = get_most_recent_git_change_year(filename) new_line = create_updated_copyright_line(l...
_range(year_range) if end_year == last_git_change_year: return line return (before_copyright + copyright_splitter + year_range_to_str(start_year, last_git_change_year) + ' ' + ' '.join(space_split[1:])) def update_updatable_copyright(filename):
64
64
146
8
56
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
update_updatable_copyright
update_updatable_copyright
383
397
383
383
cdfad236f2c0d938b71dcc78099f5b4b3c174c4b
bigcode/the-stack
train
a2f072def982f8909eb2ad58
train
function
def create_updated_copyright_line(line, last_git_change_year): copyright_splitter = 'Copyright (c) ' copyright_split = line.split(copyright_splitter) # Preserve characters on line that are ahead of the start of the copyright # notice - they are part of the comment block and vary from file-to-file. b...
def create_updated_copyright_line(line, last_git_change_year):
copyright_splitter = 'Copyright (c) ' copyright_split = line.split(copyright_splitter) # Preserve characters on line that are ahead of the start of the copyright # notice - they are part of the comment block and vary from file-to-file. before_copyright = copyright_split[0] after_copyright = copy...
_year return start_year, year_split[1] def year_range_to_str(start_year, end_year): if start_year == end_year: return start_year return "%s-%s" % (start_year, end_year) def create_updated_copyright_line(line, last_git_change_year):
64
64
173
13
51
caapisas88/lukcore
contrib/devtools/copyright_header.py
Python
create_updated_copyright_line
create_updated_copyright_line
366
381
366
366
3db11764e940dee6517e17a1ddd796ebf4f4f8d5
bigcode/the-stack
train