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
b5f1942db36dd97ecd6cc26a
train
function
def degree_shuffNet(network, verbose=False): shuff_time = time.time() edge_len=len(list(network.edges)) shuff_net=network.copy() try: nx.double_edge_swap(shuff_net, nswap=edge_len, max_tries=edge_len*10) except: if verbose: print('Note: Maximum number of swap attempts ('+repr(edge_len*10)+') exceeded before...
def degree_shuffNet(network, verbose=False):
shuff_time = time.time() edge_len=len(list(network.edges)) shuff_net=network.copy() try: nx.double_edge_swap(shuff_net, nswap=edge_len, max_tries=edge_len*10) except: if verbose: print('Note: Maximum number of swap attempts ('+repr(edge_len*10)+') exceeded before desired swaps achieved ('+repr(edge_len)+')....
pass # Constructs output directory if directory does not exist if not os.path.exists(run_pyNBS_params['outdir']): os.makedirs(run_pyNBS_params['outdir']) return run_pyNBS_params # Shuffle network by preserving node-degree def degree_shuffNet(network, verbose=False):
64
64
156
10
53
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
degree_shuffNet
degree_shuffNet
124
137
124
124
c02f64677e4f9c0cb3319c04df3c8a93d5264d1c
bigcode/the-stack
train
d32bad0036f10bc770e5c0c0
train
function
def filter_weighted_network(network_file_path, save_path, nodeA_col=0, nodeB_col=1, score_col=2, q=0.9, delimiter='\t', verbose=False): data = pd.read_csv(network_file_path, sep=delimiter, header=-1, low_memory=False) # Filter edges by score quantile q_score = data[score_col].quantile(q) if verbose: print(str(rou...
def filter_weighted_network(network_file_path, save_path, nodeA_col=0, nodeB_col=1, score_col=2, q=0.9, delimiter='\t', verbose=False):
data = pd.read_csv(network_file_path, sep=delimiter, header=-1, low_memory=False) # Filter edges by score quantile q_score = data[score_col].quantile(q) if verbose: print(str(round(q*100,2))+'%', 'score:', q_score) data_filt = data[data[score_col]>q_score][data.columns[[nodeA_col, nodeB_col, score_col]]] data_f...
table format of edge list, but the columns for Node A, Node B, and weight must be specified def filter_weighted_network(network_file_path, save_path, nodeA_col=0, nodeB_col=1, score_col=2, q=0.9, delimiter='\t', verbose=False):
64
64
192
42
21
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
filter_weighted_network
filter_weighted_network
159
170
159
159
6f98eb1e4be5714f0cb24ee9a2deb8ee731218ca
bigcode/the-stack
train
7951f3909a899267996c9030
train
function
def load_network_file(network_file_path, delimiter='\t', degree_shuffle=False, label_shuffle=False, verbose=True): # Load network using networkx network = nx.read_edgelist(network_file_path, delimiter=delimiter, data=False) if verbose: print('Network File Loaded:', network_file_path) if degree_shuffle: network ...
def load_network_file(network_file_path, delimiter='\t', degree_shuffle=False, label_shuffle=False, verbose=True): # Load network using networkx
network = nx.read_edgelist(network_file_path, delimiter=delimiter, data=False) if verbose: print('Network File Loaded:', network_file_path) if degree_shuffle: network = degree_shuffNet(network, verbose=verbose) if label_shuffle: network = label_shuffNet(network, verbose=verbose) return network
edges as first two columns, all other columns will be ignored # There are also options to shuffle the network to be loaded if desired (testing randomized network controls) def load_network_file(network_file_path, delimiter='\t', degree_shuffle=False, label_shuffle=False, verbose=True): # Load network using networkx
64
64
103
31
33
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
load_network_file
load_network_file
17
26
17
18
543fcc8c2064fb3ff386b255b7a94928a3e8d78c
bigcode/the-stack
train
3c8d3151d5925cf039678d02
train
function
def load_params(params_file=None): run_pyNBS_params = { # Overall pyNBS Parameters 'verbose' : True, 'job_name' : 'pyNBS', 'outdir' : './Results/', # Data Loading Parameters 'mut_filetype' : 'list', 'mut_filedelim' : '\t', 'net_filedelim' : '\t', 'degree_preserved_shuffle' : False, 'node_label_shuf...
def load_params(params_file=None):
run_pyNBS_params = { # Overall pyNBS Parameters 'verbose' : True, 'job_name' : 'pyNBS', 'outdir' : './Results/', # Data Loading Parameters 'mut_filetype' : 'list', 'mut_filedelim' : '\t', 'net_filedelim' : '\t', 'degree_preserved_shuffle' : False, 'node_label_shuffle' : False, # Data Subsampling ...
in binary_mat_lines] binary_mat_index = pd.MultiIndex.from_tuples(binary_mat_data, names=['Tumor_Sample_Barcode', 'Gene_Name']) binary_mat_2col = pd.DataFrame(1, index=binary_mat_index, columns=[0])[0] binary_mat = binary_mat_2col.unstack().fillna(0) elif filetype=='matrix': binary_mat = pd.read_csv(filename,...
218
218
729
7
210
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
load_params
load_params
55
121
55
55
ce8c0c2a0fe597a5d54e80c37a701783e6eeb2cc
bigcode/the-stack
train
e716e0da081dbe0208b2174c
train
function
def label_shuffNet(network, verbose=False): shuff_time = time.time() edge_len=len(list(network.edges)) # Permute node labels network_nodes = list(network.nodes) shuff_nodes = list(network_nodes) for i in range(10): random.shuffle(shuff_nodes) network_relabel_map = {network_nodes[i]:shuff_nodes[i] for i in rang...
def label_shuffNet(network, verbose=False):
shuff_time = time.time() edge_len=len(list(network.edges)) # Permute node labels network_nodes = list(network.nodes) shuff_nodes = list(network_nodes) for i in range(10): random.shuffle(shuff_nodes) network_relabel_map = {network_nodes[i]:shuff_nodes[i] for i in range(len(network_nodes))} shuff_net = nx.rela...
(set(list(network.edges)).intersection(set(list(shuff_net.edges)))) print('Network shuffled:', time.time()-shuff_time, 'seconds. Edge similarity:', shared_edges/float(edge_len)) return shuff_net # Shuffle network by permuting network node labels def label_shuffNet(network, verbose=False):
64
64
167
10
53
decarlin/pyNBS_3
pyNBS/data_import_tools.py
Python
label_shuffNet
label_shuffNet
140
154
140
140
f6a51138075101ca4d598bf576fbc5db41e39e81
bigcode/the-stack
train
39d142dfdd2192e9529ea16f
train
function
def _check_keys(new_config, old_config, prefix=""): if isinstance(new_config, Config): new_config = new_config.get_dict() if isinstance(old_config, Config): old_config = new_config.get_dict() assert isinstance(new_config, dict) assert isinstance(old_config, dict) own_keys = set(old_c...
def _check_keys(new_config, old_config, prefix=""):
if isinstance(new_config, Config): new_config = new_config.get_dict() if isinstance(old_config, Config): old_config = new_config.get_dict() assert isinstance(new_config, dict) assert isinstance(old_config, dict) own_keys = set(old_config) new_keys = set(new_config) if own_key...
old_dict = old_dict.get_dict() if isinstance(new_dict, Config): new_dict = new_dict.get_dict() merged = merge_dicts(old_dict, new_dict, allow_new_keys=new_keys_allowed) return Config(merged) def _check_keys(new_config, old_config, prefix=""):
64
64
145
13
51
decisionforce/pgdrive
pgdrive/utils/config.py
Python
_check_keys
_check_keys
23
39
23
23
648727d5422cdd1cdff14a63650dcff43b49bb08
bigcode/the-stack
train
36f8054bdc34b3365244d63b
train
function
def config_to_dict(config: Union[Any, dict, "Config"], serializable=False) -> dict: # Return the flatten and json-able dict if not isinstance(config, (dict, Config)): return config ret = dict() for k, v in config.items(): if isinstance(v, Config): v = v.get_dict() eli...
def config_to_dict(config: Union[Any, dict, "Config"], serializable=False) -> dict: # Return the flatten and json-able dict
if not isinstance(config, (dict, Config)): return config ret = dict() for k, v in config.items(): if isinstance(v, Config): v = v.get_dict() elif isinstance(v, dict): v = {sub_k: config_to_dict(sub_v, serializable) for sub_k, sub_v in v.items()} elif s...
) if isinstance(v, list): for new, old in zip(v, old_config[k]): _recursive_check_keys(new, old, new_prefix) def config_to_dict(config: Union[Any, dict, "Config"], serializable=False) -> dict: # Return the flatten and json-able dict
64
64
135
31
33
decisionforce/pgdrive
pgdrive/utils/config.py
Python
config_to_dict
config_to_dict
53
66
53
54
052cfa0f52c42e35b9d2406c03ab896be15dc29f
bigcode/the-stack
train
50d134e4f2f18ef85288214d
train
class
class Config: """ This class aims to check whether user config exists if default config system, Mostly, Config is sampled from parameter space in PGDrive Besides, the value type will also be checked, but sometimes the value type is not unique (maybe Union[str, int]). For these <key, value> items, u...
class Config:
""" This class aims to check whether user config exists if default config system, Mostly, Config is sampled from parameter space in PGDrive Besides, the value type will also be checked, but sometimes the value type is not unique (maybe Union[str, int]). For these <key, value> items, use Config["you...
prefix else "", own_keys ) ) def _recursive_check_keys(new_config, old_config, prefix=""): _check_keys(new_config, old_config, prefix) for k, v in new_config.items(): new_prefix = prefix + "/" + k if prefix else k # if isinstance(v, dict): # _recursive_check_ke...
256
256
1,893
3
252
decisionforce/pgdrive
pgdrive/utils/config.py
Python
Config
Config
69
290
69
69
5951c37872f0822fd898468f2e153c4fd2d3dcad
bigcode/the-stack
train
b6cbcba7d0de55534d25b071
train
function
def filter_none(config): to_remove = [] for k, v in config.items(): if v is None: to_remove.append(k) for k in to_remove: config.pop(k) return config
def filter_none(config):
to_remove = [] for k, v in config.items(): if v is None: to_remove.append(k) for k in to_remove: config.pop(k) return config
set(v2.keys()): return False for k in v1.keys(): if not _is_identical(k, v1[k], k, v2[k]): return False else: if v1 != v2: return False return True def filter_none(config):
64
64
47
5
58
decisionforce/pgdrive
pgdrive/utils/config.py
Python
filter_none
filter_none
310
317
310
310
b00ec8a763517ed52ed1a59c41419640b1b5bda7
bigcode/the-stack
train
00bc65aac4bd5a07c917d7f4
train
function
def _is_identical(k1, v1, k2, v2): if k1 != k2: return False if isinstance(v1, (dict, Config)) or isinstance(v2, (dict, Config)): if (not isinstance(v2, (dict, Config))) or (not isinstance(v1, (dict, Config))): return False if set(v1.keys()) != set(v2.keys()): ret...
def _is_identical(k1, v1, k2, v2):
if k1 != k2: return False if isinstance(v1, (dict, Config)) or isinstance(v2, (dict, Config)): if (not isinstance(v2, (dict, Config))) or (not isinstance(v1, (dict, Config))): return False if set(v1.keys()) != set(v2.keys()): return False for k in v1.keys(...
(new_config) self._unchangeable = True def force_set(self, key, value): self._unchangeable = False self[key] = value self._unchangeable = True def _is_identical(k1, v1, k2, v2):
64
64
147
17
46
decisionforce/pgdrive
pgdrive/utils/config.py
Python
_is_identical
_is_identical
293
307
293
293
4693aaaa6eaae0fbe79f5f2d2c94887c101b564e
bigcode/the-stack
train
f0504354a05650f3ec420f17
train
function
def merge_config(old_dict, new_dict, new_keys_allowed=False): from pgdrive.utils import Config if isinstance(old_dict, Config): old_dict = old_dict.get_dict() if isinstance(new_dict, Config): new_dict = new_dict.get_dict() merged = merge_dicts(old_dict, new_dict, allow_new_keys=new_keys_...
def merge_config(old_dict, new_dict, new_keys_allowed=False):
from pgdrive.utils import Config if isinstance(old_dict, Config): old_dict = old_dict.get_dict() if isinstance(new_dict, Config): new_dict = new_dict.get_dict() merged = merge_dicts(old_dict, new_dict, allow_new_keys=new_keys_allowed) return Config(merged)
from typing import Union, Any import numpy as np from pgdrive.utils.utils import merge_dicts def merge_config_with_unknown_keys(old_dict, new_dict): return merge_config(old_dict, new_dict, new_keys_allowed=True) def merge_config(old_dict, new_dict, new_keys_allowed=False):
64
64
81
14
50
decisionforce/pgdrive
pgdrive/utils/config.py
Python
merge_config
merge_config
13
20
13
13
0a47a1bbeaecde42c4f7c46c182c99a11d19e51e
bigcode/the-stack
train
38c5807ea37104d9adc3ffcf
train
function
def _recursive_check_keys(new_config, old_config, prefix=""): _check_keys(new_config, old_config, prefix) for k, v in new_config.items(): new_prefix = prefix + "/" + k if prefix else k # if isinstance(v, dict): # _recursive_check_keys(new_config[k], old_config[k], new_prefix) ...
def _recursive_check_keys(new_config, old_config, prefix=""):
_check_keys(new_config, old_config, prefix) for k, v in new_config.items(): new_prefix = prefix + "/" + k if prefix else k # if isinstance(v, dict): # _recursive_check_keys(new_config[k], old_config[k], new_prefix) if isinstance(v, list): for new, old in zip(v, ol...
raise KeyError( "Unexpected keys: {} in new dict{} when update config. Existing keys: {}.".format( new_keys - own_keys, "'s '{}'".format(prefix) if prefix else "", own_keys ) ) def _recursive_check_keys(new_config, old_config, prefix=""):
64
64
108
14
50
decisionforce/pgdrive
pgdrive/utils/config.py
Python
_recursive_check_keys
_recursive_check_keys
42
50
42
42
c9fca54175682a5a1da603edf9dcb178ce2dbcbc
bigcode/the-stack
train
ff1b9c07af33b192b15e09f2
train
function
def merge_config_with_unknown_keys(old_dict, new_dict): return merge_config(old_dict, new_dict, new_keys_allowed=True)
def merge_config_with_unknown_keys(old_dict, new_dict):
return merge_config(old_dict, new_dict, new_keys_allowed=True)
import copy from typing import Union, Any import numpy as np from pgdrive.utils.utils import merge_dicts def merge_config_with_unknown_keys(old_dict, new_dict):
37
64
27
12
24
decisionforce/pgdrive
pgdrive/utils/config.py
Python
merge_config_with_unknown_keys
merge_config_with_unknown_keys
9
10
9
9
492989837c6904e437fa1f20d4e715bf3037d4ba
bigcode/the-stack
train
92eb6f2ed773df55775a00ed
train
function
def create_project_directory(directory): if not os.path.exists(directory): print("Creating project directory \"{}\"".format(directory)) os.makedirs(directory) else: print("Already exist this \"{}\" directory.Please try another name.".format(directory)) return directory
def create_project_directory(directory):
if not os.path.exists(directory): print("Creating project directory \"{}\"".format(directory)) os.makedirs(directory) else: print("Already exist this \"{}\" directory.Please try another name.".format(directory)) return directory
import os # Create directory path (If not exist) def create_project_directory(directory):
18
64
57
6
12
dipto0321/Web_Crawler
methods.py
Python
create_project_directory
create_project_directory
6
12
6
6
e6e5c2e373c7ceb2690d68accf9a86e6fce4b401
bigcode/the-stack
train
afb58208583c9d736f096e92
train
function
def file_to_index(filename): result = set() with open(filename, 'rt') as lines: for line in lines: result.add(line.replace('\n', '')) return result
def file_to_index(filename):
result = set() with open(filename, 'rt') as lines: for line in lines: result.add(line.replace('\n', '')) return result
with open(path, 'a') as file: file.write(data + '\n') # Delete content path def clear_file_contents(path): with open(path, 'w') as f: f.close() # Read a file and convert it into a index/content list def file_to_index(filename):
64
64
42
6
57
dipto0321/Web_Crawler
methods.py
Python
file_to_index
file_to_index
49
54
49
49
64bcda2c0055e1699e06f9bf138524a140a902e7
bigcode/the-stack
train
16da0436eab814b074279266
train
function
def clear_file_contents(path): with open(path, 'w') as f: f.close()
def clear_file_contents(path):
with open(path, 'w') as f: f.close()
, data): with open(path, 'w') as f: f.write(data) # Add data on the existing file def append_data(path, data): with open(path, 'a') as file: file.write(data + '\n') # Delete content path def clear_file_contents(path):
64
64
21
6
57
dipto0321/Web_Crawler
methods.py
Python
clear_file_contents
clear_file_contents
42
44
42
42
a8d9c50b437729ab5d32c863f86760dac21d53e9
bigcode/the-stack
train
6d5c4d047cf8ef9fd7d0c0ec
train
function
def set_to_file(file, links): with open(file,"w") as f: for l in sorted(links): f.write(l+"\n")
def set_to_file(file, links):
with open(file,"w") as f: for l in sorted(links): f.write(l+"\n")
/content list def file_to_index(filename): result = set() with open(filename, 'rt') as lines: for line in lines: result.add(line.replace('\n', '')) return result # Save index data on a file through iteration set def set_to_file(file, links):
64
64
33
8
55
dipto0321/Web_Crawler
methods.py
Python
set_to_file
set_to_file
58
61
58
58
1384cc05d74f3b0bb99631a95ed4f6ad980f4707
bigcode/the-stack
train
2e85cdccd87d9fe3fe970f31
train
function
def append_data(path, data): with open(path, 'a') as file: file.write(data + '\n')
def append_data(path, data):
with open(path, 'a') as file: file.write(data + '\n')
_url) if not os.path.isfile(crawled): write_file(crawled, '') # Create new files def write_file(path, data): with open(path, 'w') as f: f.write(data) # Add data on the existing file def append_data(path, data):
64
64
26
7
56
dipto0321/Web_Crawler
methods.py
Python
append_data
append_data
35
37
35
35
c482a99a45e14a5f6f3ea91f4159b0b636fccf3c
bigcode/the-stack
train
6d86cc8927db4b8b765f210b
train
function
def write_file(path, data): with open(path, 'w') as f: f.write(data)
def write_file(path, data):
with open(path, 'w') as f: f.write(data)
') crawled = os.path.join(project_name , 'crawled.txt') if not os.path.isfile(queue): write_file(queue, base_url) if not os.path.isfile(crawled): write_file(crawled, '') # Create new files def write_file(path, data):
64
64
23
7
56
dipto0321/Web_Crawler
methods.py
Python
write_file
write_file
28
30
28
28
ccc39cdac6d529700c1580c5a58e38889f619fc1
bigcode/the-stack
train
f0c22df95ddfea94b8e3196c
train
function
def created_data_files(project_name, base_url): queue = os.path.join(project_name , 'queue.txt') crawled = os.path.join(project_name , 'crawled.txt') if not os.path.isfile(queue): write_file(queue, base_url) if not os.path.isfile(crawled): write_file(crawled, '')
def created_data_files(project_name, base_url):
queue = os.path.join(project_name , 'queue.txt') crawled = os.path.join(project_name , 'crawled.txt') if not os.path.isfile(queue): write_file(queue, base_url) if not os.path.isfile(crawled): write_file(crawled, '')
("Creating project directory \"{}\"".format(directory)) os.makedirs(directory) else: print("Already exist this \"{}\" directory.Please try another name.".format(directory)) return directory # Create queue and crawled files [(If not exist)] def created_data_files(project_name, base_url...
63
64
74
10
53
dipto0321/Web_Crawler
methods.py
Python
created_data_files
created_data_files
17
23
17
17
22bb63f1a21d9cb3cc2695fdca36ce69c49fcbd7
bigcode/the-stack
train
1947c5478ad8b854fc1eaa99
train
function
def is_installing(): # Allow command-lines such as "python setup.py build install" install_commands = set(['install', 'develop']) return install_commands.intersection(set(sys.argv))
def is_installing(): # Allow command-lines such as "python setup.py build install"
install_commands = set(['install', 'develop']) return install_commands.intersection(set(sys.argv))
later function call using global vars doesn't work. globals_dict = {} with open(os.path.join('nilearn', 'version.py')) as fp: exec(fp.read(), globals_dict) return globals_dict def is_installing(): # Allow command-lines such as "python setup.py build install"
64
64
40
19
44
ctw/nilearn
setup.py
Python
is_installing
is_installing
27
30
27
28
de31347215ef990a6cefddbaf2a16d46f18fe7a8
bigcode/the-stack
train
e5bde59d4da29eeeadb3cdea
train
function
def list_required_packages(): required_packages = [] required_packages_orig = ['%s>=%s' % (mod, meta['min_version']) for mod, meta in _VERSION_GLOBALS['REQUIRED_MODULE_METADATA'] ] for package in required_packages_orig...
def list_required_packages():
required_packages = [] required_packages_orig = ['%s>=%s' % (mod, meta['min_version']) for mod, meta in _VERSION_GLOBALS['REQUIRED_MODULE_METADATA'] ] for package in required_packages_orig: if package.startswit...
version.py')) as fp: exec(fp.read(), globals_dict) return globals_dict def is_installing(): # Allow command-lines such as "python setup.py build install" install_commands = set(['install', 'develop']) return install_commands.intersection(set(sys.argv)) def list_required_packages():
64
64
93
5
59
ctw/nilearn
setup.py
Python
list_required_packages
list_required_packages
33
43
33
33
40036d1e7b24b3339b1304423e17b140ab37110d
bigcode/the-stack
train
0731a8812eb433484fe8873e
train
function
def load_version(): """Executes nilearn/version.py in a globals dictionary and return it. Note: importing nilearn is not an option because there may be dependencies like nibabel which are not installed and setup.py is supposed to install them. """ # load all vars into globals, otherwise # ...
def load_version():
"""Executes nilearn/version.py in a globals dictionary and return it. Note: importing nilearn is not an option because there may be dependencies like nibabel which are not installed and setup.py is supposed to install them. """ # load all vars into globals, otherwise # the later function ...
#! /usr/bin/env python descr = """A set of python modules for neuroimaging...""" import sys import os from setuptools import setup, find_packages def load_version():
39
64
116
4
34
ctw/nilearn
setup.py
Python
load_version
load_version
11
24
11
11
9469f02a59aa7623556786813a3e3febd8137252
bigcode/the-stack
train
ec6c94c6766d13ee96c562ff
train
function
@pytest.yield_fixture(scope='function') def client(app): """ Setup an app client, this gets executed for each test function. :param app: Pytest fixture :return: Flask app client """ yield app.test_client()
@pytest.yield_fixture(scope='function') def client(app):
""" Setup an app client, this gets executed for each test function. :param app: Pytest fixture :return: Flask app client """ yield app.test_client()
': True, } _app = create_app(settings_override=params) # Establish an application context before running the tests. ctx = _app.app_context() ctx.push() yield _app ctx.pop() ## DEFINE TEST CLIENT @pytest.yield_fixture(scope='function') def client(app):
64
64
53
12
51
pkeech/Docker-WinRM-Demo
App/src/tests/conftest.py
Python
client
client
31
39
31
32
76f80cd13c44f2c9d88699f3b4196c9cfe44ac20
bigcode/the-stack
train
c1b5df25979739c5fc9d15f1
train
function
@pytest.yield_fixture(scope='session') def app(): """ Setup our flask test app, this only gets executed once. :return: Flask app """ params = { 'DEBUG': False, 'TESTING': True, } _app = create_app(settings_override=params) # Establish an application context before runn...
@pytest.yield_fixture(scope='session') def app():
""" Setup our flask test app, this only gets executed once. :return: Flask app """ params = { 'DEBUG': False, 'TESTING': True, } _app = create_app(settings_override=params) # Establish an application context before running the tests. ctx = _app.app_context() ct...
## IMPORT TESTING PYTHON MODULE import pytest ## IMPORT FLASK MODULE from src import create_app ## DEFINE TEST SETTINGS @pytest.yield_fixture(scope='session') def app():
39
64
96
11
27
pkeech/Docker-WinRM-Demo
App/src/tests/conftest.py
Python
app
app
8
28
8
9
b97d68f982472b2c8d1b82c5c08caa878a76142b
bigcode/the-stack
train
a5fea548b6b15fbb74a43290
train
class
class YoutubedlSkill(MycroftSkill): def __init__(self): super().__init__() self.proc = None self.vid = None self.queue = [] def initialize(self): my_setting = self.settings.get("my_setting") def play_vid(self): if self.proc is not None: self.stop...
class YoutubedlSkill(MycroftSkill):
def __init__(self): super().__init__() self.proc = None self.vid = None self.queue = [] def initialize(self): my_setting = self.settings.get("my_setting") def play_vid(self): if self.proc is not None: self.stop() try: self.pro...
#!/usr/bin/python3 from __future__ import unicode_literals from adapt.intent import IntentBuilder from mycroft import MycroftSkill, intent_handler import youtube_dl from subprocess import Popen, DEVNULL, STDOUT, CalledProcessError from os import remove class YoutubedlSkill(MycroftSkill):
68
256
1,140
11
56
bosangeros/mycroft-youtubedl-skill
__init__.py
Python
YoutubedlSkill
YoutubedlSkill
11
147
11
11
d0afc538cc2ea7e60dd9bbe2eacf8d3d696ee492
bigcode/the-stack
train
fdbd5bf9291e4f6fad8cde61
train
function
def create_skill(): return YoutubedlSkill()
def create_skill():
return YoutubedlSkill()
Stop playing video youtubedl.") # clear queue self.queue = [] # reset vars if self.proc: self.proc.terminate() self.proc = None if self.vid: remove(self.vid) self.vid = None def create_skill():
64
64
13
4
59
bosangeros/mycroft-youtubedl-skill
__init__.py
Python
create_skill
create_skill
150
151
150
150
6b73764c44abbdd36fa65904e91b1bb8c529655f
bigcode/the-stack
train
bc4e9988d520a6529687f00e
train
class
class Cache: def __init__(self, config_path, expiration): cache = "{}.cache".format(os.path.splitext(config_path)[0]) with sqlite3.connect(cache) as connection: connection.row_factory = sqlite3.Row with closing(connection.cursor()) as cursor: cursor.execute("S...
class Cache:
def __init__(self, config_path, expiration): cache = "{}.cache".format(os.path.splitext(config_path)[0]) with sqlite3.connect(cache) as connection: connection.row_factory = sqlite3.Row with closing(connection.cursor()) as cursor: cursor.execute("SELECT count(n...
import logging, os, random, sqlite3 from contextlib import closing from datetime import datetime, timedelta logger = logging.getLogger("Plex Meta Manager") class Cache:
37
256
1,772
3
34
maciejzgadzaj/Plex-Meta-Manager
modules/cache.py
Python
Cache
Cache
7
128
7
7
784da739cf8a63f2fb660c6b43571f26a6958a86
bigcode/the-stack
train
e3c6279806c2ffbc31f24927
train
function
def WriteComponentToParallelUploadTrackerFile(tracker_file_name, tracker_file_lock, component, logger, encryption_key_sha256=None): ""...
def WriteComponentToParallelUploadTrackerFile(tracker_file_name, tracker_file_lock, component, logger, encryption_key_sha256=None):
"""Rewrites an existing tracker file with info about the uploaded component. Follows the format described in _CreateParallelUploadTrackerFile. Args: tracker_file_name: Tracker file to append to. tracker_file_lock: Thread and process-safe Lock protecting the tracker file. component: ObjectFromTracker...
with a different encryption key. Returns: String prefix for use in the composite upload. """ return str( (random.randint(1, (10**10) - 1) + hash(encryption_key_sha256)) % 10**10) def WriteComponentToParallelUploadTrackerFile(tracker_file_name, tracker_file...
86
86
289
31
55
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
WriteComponentToParallelUploadTrackerFile
WriteComponentToParallelUploadTrackerFile
226
257
226
230
1e8cdca83375acd5e3d4f2bfbd0918e1fdcf103b
bigcode/the-stack
train
b8e35762253749bcdfc6d5db
train
function
def _ParseLegacyTrackerData(tracker_data): """Parses a legacy parallel composite upload tracker file. Args: tracker_data: Legacy tracker file contents. Returns: component_prefix: The prefix used in naming the existing components, or None if no prefix was found. existing_components: A list of...
def _ParseLegacyTrackerData(tracker_data):
"""Parses a legacy parallel composite upload tracker file. Args: tracker_data: Legacy tracker file contents. Returns: component_prefix: The prefix used in naming the existing components, or None if no prefix was found. existing_components: A list of ObjectFromTracker objects representing ...
# Legacy format did not support user-supplied encryption. enc_key_sha256 = None (prefix, existing_components) = _ParseLegacyTrackerData(tracker_data) finally: if tracker_file: tracker_file.close() return (enc_key_sha256, prefix, existing_components) def _ParseLegacyTrackerData(tracker_data):
74
74
248
10
64
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
_ParseLegacyTrackerData
_ParseLegacyTrackerData
107
135
107
107
706defc0c133159f28697eef6ab1088620d764c5
bigcode/the-stack
train
b80a2dc18731185729bd4b62
train
function
def ValidateParallelCompositeTrackerData(tracker_file_name, existing_enc_sha256, existing_prefix, existing_components, current_enc_key_sha256, bucket_url, command_obj, logger, delete_func, ...
def ValidateParallelCompositeTrackerData(tracker_file_name, existing_enc_sha256, existing_prefix, existing_components, current_enc_key_sha256, bucket_url, command_obj, logger, delete_func, ...
"""Validates that tracker data matches the current encryption key. If the data does not match, makes a best-effort attempt to delete existing temporary component objects encrypted with the old key. Args: tracker_file_name: String file name of tracker file. existing_enc_sha256: Encryption key SHA256 us...
# The first line represents the prefix, followed by line pairs of object_name # and generation. Discard the last blank line. old_tracker_data = tracker_data.split('\n')[:-1] prefix = None existing_components = [] if old_tracker_data: prefix = old_tracker_data[0] i = 1 while i < len(old_tracker_da...
196
196
654
47
149
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
ValidateParallelCompositeTrackerData
ValidateParallelCompositeTrackerData
138
208
138
142
b522e8f46fd52d131a3c7ba6a22afc11a3b4db8e
bigcode/the-stack
train
19b1f8b2ca998351971412e7
train
function
def GenerateComponentObjectPrefix(encryption_key_sha256=None): """Generates a random prefix for component objects. Args: encryption_key_sha256: Encryption key SHA256 that will be used to encrypt the components. This is hashed into the prefix to avoid collision during resumption with a different...
def GenerateComponentObjectPrefix(encryption_key_sha256=None):
"""Generates a random prefix for component objects. Args: encryption_key_sha256: Encryption key SHA256 that will be used to encrypt the components. This is hashed into the prefix to avoid collision during resumption with a different encryption key. Returns: String prefix for use in the c...
on to re-upload components from scratch.)', '\n'.join(component_names)) # Encryption keys have changed, so the old components and prefix # cannot be used. return (None, []) return (existing_prefix, existing_components) def GenerateComponentObjectPrefix(encryption_key_sha256=None):
64
64
116
12
52
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
GenerateComponentObjectPrefix
GenerateComponentObjectPrefix
211
223
211
211
51dce65a35636e68b7a2c8bfe08eceffb4e17ec9
bigcode/the-stack
train
942b9d20121f017ed3956ed4
train
function
def WriteParallelUploadTrackerFile(tracker_file_name, prefix, components, encryption_key_sha256=None): """Writes information about components that were successfully uploaded. The tracker file is serialized JSON...
def WriteParallelUploadTrackerFile(tracker_file_name, prefix, components, encryption_key_sha256=None):
"""Writes information about components that were successfully uploaded. The tracker file is serialized JSON of the form: { "encryption_key_sha256": sha256 hash of encryption key (or null), "prefix": Prefix used for the component objects, "components": [ { "component_name": Component obje...
'does not match encryption key SHA256 (%s) of component %s' % (existing_enc_key_sha256, encryption_key_sha256, component.object_name)) newly_completed_components = [component] completed_components = existing_components + newly_completed_components WriteParallelUploadTrackerFil...
108
108
360
24
84
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
WriteParallelUploadTrackerFile
WriteParallelUploadTrackerFile
260
304
260
263
f2dd513c8225622c42e7a4a25da4189d3ee0a659
bigcode/the-stack
train
a329da75cdfa4290089abdf7
train
class
class _CompositeUploadTrackerEntry(object): """Enum class for composite upload tracker file JSON keys.""" COMPONENTS_LIST = 'components' COMPONENT_NAME = 'component_name' COMPONENT_GENERATION = 'component_generation' ENC_SHA256 = 'encryption_key_sha256' PREFIX = 'prefix'
class _CompositeUploadTrackerEntry(object):
"""Enum class for composite upload tracker file JSON keys.""" COMPONENTS_LIST = 'components' COMPONENT_NAME = 'component_name' COMPONENT_GENERATION = 'component_generation' ENC_SHA256 = 'encryption_key_sha256' PREFIX = 'prefix'
gslib.exception import CommandException from gslib.tracker_file import (WriteJsonDataToTrackerFile, RaiseUnwritableTrackerFileException) from gslib.utils.constants import UTF8 ObjectFromTracker = namedtuple('ObjectFromTracker', 'object_name generation') class _CompositeUploadTrackerEnt...
64
64
63
8
56
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
_CompositeUploadTrackerEntry
_CompositeUploadTrackerEntry
38
44
38
38
f19a00093a5afd3a5c7e50626b36f08255157957
bigcode/the-stack
train
c7d1359cd114826abccbdbd3
train
function
def ReadParallelUploadTrackerFile(tracker_file_name, logger): """Read the tracker file from the last parallel composite upload attempt. If it exists, the tracker file is of the format described in WriteParallelUploadTrackerFile or a legacy format. If the file doesn't exist or is formatted incorrectly, then the...
def ReadParallelUploadTrackerFile(tracker_file_name, logger):
"""Read the tracker file from the last parallel composite upload attempt. If it exists, the tracker file is of the format described in WriteParallelUploadTrackerFile or a legacy format. If the file doesn't exist or is formatted incorrectly, then the upload will start from the beginning. This function is not...
division from __future__ import unicode_literals from collections import namedtuple import errno import json import random import six import gslib from gslib.exception import CommandException from gslib.tracker_file import (WriteJsonDataToTrackerFile, RaiseUnwritableTrackerFileExcept...
165
165
553
13
152
stanhu/gsutil
gslib/parallel_tracker_file.py
Python
ReadParallelUploadTrackerFile
ReadParallelUploadTrackerFile
47
104
47
47
9bf82693453310e6cd409a4c3ed47f6b9790d39d
bigcode/the-stack
train
36131d6e1f1e4f9cf4cbe90b
train
class
class TMCM_1370(): def __init__(self, connection): self.connection = connection self.GPs = _GPs self.APs = _APs self.ENUMs = _ENUMs self.MOTORS = 1 self.__default_motor = 0 def showChipInfo(self): ("The PD42-x-1370 is a stepper motor driver, made up...
class TMCM_1370():
def __init__(self, connection): self.connection = connection self.GPs = _GPs self.APs = _APs self.ENUMs = _ENUMs self.MOTORS = 1 self.__default_motor = 0 def showChipInfo(self): ("The PD42-x-1370 is a stepper motor driver, made up of the TMCM-1370 m...
''' Created on 08.07.2020 @author: JM ''' class TMCM_1370():
23
256
882
7
16
bmoneke/PyTrinamic
PyTrinamic/modules/TMCM1370/TMCM_1370.py
Python
TMCM_1370
TMCM_1370
7
128
7
7
cc72f6572ec3afa4fd3a344642b1bbd5debf56ea
bigcode/the-stack
train
e4c5cf6e8f5b802fc4c31a34
train
class
class _APs(): TargetPosition = 0 ActualPosition = 1 TargetVelocity = 2 ActualVelocity = 3 MaxVelocity = 4 MaxAcceleration = 5 MaxCurrent = 6 StandbyCurrent ...
class _APs():
TargetPosition = 0 ActualPosition = 1 TargetVelocity = 2 ActualVelocity = 3 MaxVelocity = 4 MaxAcceleration = 5 MaxCurrent = 6 StandbyCurrent = 7 Posi...
TargetVelocity(self): return self.getAxisParameter(self.APs.TargetVelocity, signed=True) def setTargetVelocity(self, velocity): self.setAxisParameter(self.APs.TargetVelocity, velocity) def getActualVelocity(self): return self.getAxisParameter(self.APs.ActualVelocity, signed=True) ...
256
256
1,025
5
251
bmoneke/PyTrinamic
PyTrinamic/modules/TMCM1370/TMCM_1370.py
Python
_APs
_APs
130
239
130
130
31aba8ac482335ded5c72ea78918ffbfb5de305e
bigcode/the-stack
train
844c4f1b43ec40d7ce8df82e
train
class
class _ENUMs(): FLAG_POSITION_END = 0x00004000
class _ENUMs():
FLAG_POSITION_END = 0x00004000
EncoderDeviation = 213 SettingDelay = 214 AbsoluteEncoder = 215 EncoderErrorBits = 219 AllStatusBits = 250 ReverseShaft = 251 ClearAlarmOutputs = 252 class _ENUMs():
64
64
17
5
58
bmoneke/PyTrinamic
PyTrinamic/modules/TMCM1370/TMCM_1370.py
Python
_ENUMs
_ENUMs
241
242
241
241
ab4767dd6ae39c6667a7d2ef244d7c2071ffa2f5
bigcode/the-stack
train
06ecccbe48871c10a2acd4f5
train
class
class _GPs(): timer_0 = 0 timer_1 = 1 timer_2 = 2 stopLeft_0 = 27 stopRight_0 = 28 input_0 = 39 input_1 = 40 input_2 ...
class _GPs():
timer_0 = 0 timer_1 = 1 timer_2 = 2 stopLeft_0 = 27 stopRight_0 = 28 input_0 = 39 input_1 = 40 input_2 = 41 ...
= 213 SettingDelay = 214 AbsoluteEncoder = 215 EncoderErrorBits = 219 AllStatusBits = 250 ReverseShaft = 251 ClearAlarmOutputs = 252 class _ENUMs(): FLAG_POSITION_END = 0x00004000 class _GPs():...
79
79
265
5
73
bmoneke/PyTrinamic
PyTrinamic/modules/TMCM1370/TMCM_1370.py
Python
_GPs
_GPs
244
273
244
244
f919644ec2e6f8ffa27ed837eb8fc7becf841f8c
bigcode/the-stack
train
638ee517e1e6c81d8743daf6
train
class
class ImageUtilsQemuTestCase(ImageUtilsRawTestCase): _file_format = [ ('qcow2', dict(file_format='qcow2')), ] _qcow2_cluster_size = [ ('65536', dict(cluster_size='65536', exp_cluster_size=65536)), ] _qcow2_encrypted = [ ('no_encryption', dict(encrypted=None)), ('en...
class ImageUtilsQemuTestCase(ImageUtilsRawTestCase):
_file_format = [ ('qcow2', dict(file_format='qcow2')), ] _qcow2_cluster_size = [ ('65536', dict(cluster_size='65536', exp_cluster_size=65536)), ] _qcow2_encrypted = [ ('no_encryption', dict(encrypted=None)), ('encrypted', dict(encrypted='yes')), ] _qcow2_ba...
_size, self.exp_disk_size) if self.snapshot_count is not None: self.assertEqual(len(image_info.snapshots), self.snapshot_count) def test_qemu_img_info(self): img_info = self._initialize_img_info() if self.garbage_before_snapshot is True: img_info = img_info + ('blah ...
178
178
595
13
165
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
Python
ImageUtilsQemuTestCase
ImageUtilsQemuTestCase
139
200
139
140
9112354a92a0c23688427a16e357f87893fa1627
bigcode/the-stack
train
c5da39700ea65cf44a921a7d
train
class
class ImageUtilsBlankTestCase(test_base.BaseTestCase): def test_qemu_img_info_blank(self): example_output = '\n'.join(['image: None', 'file_format: None', 'virtual_size: None', 'disk_size: None', 'cluster_size: None', ...
class ImageUtilsBlankTestCase(test_base.BaseTestCase):
def test_qemu_img_info_blank(self): example_output = '\n'.join(['image: None', 'file_format: None', 'virtual_size: None', 'disk_size: None', 'cluster_size: None', 'backing_file: None']) image_...
None: self.assertEqual(image_info.backing_file, self.exp_backing_file) if self.encrypted is not None: self.assertEqual(image_info.encrypted, self.encrypted) ImageUtilsQemuTestCase.generate_scenarios() class ImageUtilsBlankTestCase(test_base.BaseTestCase):
64
64
104
12
52
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
Python
ImageUtilsBlankTestCase
ImageUtilsBlankTestCase
205
213
205
205
2ef97aa80e351e933a3f16332ea929493964e3fa
bigcode/the-stack
train
6e4e9977dd1cfc4b1f0b6f27
train
class
class ImageUtilsJSONTestCase(test_base.BaseTestCase): def test_qemu_img_info_json_format(self): img_output = '''{ "virtual-size": 41126400, "filename": "fake_img", "cluster-size": 65536, "format": "qcow2", ...
class ImageUtilsJSONTestCase(test_base.BaseTestCase):
def test_qemu_img_info_json_format(self): img_output = '''{ "virtual-size": 41126400, "filename": "fake_img", "cluster-size": 65536, "format": "qcow2", "actual-size": 13168640 ...
virtual_size: None', 'disk_size: None', 'cluster_size: None', 'backing_file: None']) image_info = imageutils.QemuImgInfo() self.assertEqual(str(image_info), example_output) self.assertEqual(len(image_info.snapshots), 0) clas...
73
73
246
12
61
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
Python
ImageUtilsJSONTestCase
ImageUtilsJSONTestCase
216
239
216
216
b3da3c85e0af3f6a1171ed2412f1531c85dab50d
bigcode/the-stack
train
230cbe79c3ad659dd8dd19b3
train
class
class ImageUtilsRawTestCase(test_base.BaseTestCase): _image_name = [ ('disk_config', dict(image_name='disk.config')), ] _file_format = [ ('raw', dict(file_format='raw')), ] _virtual_size = [ ('64M', dict(virtual_size='64M', exp_virtual_size=67108864)),...
class ImageUtilsRawTestCase(test_base.BaseTestCase):
_image_name = [ ('disk_config', dict(image_name='disk.config')), ] _file_format = [ ('raw', dict(file_format='raw')), ] _virtual_size = [ ('64M', dict(virtual_size='64M', exp_virtual_size=67108864)), ('64M_with_byte_hint', dict(virtual_size='64M...
# Copyright (C) 2012 Yahoo! Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
196
256
1,092
12
183
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
Python
ImageUtilsRawTestCase
ImageUtilsRawTestCase
24
134
24
25
049cae90d05bb13ac930bc7457af4b6c9c2fbe90
bigcode/the-stack
train
767a897fc8fe4c170ad52507
train
function
def main(): badger = connect_badger(badger_config.prod_json) table = [] hunt = badger.badgerHunt table.append(["nextEpochStart", hunt.getNextEpochStart()]) table.append(["timeTillNextEpoch", hunt.getNextEpochStart() - chain.time()]) table.append(["currentEpoch", hunt.getCurrentEpoch()]) ta...
def main():
badger = connect_badger(badger_config.prod_json) table = [] hunt = badger.badgerHunt table.append(["nextEpochStart", hunt.getNextEpochStart()]) table.append(["timeTillNextEpoch", hunt.getNextEpochStart() - chain.time()]) table.append(["currentEpoch", hunt.getCurrentEpoch()]) table.append([...
from brownie import * from config.badger_config import badger_config from scripts.systems.badger_system import connect_badger from tabulate import tabulate def main():
36
69
230
3
32
EchoDao-BSC/badger-system
scripts/status/hunt_status.py
Python
main
main
7
27
7
7
d298754c2ad5da2885e05d78ab141f05e9957d74
bigcode/the-stack
train
3c6d6ad03bd2e0ec68f257a6
train
function
def macd(ohlcv, short_period=12, long_period=26, signal_period=9, ohlcv_series="close"): _ohlcv = ohlcv[[ohlcv_series]].copy(deep=True) _ohlcv["short"] = _ohlcv[ohlcv_series].ewm(span=short_period, min_periods=short_period).mean() _ohlcv["long"] = _ohlcv[ohlcv_series].ewm(span=long_period, min_periods=long...
def macd(ohlcv, short_period=12, long_period=26, signal_period=9, ohlcv_series="close"):
_ohlcv = ohlcv[[ohlcv_series]].copy(deep=True) _ohlcv["short"] = _ohlcv[ohlcv_series].ewm(span=short_period, min_periods=short_period).mean() _ohlcv["long"] = _ohlcv[ohlcv_series].ewm(span=long_period, min_periods=long_period).mean() _ohlcv["macd"] = _ohlcv["short"] - _ohlcv["long"] _ohlcv["signal"]...
9-day EMA of MACD Line MACD Histogram: MACD Line - Signal Line Validation: validated with results from Bloomberg """ # Standard MACD function def macd(ohlcv, short_period=12, long_period=26, signal_period=9, ohlcv_series="close"):
64
64
204
30
33
leopoldsw/qrtt
qrtt/technical/macd.py
Python
macd
macd
41
50
41
42
25c14bd8cf5a9f79ef0f058377a26f8b377a2980
bigcode/the-stack
train
7bb0a3913746d20edba9060a
train
class
class MispEvent(object): def __init__(self, event): self.event_id = event['Event']['id'] self.event = event def get_all_ips(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'ip-dst' or a['type'] == 'ip-src'] def get_all_domains(se...
class MispEvent(object):
def __init__(self, event): self.event_id = event['Event']['id'] self.event = event def get_all_ips(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'ip-dst' or a['type'] == 'ip-src'] def get_all_domains(self): return [a['va...
except ImportError: HAVE_SSDEEP = False try: import magic except ImportError: pass class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls...
92
92
309
6
86
vasporig/viper
viper/common/objects.py
Python
MispEvent
MispEvent
29
60
29
30
ef8864a5dd0e4d38732e4a080bf14867b7521632
bigcode/the-stack
train
e9a0b425aa32da9788154690
train
class
class Dictionary(dict): """Viper custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
class Dictionary(dict):
"""Viper custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
ms = magic.open(magic.MIME) ms.load() mime_type = ms.file(self.path) except: try: mime = magic.Magic(mime=True) mime_type = mime.from_file(self.path) except: return '' return mime_type class Dict...
64
64
51
4
59
vasporig/viper
viper/common/objects.py
Python
Dictionary
Dictionary
175
182
175
175
e9d26a28a76498e3b14332a6cc6f58891a64daf7
bigcode/the-stack
train
588076bd2cf31ec44fb8bbad
train
class
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
class Singleton(type):
_instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
See the file 'LICENSE' for copying permission. import os import hashlib import binascii try: import pydeep HAVE_SSDEEP = True except ImportError: HAVE_SSDEEP = False try: import magic except ImportError: pass class Singleton(type):
64
64
61
4
59
vasporig/viper
viper/common/objects.py
Python
Singleton
Singleton
20
26
20
20
8b2127f8b70f88e5afc53b2f6f44210b93a4a691
bigcode/the-stack
train
787dc265334e21fed757b7ce
train
class
class File(object): def __init__(self, path): self.id = None self.path = path self.name = '' self.size = 0 self.type = '' self.mime = '' self.md5 = '' self.sha1 = '' self.sha256 = '' self.sha512 = '' self.crc32 = '' sel...
class File(object):
def __init__(self, path): self.id = None self.path = path self.name = '' self.size = 0 self.type = '' self.mime = '' self.md5 = '' self.sha1 = '' self.sha256 = '' self.sha512 = '' self.crc32 = '' self.ssdeep = '' ...
'hostname'] def get_all_urls(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'url'] def get_all_hashes(self): event_hashes = [] sample_hashes = [] for a in self.event['Event']['Attribute']: h = None if a['type'] in ('...
195
195
650
4
190
vasporig/viper
viper/common/objects.py
Python
File
File
63
172
63
64
d04eca92ad0083f8de9b5113fb90f825b97103c3
bigcode/the-stack
train
6274a977c441e7da91f99c1a
train
class
class Backtest(object): """ Enscapsulates the settings and components for carrying out an event-driven backtest on the foreign exchange markets. """ def __init__( self, pairs, data_handler, strategy, strategy_params, portfolio, execution, equity=100000.0, heartbeat=0.0, ...
class Backtest(object):
""" Enscapsulates the settings and components for carrying out an event-driven backtest on the foreign exchange markets. """ def __init__( self, pairs, data_handler, strategy, strategy_params, portfolio, execution, equity=100000.0, heartbeat=0.0, max_iters=10000 ...
from __future__ import print_function try: import Queue as queue except ImportError: import queue import time import settings # class Backtest(object):
36
156
520
5
31
G-Wang/forexfun
backtest.py
Python
Backtest
Backtest
12
84
12
12
0bd2ca278ab87d8fc3554ef1dfef0ec7fd983020
bigcode/the-stack
train
e907e0ffcba147001684451b
train
class
class DataPipelineConnection(AWSQueryConnection): """ This is the AWS Data Pipeline API Reference . This guide provides descriptions and samples of the AWS Data Pipeline API. AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipe...
class DataPipelineConnection(AWSQueryConnection):
""" This is the AWS Data Pipeline API Reference . This guide provides descriptions and samples of the AWS Data Pipeline API. AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipeline handles the details of scheduling and ens...
and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, sub...
256
256
5,420
9
246
Rome84/AWS
datapipeline/layer1.py
Python
DataPipelineConnection
DataPipelineConnection
31
639
31
31
e9147b01a2eec50920a67e5a15fb2febf433521f
bigcode/the-stack
train
2f61101df8a22d81315ad9db
train
function
def simulation_kruskal_crossover(params): STPG = read_problem("datasets", "ORLibrary", params["dataset"]) crossover = CrossoverKruskalRST(STPG) evaluation = EvaluateEdgeSet(STPG) mutate = MutationReplaceByRandomEdge(STPG) output_data_dir = os.path.join("data","test","edgeset", "kruskal_cr...
def simulation_kruskal_crossover(params):
STPG = read_problem("datasets", "ORLibrary", params["dataset"]) crossover = CrossoverKruskalRST(STPG) evaluation = EvaluateEdgeSet(STPG) mutate = MutationReplaceByRandomEdge(STPG) output_data_dir = os.path.join("data","test","edgeset", "kruskal_crossover", STPG.name) tracker = DataTrack...
']) .callback(update_generation) .callback(display, every=100)) with Stagnation(interval=params["stagnation_interval"]), \ BestKnownReached(global_optimum=params['global_optimum']): result = population.evolve(evol, n=params["n_iterations"]) tracker.log_s...
93
93
310
10
83
GiliardGodoi/steiner-problem-with-evol
simulations/lab_edgeset.py
Python
simulation_kruskal_crossover
simulation_kruskal_crossover
57
94
57
58
32223618db28067f88b2246d7103624a02562a58
bigcode/the-stack
train
1736323cae6b9791d711ef99
train
function
def simulation_prim_crossover(params): STPG = read_problem("datasets", "ORLibrary", params["dataset"]) crossover = CrossoverPrimRST(STPG) evaluation = EvaluateEdgeSet(STPG) mutate = MutationReplaceByRandomEdge(STPG) output_data_dir = os.path.join("data","test","edgeset", "prim_crossover",...
def simulation_prim_crossover(params):
STPG = read_problem("datasets", "ORLibrary", params["dataset"]) crossover = CrossoverPrimRST(STPG) evaluation = EvaluateEdgeSet(STPG) mutate = MutationReplaceByRandomEdge(STPG) output_data_dir = os.path.join("data","test","edgeset", "prim_crossover", STPG.name) tracker = DataTracker(par...
']) .callback(update_generation) .callback(display, every=100)) with Stagnation(interval=params["stagnation_interval"]), \ BestKnownReached(global_optimum=params['global_optimum']): result = population.evolve(evol, n=params["n_iterations"]) tracker.log_s...
91
91
304
8
83
GiliardGodoi/steiner-problem-with-evol
simulations/lab_edgeset.py
Python
simulation_prim_crossover
simulation_prim_crossover
96
133
96
97
b803a0e1fa1c23a03e540c2a39496dc218cfbab4
bigcode/the-stack
train
4f5e042e44e582181c6a63fc
train
function
def simulation_random_walk(params): STPG = read_problem("datasets", "ORLibrary", params["dataset"]) crossover = CrossoverRandomWalkRST(STPG) evaluation = EvaluateEdgeSet(STPG) mutate = MutationReplaceByRandomEdge(STPG) output_data_dir = os.path.join("data","test","edgeset", STPG.name) ...
def simulation_random_walk(params):
STPG = read_problem("datasets", "ORLibrary", params["dataset"]) crossover = CrossoverRandomWalkRST(STPG) evaluation = EvaluateEdgeSet(STPG) mutate = MutationReplaceByRandomEdge(STPG) output_data_dir = os.path.join("data","test","edgeset", STPG.name) tracker = DataTracker(params['runtria...
import GeneticEvolution as Evolution from ga4stpg.customevol import GeneticPopulation as GPopulation from ga4stpg.graph.reader import read_problem from ga4stpg.normalization import normalize from ga4stpg.selector import roullete from ga4stpg.tracker import DataTracker from ga4stpg.util import STEIN_B, display, u...
89
89
298
6
82
GiliardGodoi/steiner-problem-with-evol
simulations/lab_edgeset.py
Python
simulation_random_walk
simulation_random_walk
18
55
18
19
6b162a01129d8c98f6298fe8031e1ea0c0b2782e
bigcode/the-stack
train
a1a520e4192a47559739af78
train
class
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] result = [] queue = Queue.Queue(maxsize=0) queue2 = Queue.Queue(maxsize=0) queue2.put(root) w...
class Solution(object):
def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] result = [] queue = Queue.Queue(maxsize=0) queue2 = Queue.Queue(maxsize=0) queue2.put(root) while not queue2.empty():...
import Queue # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object):
52
64
146
4
47
xuychen/Leetcode
LCOF/31-40/32-2/32-2.py
Python
Solution
Solution
10
38
10
10
95bb6f6a5c5c38d45562a2d64dfe3616a86e2933
bigcode/the-stack
train
615d6ddd023a38ed4349e6a3
train
function
def test_recoverable_flag(app, client, get_message): recorded_resets = [] recorded_instructions_sent = [] @password_reset.connect_via(app) def on_password_reset(app, user): recorded_resets.append(user) @reset_password_instructions_sent.connect_via(app) def on_instructions_sent(app, use...
def test_recoverable_flag(app, client, get_message):
recorded_resets = [] recorded_instructions_sent = [] @password_reset.connect_via(app) def on_password_reset(app, user): recorded_resets.append(user) @reset_password_instructions_sent.connect_via(app) def on_instructions_sent(app, user, token): recorded_instructions_sent.append(...
# -*- coding: utf-8 -*- """ test_recoverable ~~~~~~~~~~~~~~~~ Recoverable functionality tests """ import time import pytest from flask_security.signals import reset_password_instructions_sent, password_reset from flask_security.utils import capture_reset_password_requests from utils import authenticate...
88
216
723
13
75
mattadendorff/flask-security
tests/test_recoverable.py
Python
test_recoverable_flag
test_recoverable_flag
21
98
21
21
257a07ec9df81f06fddf940512531b37f1580b06
bigcode/the-stack
train
d530d304839f2b84eed0a4a8
train
function
@pytest.mark.settings(reset_url='/custom_reset') def test_custom_reset_url(client): response = client.get('/custom_reset') assert response.status_code == 200
@pytest.mark.settings(reset_url='/custom_reset') def test_custom_reset_url(client):
response = client.get('/custom_reset') assert response.status_code == 200
': 'newpassword', 'password_confirm': 'newpassword' }, follow_redirects=True) msg = get_message('PASSWORD_RESET_EXPIRED', within='1 milliseconds', email=user.email) assert msg in response.data @pytest.mark.settings(reset_url='/custom_reset') def test_custom_reset_url(client):
64
64
34
16
47
mattadendorff/flask-security
tests/test_recoverable.py
Python
test_custom_reset_url
test_custom_reset_url
120
123
120
121
3528776839da240336b8df08e50919b5b526b5c3
bigcode/the-stack
train
7318cbda7422040eb5d4bf5b
train
function
@pytest.mark.settings(reset_password_within='1 milliseconds') def test_expired_reset_token(client, get_message): with capture_reset_password_requests() as requests: client.post('/reset', data=dict(email='joe@lp.com'), follow_redirects=True) user = requests[0]['user'] token = requests[0]['token'] ...
@pytest.mark.settings(reset_password_within='1 milliseconds') def test_expired_reset_token(client, get_message):
with capture_reset_password_requests() as requests: client.post('/reset', data=dict(email='joe@lp.com'), follow_redirects=True) user = requests[0]['user'] token = requests[0]['token'] time.sleep(1) response = client.post('/reset/' + token, data={ 'password': 'newpassword', ...
token, data={ 'password': 'newpassword', 'password_confirm': 'newpassword' }, follow_redirects=True) assert get_message('INVALID_RESET_PASSWORD_TOKEN') in response.data @pytest.mark.settings(reset_password_within='1 milliseconds') def test_expired_reset_token(client, get_message):
64
64
140
22
41
mattadendorff/flask-security
tests/test_recoverable.py
Python
test_expired_reset_token
test_expired_reset_token
101
117
101
102
5f2bddbb38c54fcdacb87539fe78d8737ad6cc5b
bigcode/the-stack
train
304ad513fa3e2c56638a5003
train
function
@pytest.mark.settings(reset_password_template='custom_security/reset_password.html', forgot_password_template='custom_security/forgot_password.html') def test_custom_reset_templates(client): response = client.get('/reset') assert b'CUSTOM FORGOT PASSWORD' in response.data with capture...
@pytest.mark.settings(reset_password_template='custom_security/reset_password.html', forgot_password_template='custom_security/forgot_password.html') def test_custom_reset_templates(client):
response = client.get('/reset') assert b'CUSTOM FORGOT PASSWORD' in response.data with capture_reset_password_requests() as requests: client.post('/reset', data=dict(email='joe@lp.com'), follow_redirects=True) token = requests[0]['token'] response = client.get('/reset/' + token) as...
.settings(reset_url='/custom_reset') def test_custom_reset_url(client): response = client.get('/custom_reset') assert response.status_code == 200 @pytest.mark.settings(reset_password_template='custom_security/reset_password.html', forgot_password_template='custom_security/forgot_password.h...
64
64
116
32
31
mattadendorff/flask-security
tests/test_recoverable.py
Python
test_custom_reset_templates
test_custom_reset_templates
126
137
126
128
3507c7e5ef5b944df18f536607ca599ffc2c75e9
bigcode/the-stack
train
6b7fe290b3325209e35ed886
train
function
def doit(args) : fields = ["copyright", "openTypeNameDescription", "openTypeNameDesigner", "openTypeNameDesignerURL", "openTypeNameLicense", # General feilds "openTypeNameLicenseURL", "openTypeNameManufacturer", "openTypeNameManufacturerURL", "openTypeOS2CodePageRanges", "openTypeOS...
def doit(args) :
fields = ["copyright", "openTypeNameDescription", "openTypeNameDesigner", "openTypeNameDesignerURL", "openTypeNameLicense", # General feilds "openTypeNameLicenseURL", "openTypeNameManufacturer", "openTypeNameManufacturerURL", "openTypeOS2CodePageRanges", "openTypeOS2UnicodeRanges", "...
#!/usr/bin/env python from __future__ import unicode_literals '''Copy metadata between fonts in different (related) families Usually run against the master (regular) font in each family then data synced within family afterwards''' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2017 SIL I...
251
256
1,436
5
246
DalavanCloud/pysilfont
lib/silfont/scripts/psfcopymeta.py
Python
doit
doit
21
137
21
22
8a88556ef3e42b92deddb9bf6fffe22ef11a2c20
bigcode/the-stack
train
206d7a0429317f780261bef2
train
function
def cmd(): execute("UFO",doit, argspec)
def cmd():
execute("UFO",doit, argspec)
precision) : # Apply same processing to real numbers that normalization will if precision is not None: val = round(float(text), precision) if val == int(val) : val = int(val) # Removed trailing decimal .0 text = str(val) return text def cmd():
64
64
14
4
59
DalavanCloud/pysilfont
lib/silfont/scripts/psfcopymeta.py
Python
cmd
cmd
148
148
148
148
42dcc31134cee9a233b0cc30b6d0b5d19112f5bc
bigcode/the-stack
train
c69dcfc3c49623d4fb70c2d4
train
function
def processnum(text, precision) : # Apply same processing to real numbers that normalization will if precision is not None: val = round(float(text), precision) if val == int(val) : val = int(val) # Removed trailing decimal .0 text = str(val) return text
def processnum(text, precision) : # Apply same processing to real numbers that normalization will
if precision is not None: val = round(float(text), precision) if val == int(val) : val = int(val) # Removed trailing decimal .0 text = str(val) return text
logger.log("Writing updated lib.plist", "P") UFO.writeXMLobject(tlib, tofont.outparams, tofont.ufodir, "lib.plist", True, fobject=True) return def processnum(text, precision) : # Apply same processing to real numbers that normalization will
64
64
65
19
44
DalavanCloud/pysilfont
lib/silfont/scripts/psfcopymeta.py
Python
processnum
processnum
140
145
140
140
1b0dd74e9ef8194e015c955c84c4008f34d6e557
bigcode/the-stack
train
4347e355d52f93e8dbbb8a08
train
class
class SimpleLayer(torch.nn.Module): r"""Basic layer for infinite MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond dtype (tensor.dtype): data type (may be complex for some models) Attribute: u (Parameter): torch container pac...
class SimpleLayer(torch.nn.Module):
r"""Basic layer for infinite MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond dtype (tensor.dtype): data type (may be complex for some models) Attribute: u (Parameter): torch container packaging disentangler tensor u ...
import sys sys.path.append("..") import torch from torch.nn.parameter import Parameter import torch.nn.functional as F import lib.functional as func class SimpleLayer(torch.nn.Module):
39
69
230
7
31
xwkgch/IsoTensor
layer/MERAlayer.py
Python
SimpleLayer
SimpleLayer
8
27
8
8
d76e198111b58f9a488a6cd362b8a20862dd9baf
bigcode/the-stack
train
ff1e2924876f96e62c622f55
train
class
class SimpleTernary(SimpleLayer): r"""single layer for ternary MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond leg_type (tuple): a pair of int number indicating the number of in and out bonds of w (default: (3, 1)) dtype (tenso...
class SimpleTernary(SimpleLayer):
r"""single layer for ternary MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond leg_type (tuple): a pair of int number indicating the number of in and out bonds of w (default: (3, 1)) dtype (tensor.dtype): data type (may be comple...
for some models) Attribute: u (Parameter): torch container packaging disentangler tensor u u.leg_type (tuple): a pair of int number indicating the number of in and out bonds of u ((2, 2) for u) """ def __init__(self, chi_in, chi_out, dtype): assert chi_in > 0 and chi_out > 0 ...
178
178
596
8
170
xwkgch/IsoTensor
layer/MERAlayer.py
Python
SimpleTernary
SimpleTernary
30
73
30
30
fa91b6ecbc9859a67d9174ca2fe92be53f282d59
bigcode/the-stack
train
209cb54b820f9bd8527c509a
train
class
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ResearchhubAccessGroup', fields=[ ('id', models.AutoField(auto_creat...
class Migration(migrations.Migration):
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ResearchhubAccessGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=Fal...
# Generated by Django 2.2 on 2021-06-03 21:49 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration):
42
66
223
7
34
ResearchHub/ResearchHub-Backend-Open
src/researchhub_access_group/migrations/0001_initial.py
Python
Migration
Migration
7
31
7
8
0360ce14d3b76903d44c232a806419231fef5c01
bigcode/the-stack
train
4b963885a9c62346bfb07176
train
class
class TableColumn(object): align = 'left' wrap = 'space' padding = None def __init__(self, name, label=None, width=('weight', 1), format_fn=None, sort_key=None, sort_fn=None, sort_reverse=False): self.name = name self.label = label if label else name ...
class TableColumn(object):
align = 'left' wrap = 'space' padding = None def __init__(self, name, label=None, width=('weight', 1), format_fn=None, sort_key=None, sort_fn=None, sort_reverse=False): self.name = name self.label = label if label else name self.format_fn = for...
return 0 @focus_position.setter def focus_position(self, value): self.listbox.focus_position = value self.listbox._invalidate() @property def row_count(self): return len(self.listbox.body) @property def selection(self): if self.body: # len(self.body) != 0 ...
93
93
310
5
87
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
TableColumn
TableColumn
148
188
148
148
e649a6dfe777cd478b8123e095ab05d030f3dfc9
bigcode/the-stack
train
e5f74c45309655ae49ea5039
train
class
class TableBodyRow(TableRow): column_class = BodyColumns attr_map = {None: 'default'} focus_map = {None: 'selected'}
class TableBodyRow(TableRow):
column_class = BodyColumns attr_map = {None: 'default'} focus_map = {None: 'selected'}
]) def cell(self, i): return self.row[i * 2] def highlight(self): for x in self.contents: x[-1].highlight() def unhighlight(self): for x in self.contents: x[-1].unhighlight() class TableBodyRow(TableRow):
64
64
34
7
57
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
TableBodyRow
TableBodyRow
369
373
369
369
6d45931a68ed864bc7254ad57eef003db26c38f2
bigcode/the-stack
train
8f6095ad25c10bfcf9bca903
train
class
class TableHeaderRow(TableRow): signals = ['column_click'] column_class = HeaderColumns decorate = False def __init__(self, table, *args, **kwargs): self.row = None self.attr_map = {None: 'table_head'} self.focus_map = {None: 'table_head'} self.table = table s...
class TableHeaderRow(TableRow):
signals = ['column_click'] column_class = HeaderColumns decorate = False def __init__(self, table, *args, **kwargs): self.row = None self.attr_map = {None: 'table_head'} self.focus_map = {None: 'table_head'} self.table = table self.contents = [str(x.label) for...
1].highlight() def unhighlight(self): for x in self.contents: x[-1].unhighlight() class TableBodyRow(TableRow): column_class = BodyColumns attr_map = {None: 'default'} focus_map = {None: 'selected'} class TableHeaderRow(TableRow):
66
67
226
7
59
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
TableHeaderRow
TableHeaderRow
376
413
376
376
51d9012aea0342a716c5900d357594b9cd521eef
bigcode/the-stack
train
f0c7596b6c193ad61b947354
train
class
class TableRowsListWalker(ListWalker): def __init__(self, table, sort=None): self.table = table self.sort = sort self.focus = 0 self.rows = [] super().__init__() def __getitem__(self, position): if position < 0 or position >= len(self.rows): raise Ind...
class TableRowsListWalker(ListWalker):
def __init__(self, table, sort=None): self.table = table self.sort = sort self.focus = 0 self.rows = [] super().__init__() def __getitem__(self, position): if position < 0 or position >= len(self.rows): raise IndexError return self.rows[posit...
Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. from functools import cmp_to_key from urwid import * from .decor_widgets import PatternBox from ...
92
92
309
8
83
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
TableRowsListWalker
TableRowsListWalker
16
71
16
16
8dd962a7bfc361dbcdf292f8fbd0ae6e70b7cff8
bigcode/the-stack
train
f3dc274557e1a79bfcfa3133
train
class
class HeaderColumns(Columns): def __init__(self, contents): self.selected_column = None super().__init__(contents) def __setitem__(self, i, v): self.contents[i * 2] = (v, self.contents[i * 2][1])
class HeaderColumns(Columns):
def __init__(self, contents): self.selected_column = None super().__init__(contents) def __setitem__(self, i, v): self.contents[i * 2] = (v, self.contents[i * 2][1])
(v, float): v = '%.03f' % v # If v doesn't match any of the previous options than it might be a Widget. if not isinstance(v, Widget): return Text(v, align=self.align, wrap=self.wrap) return v class HeaderColumns(Columns):
64
64
62
6
57
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
HeaderColumns
HeaderColumns
191
197
191
191
eb33c426decc4ffeba5c3c1694d58b6b64f500bb
bigcode/the-stack
train
de2f7ab08d4799585c66c7a2
train
class
class Table(WidgetWrap): signals = ['select', 'refresh', 'focus', 'delete'] attr_map = {} focus_map = {} row_dict = {} title = '' columns = [] query_data = [] key_columns = None sort_field = None _selectable = True def __init__(self, initial_sort=None, limit=None): ...
class Table(WidgetWrap):
signals = ['select', 'refresh', 'focus', 'delete'] attr_map = {} focus_map = {} row_dict = {} title = '' columns = [] query_data = [] key_columns = None sort_field = None _selectable = True def __init__(self, initial_sort=None, limit=None): self.border = (1, ' ', '...
BodyColumns attr_map = {None: 'default'} focus_map = {None: 'selected'} class TableHeaderRow(TableRow): signals = ['column_click'] column_class = HeaderColumns decorate = False def __init__(self, table, *args, **kwargs): self.row = None self.attr_map = {None: 'table_head'}...
256
256
1,549
6
249
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
Table
Table
416
633
416
416
6003bfede88c1d1cf1492c24de8b37ec2a50b8ae
bigcode/the-stack
train
eb7c95b0c86281f9d04db5da
train
class
class TableCell(WidgetWrap): signals = ['click', 'select'] def __init__(self, table, column, row, value): self.table = table self.column = column self.row = row self.value = value self.contents = self.column._format(self.value) padding = self.column.padding or s...
class TableCell(WidgetWrap):
signals = ['click', 'select'] def __init__(self, table, column, row, value): self.table = table self.column = column self.row = row self.value = value self.contents = self.column._format(self.value) padding = self.column.padding or self.table.padding sel...
.contents[i * 2][1]) class BodyColumns(Columns): def __init__(self, contents, header=None): self.header = header super().__init__(contents) @property def selected_column(self): return self.header.selected_column @selected_column.setter def selected_column(self, value): ...
85
85
285
7
77
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
TableCell
TableCell
214
252
214
214
c1af02b01ab84a221ba94b06a569a497057a512a
bigcode/the-stack
train
a183384acda0dcb4a1373d73
train
class
class BodyColumns(Columns): def __init__(self, contents, header=None): self.header = header super().__init__(contents) @property def selected_column(self): return self.header.selected_column @selected_column.setter def selected_column(self, value): self.header.selec...
class BodyColumns(Columns):
def __init__(self, contents, header=None): self.header = header super().__init__(contents) @property def selected_column(self): return self.header.selected_column @selected_column.setter def selected_column(self, value): self.header.selected_column = value
Columns): def __init__(self, contents): self.selected_column = None super().__init__(contents) def __setitem__(self, i, v): self.contents[i * 2] = (v, self.contents[i * 2][1]) class BodyColumns(Columns):
64
64
70
6
58
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
BodyColumns
BodyColumns
200
211
200
200
f205379d18165ddca2cb95a295ad781a927ca488
bigcode/the-stack
train
42b99c2447ef4471c1af94d2
train
class
class TableRow(WidgetWrap): attr_map = {} focus_map = {} border_char = ' ' column_class = Columns # To be redefined by subclasses. decorate = True _selectable = True def __init__(self, table, data, header=None, cell_click=None, cell_select=None, ...
class TableRow(WidgetWrap):
attr_map = {} focus_map = {} border_char = ' ' column_class = Columns # To be redefined by subclasses. decorate = True _selectable = True def __init__(self, table, data, header=None, cell_click=None, cell_select=None, attr_map=None, focus...
= self.column.padding or self.table.padding self.padding = Padding(self.contents, left=padding, right=padding) self.attr = AttrMap(self.padding, attr_map=row.attr_map, focus_map=row.focus_map) super().__init__(self.attr) def selectable(self): return isinstance(self.row, TableBodyRo...
224
224
748
7
217
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
TableRow
TableRow
255
366
255
255
2f989739f70a625cecfba86cd069e9019074873d
bigcode/the-stack
train
b6f2ffc3c198d74128a67417
train
class
class ScrollingListBox(WidgetWrap): signals = ['select', 'load_more'] def __init__(self, body, infinite=False): self.infinite = infinite self.requery = False self.height = 0 self.listbox = ListBox(body) self.body = self.listbox.body self.ends_visible = self.lis...
class ScrollingListBox(WidgetWrap):
signals = ['select', 'load_more'] def __init__(self, body, infinite=False): self.infinite = infinite self.requery = False self.height = 0 self.listbox = ListBox(body) self.body = self.listbox.body self.ends_visible = self.listbox.ends_visible super()._...
, value): self.rows.remove(value) def next_position(self, position): index = position + 1 if position >= len(self.rows): raise IndexError return index def prev_position(self, position): index = position - 1 if position < 0: raise IndexErr...
152
152
508
9
143
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
Python
ScrollingListBox
ScrollingListBox
75
145
75
75
5888390f3d394bc3e38b43b58ecb4758c9ab9f94
bigcode/the-stack
train
e0a6057d9dc9162ce57ee040
train
function
def next_day(day): """Return next day of the week""" index = days_of_the_week.index(day) return days_of_the_week[(index + 1) % 7]
def next_day(day):
"""Return next day of the week""" index = days_of_the_week.index(day) return days_of_the_week[(index + 1) % 7]
else: return 3600 * (24 - sh + oh - 1) + (60 - sm + om) * 60 days_of_the_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] def next_day(day):
63
64
40
5
58
marcoplaitano/iot-alarm-clock
sources/time_data.py
Python
next_day
next_day
131
134
131
131
dfa5c8d73c03582dc1fdd240b8d3afd03bd4c8f5
bigcode/the-stack
train
514d4092493119bc1388bb35
train
class
class Time: def __init__(self, day="Monday", hour=0, minutes=0): self._day = day self._hour = hour self._minutes = minutes def format(self): """Return string in format 'HH:MM'.""" h = "0" + str(self._hour) if self._hour < 10 else str(self._hour) m = "0" + str(se...
class Time:
def __init__(self, day="Monday", hour=0, minutes=0): self._day = day self._hour = hour self._minutes = minutes def format(self): """Return string in format 'HH:MM'.""" h = "0" + str(self._hour) if self._hour < 10 else str(self._hour) m = "0" + str(self._minutes)...
# @file time_data.py # @author marco # @date 04 Oct 2021 class Time:
25
256
932
3
21
marcoplaitano/iot-alarm-clock
sources/time_data.py
Python
Time
Time
6
123
6
6
276c8d1578f20ca85f64cb375243d8e7a4347dd8
bigcode/the-stack
train
6a41322874aa57c85b0cbfbd
train
function
def format_result(result, refund=None): """Format API response for telegram rendering""" output = '' for item in result: text = item['text'] date = item['date'] response_status = item['status'] emoji = decode_surrogates(status_emoji[response_status]) status = emoji + ...
def format_result(result, refund=None):
"""Format API response for telegram rendering""" output = '' for item in result: text = item['text'] date = item['date'] response_status = item['status'] emoji = decode_surrogates(status_emoji[response_status]) status = emoji + response_status response_tag = i...
d\udd57 ', 'Forgotten': '\ud83d\ude31 ' } status_emoji = { 'New': '\ud83d\udce9 ', 'Actual': '\ud83d\udcd6 ', 'Closed': '\ud83d\udd12 ', } def decode_surrogates(string): return string.encode( 'utf-16', 'surrogatepass').decode( 'utf-16', 'surrogatepass') def format_result(result, r...
107
107
357
8
99
Igorishe/Report_Traker
telegram/services/format_functions.py
Python
format_result
format_result
23
64
23
23
3a7e4b9ba2401450246dab3b371777dbc602d240
bigcode/the-stack
train
396d93170fe0b5113abb3e3b
train
function
def format_to_save(message): """Serialize report objects for POST request""" text = message.text reports = parse_report(text) author_id = message.from_user.id author_username = message.from_user.username to_save = [] for report in reports: obj_to_save = { 'author': author...
def format_to_save(message):
"""Serialize report objects for POST request""" text = message.text reports = parse_report(text) author_id = message.from_user.id author_username = message.from_user.username to_save = [] for report in reports: obj_to_save = { 'author': author_id, 'author_name...
'Система: {system}\n' '____________________________________\n' ) output += line if not output: return 'Эта категория пуста' if len(output) > 4096: return output[:4096] return output def format_to_save(message):
64
64
162
6
57
Igorishe/Report_Traker
telegram/services/format_functions.py
Python
format_to_save
format_to_save
67
86
67
67
676d10f5614a3ee7392f0a7bea0aa26098d5d190
bigcode/the-stack
train
461f3d888f58ddec24ed48d3
train
function
def format_moneyback_to_save(message): """Serialize refund object for POST request""" moneyback = parse_moneyback(message.text) moneyback['author'] = message.from_user.id moneyback['author_name'] = message.from_user.username return moneyback
def format_moneyback_to_save(message):
"""Serialize refund object for POST request""" moneyback = parse_moneyback(message.text) moneyback['author'] = message.from_user.id moneyback['author_name'] = message.from_user.username return moneyback
obj_to_save['tag'] = 'Burning' if 'передать' in report.lower() and 'нечего' in report.lower(): obj_to_save['status'] = 'Closed' to_save.append(obj_to_save) return to_save def format_moneyback_to_save(message):
64
64
57
8
55
Igorishe/Report_Traker
telegram/services/format_functions.py
Python
format_moneyback_to_save
format_moneyback_to_save
89
94
89
89
8b5607f2dec658dfb27c998c56ed36ee4f7164c6
bigcode/the-stack
train
c45a1a27076c49c67149cf39
train
function
def decode_surrogates(string): return string.encode( 'utf-16', 'surrogatepass').decode( 'utf-16', 'surrogatepass')
def decode_surrogates(string):
return string.encode( 'utf-16', 'surrogatepass').decode( 'utf-16', 'surrogatepass')
'Forgotten': '\ud83d\ude31 ' } status_emoji = { 'New': '\ud83d\udce9 ', 'Actual': '\ud83d\udcd6 ', 'Closed': '\ud83d\udd12 ', } def decode_surrogates(string):
64
64
36
7
57
Igorishe/Report_Traker
telegram/services/format_functions.py
Python
decode_surrogates
decode_surrogates
17
20
17
17
6cf23144ac0194cfc412d6ae490361e032e2f80f
bigcode/the-stack
train
a097e543c2b11a16122e6b2e
train
class
class C14_RS485: def __init__(self, SerialPort): self.SerialPort = SerialPort self.BaudRate = 9600 print('Started') # Read frame from serial port # @param self, bytearray(30) bFrame # @return bytearray(30) def SerialRequest(self, bFrame): try: print('Ser...
class C14_RS485:
def __init__(self, SerialPort): self.SerialPort = SerialPort self.BaudRate = 9600 print('Started') # Read frame from serial port # @param self, bytearray(30) bFrame # @return bytearray(30) def SerialRequest(self, bFrame): try: print('Serial initial...') ...
###################################################################################### # Descirption: C14_RS485 Protocol python class # author: Gabriel Zima (z1mEk) # e-mail: gabriel.zima@wp.pl # github: https://github.com/z1mEk/c14_protocol.git # create date: 2018-08-09 # update date: 2019-05-10 ######################...
94
177
593
6
87
z1mEk/c14_protocol
c14_class.py
Python
C14_RS485
C14_RS485
12
71
12
13
15d2e58e1754a06fac98c7177a2f60b57b5ee87a
bigcode/the-stack
train
05ad62e367d2be2dca4faf0d
train
class
class spawner:#spawners spawn characters def __init__(self,world,charID,location,level=1, limit=1, delay=5):#construct requires the list of body parts,name,team,location and other options #like AI level and max limit to spawn self.location = location self.level = level self.limit = l...
class spawner:#spawners spawn characters
def __init__(self,world,charID,location,level=1, limit=1, delay=5):#construct requires the list of body parts,name,team,location and other options #like AI level and max limit to spawn self.location = location self.level = level self.limit = limit self.charID = charID ...
import time class spawner:#spawners spawn characters
13
99
331
10
2
joaompinto/2DExplorer
Game/Spawner.py
Python
spawner
spawner
3
39
3
3
8f26d667a606c347365319108c7d336080a4eca9
bigcode/the-stack
train
a7c2cd6e1e72019cdb367368
train
function
@hug.get(examples="year=2016&firstName=Ryan&lastName=Wiley") def results(year: hug.types.text, firstName: hug.types.text, lastName: hug.types.text): """Returns the results for a given candidate for a given year""" engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,ip,user), cl...
@hug.get(examples="year=2016&firstName=Ryan&lastName=Wiley") def results(year: hug.types.text, firstName: hug.types.text, lastName: hug.types.text):
"""Returns the results for a given candidate for a given year""" engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,ip,user), client_encoding='utf8',echo=False) conn = engine.connect() Base = declarative_base() query = "SELECT * FROM names WHERE election_year = '%s...
s@%s/%s' %(user,pwd,ip,user), client_encoding='utf8',echo=False) conn = engine.connect() Base = declarative_base() query = "SELECT * FROM offices WHERE election_year = '%s'" %(str(year)) df = pd.read_sql(query, conn) return df.reset_index().to_json(orient="records") @hug.get(examples="ye...
123
123
413
43
80
rdubwiley09/election_results_parser
api/api.py
Python
results
results
21
41
21
22
8e33436ebb838ae582136d9315f64ee9724933df
bigcode/the-stack
train
68f0417e2aed62d635d8ac36
train
function
@hug.get(examples="year=2016&city=Southfield") def city(year: hug.types.text, city: hug.types.text): """Returns the results for a given candidate for a given year""" engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,ip,user), client_encoding='utf8',echo=False) conn = engi...
@hug.get(examples="year=2016&city=Southfield") def city(year: hug.types.text, city: hug.types.text):
"""Returns the results for a given candidate for a given year""" engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,ip,user), client_encoding='utf8',echo=False) conn = engine.connect() Base = declarative_base() query = "SELECT * FROM cities WHERE election_year = '%...
['precinct_votes']/output['total_votes'] output.rename(columns={'precinct_votes':'candidate_votes'}) return output.reset_index().to_json(orient="records") @hug.get(examples="year=2016&city=Southfield") def city(year: hug.types.text, city: hug.types.text):
65
65
217
30
35
rdubwiley09/election_results_parser
api/api.py
Python
city
city
87
102
87
88
336e1a2e724bd8015e94b9f80bae385b8b02b211
bigcode/the-stack
train
00f7d1df7bb59c2078954f91
train
function
@hug.get(examples="year=2016") def offices(year: hug.types.text): """Returns all the offices for a given year""" engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,ip,user), client_encoding='utf8',echo=False) conn = engine.connect() Base = declarative_base() query ...
@hug.get(examples="year=2016") def offices(year: hug.types.text):
"""Returns all the offices for a given year""" engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,ip,user), client_encoding='utf8',echo=False) conn = engine.connect() Base = declarative_base() query = "SELECT * FROM offices WHERE election_year = '%s'" %(str(year)) ...
from server_config import user,ip, pwd from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base import pandas as pd import requests from lookup_functions import lookup_office_id @hug.get(examples="year=2016") def offices(year: hug.types.text):
64
64
124
19
44
rdubwiley09/election_results_parser
api/api.py
Python
offices
offices
9
19
9
10
24a54d2d57cb4db0c7f3f5c5d47ba18be370d121
bigcode/the-stack
train
921482c63a09cf78c29434fe
train
function
@hug.get(examples="officeType=congress&district=1&zoom=total") def history(officeType: hug.types.text, district: hug.types.text, zoom: hug.types.text): """Returns the results for a given office for all years. Office types: president, governor, sos, ag, senate, congress, misenate, mihouse, miboe, regenum, regentmsu,...
@hug.get(examples="officeType=congress&district=1&zoom=total") def history(officeType: hug.types.text, district: hug.types.text, zoom: hug.types.text):
"""Returns the results for a given office for all years. Office types: president, governor, sos, ag, senate, congress, misenate, mihouse, miboe, regenum, regentmsu, wsugovernor, miscotus. Four types for zoom: total, county, city, all """ engine = create_engine( 'postgresql://%s:%s@%s/%s' %(user,pwd,...
= pd.read_sql(resultQuery,conn) officeId, districtId = result['office_code'].tolist()[0], result['district_code'].tolist()[0] totalQuery = "Select office_code, district_code, county_code, city_code, ward_number, precinct_number, SUM(precinct_votes) AS total_votes FROM votes WHERE office_code = '%s' AND distric...
256
256
930
42
214
rdubwiley09/election_results_parser
api/api.py
Python
history
history
43
85
43
44
d33f9c446f823cd324ea69024d1819c345b18832
bigcode/the-stack
train
8a0e626a56f16c2fd7f27d6e
train
class
class RecoveryAlert(BaseAlert): def __init__(self, alert_meta, alert_source_meta, config, recovery_manager): super(RecoveryAlert, self).__init__(alert_meta, alert_source_meta, config) self.recovery_manager = recovery_manager self.warning_count = DEFAULT_WARNING_RECOVERIES_COUNT self.critical_count =...
class RecoveryAlert(BaseAlert):
def __init__(self, alert_meta, alert_source_meta, config, recovery_manager): super(RecoveryAlert, self).__init__(alert_meta, alert_source_meta, config) self.recovery_manager = recovery_manager self.warning_count = DEFAULT_WARNING_RECOVERIES_COUNT self.critical_count = DEFAULT_CRITICAL_RECOVERIES_COUN...
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a ...
208
208
696
6
202
likenamehaojie/Apache-Ambari-ZH
ambari-agent/src/main/python/ambari_agent/alerts/recovery_alert.py
Python
RecoveryAlert
RecoveryAlert
31
107
31
32
9bc8f0311695daffdcd433f231041fe2aec0d223
bigcode/the-stack
train
28a67309784dcdbf4c2c7608
train
class
@skipIf(NO_MOCK, NO_MOCK_REASON) class CoreGrainsTestCase(TestCase): ''' Test cases for core grains ''' @skipIf(not salt.utils.is_linux(), 'System is not Linux') def test_gnu_slash_linux_in_os_name(self): ''' Test to return a list of all enabled services ''' _path_exi...
@skipIf(NO_MOCK, NO_MOCK_REASON) class CoreGrainsTestCase(TestCase):
''' Test cases for core grains ''' @skipIf(not salt.utils.is_linux(), 'System is not Linux') def test_gnu_slash_linux_in_os_name(self): ''' Test to return a list of all enabled services ''' _path_exists_map = { '/proc/1/cmdline': False } _p...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Erik Johnson <erik@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import import os import platform # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock ...
174
256
4,094
21
153
fictivekin/salt
tests/unit/grains/core_test.py
Python
CoreGrainsTestCase
CoreGrainsTestCase
34
461
34
35
d9f7f02217e8c5365dfdedf0030d1e0218a64bda
bigcode/the-stack
train
505bd4a4158415ca33ed467b
train
class
class DdtraceRunTest(unittest.TestCase): """Test that celery is patched successfully if run with ddtrace-run.""" def test_autopatch(self): out = subprocess.check_output( ['ddtrace-run', 'python', 'tests/contrib/celery/autopatch.py'] ) assert out.startswith(b'Test success')
class DdtraceRunTest(unittest.TestCase):
"""Test that celery is patched successfully if run with ddtrace-run.""" def test_autopatch(self): out = subprocess.check_output( ['ddtrace-run', 'python', 'tests/contrib/celery/autopatch.py'] ) assert out.startswith(b'Test success')
#!/usr/bin/env python import subprocess import unittest class DdtraceRunTest(unittest.TestCase):
22
64
72
10
11
zhammer/dd-trace-py
tests/contrib/celery/test_autopatch.py
Python
DdtraceRunTest
DdtraceRunTest
6
13
6
6
01991ca3e8a4c129a021f7e778fa22ec8bfa2beb
bigcode/the-stack
train
779a6d72eb98333b58664da3
train
class
class FasterRCNNObjectDetection(ObjectDetectionModelMixin, FasterRCNNModel): """Faster RCNN with object detection loss"""
class FasterRCNNObjectDetection(ObjectDetectionModelMixin, FasterRCNNModel):
"""Faster RCNN with object detection loss"""
"""Faster RCNN with object detection loss""" from ..faster_rcnn import FasterRCNNModel from .mixin import ObjectDetectionModelMixin class FasterRCNNObjectDetection(ObjectDetectionModelMixin, FasterRCNNModel):
48
64
27
16
31
IVRL/Dunit
object_detection/faster_rcnn.py
Python
FasterRCNNObjectDetection
FasterRCNNObjectDetection
5
6
5
5
4219c432ec3de7ec1a86b0e4e04c77dd6570ffd2
bigcode/the-stack
train
0ee18739581ee9dbf9ace271
train
function
def main(): """Package installation entry point.""" setuptools.setup(**setup_params)
def main():
"""Package installation entry point.""" setuptools.setup(**setup_params)
=packages, entry_points={'console_scripts': ['chaos = chaostoolkit.__main__:cli']}, include_package_data=True, install_requires=install_require, tests_require=test_require, setup_requires=pytest_runner, python_requires='>=3.5.*' ) def main():
64
64
17
3
61
ddavtian/chaostoolkit
setup.py
Python
main
main
72
74
72
72
4daa29927a72177523935000a65160257836ea4a
bigcode/the-stack
train
e3e0a328c0297476625af4c9
train
class
class VnicVnicBehPolicy(ManagedObject): """This is VnicVnicBehPolicy class.""" consts = VnicVnicBehPolicyConsts() naming_props = set([]) mo_meta = MoMeta("VnicVnicBehPolicy", "vnicVnicBehPolicy", "beh-vnic", VersionMeta.Version111a, "InputOutput", 0x7f, [], ["read-only"], [u'orgOrg'], [], ["Get", "Set...
class VnicVnicBehPolicy(ManagedObject):
"""This is VnicVnicBehPolicy class.""" consts = VnicVnicBehPolicyConsts() naming_props = set([]) mo_meta = MoMeta("VnicVnicBehPolicy", "vnicVnicBehPolicy", "beh-vnic", VersionMeta.Version111a, "InputOutput", 0x7f, [], ["read-only"], [u'orgOrg'], [], ["Get", "Set"]) prop_meta = { "action":...
"""This module contains the general information for VnicVnicBehPolicy ManagedObject.""" from ...ucscentralmo import ManagedObject from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta from ...ucscentralmeta import VersionMeta class VnicVnicBehPolicyConsts(): ACTION_HW_INHERIT = "hw-inherit"...
138
256
1,014
11
127
ragupta-git/ucscentralsdk
ucscentralsdk/mometa/vnic/VnicVnicBehPolicy.py
Python
VnicVnicBehPolicy
VnicVnicBehPolicy
18
69
18
18
ee6d531dfbf5633387263f687c2efefdd47f684c
bigcode/the-stack
train
ed0993c668022dc686821535
train
class
class VnicVnicBehPolicyConsts(): ACTION_HW_INHERIT = "hw-inherit" ACTION_NONE = "none" INT_ID_NONE = "none" POLICY_OWNER_LOCAL = "local" POLICY_OWNER_PENDING_POLICY = "pending-policy" POLICY_OWNER_POLICY = "policy" POLICY_OWNER_UNSPECIFIED = "unspecified"
class VnicVnicBehPolicyConsts():
ACTION_HW_INHERIT = "hw-inherit" ACTION_NONE = "none" INT_ID_NONE = "none" POLICY_OWNER_LOCAL = "local" POLICY_OWNER_PENDING_POLICY = "pending-policy" POLICY_OWNER_POLICY = "policy" POLICY_OWNER_UNSPECIFIED = "unspecified"
"""This module contains the general information for VnicVnicBehPolicy ManagedObject.""" from ...ucscentralmo import ManagedObject from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta from ...ucscentralmeta import VersionMeta class VnicVnicBehPolicyConsts():
63
64
73
9
53
ragupta-git/ucscentralsdk
ucscentralsdk/mometa/vnic/VnicVnicBehPolicy.py
Python
VnicVnicBehPolicyConsts
VnicVnicBehPolicyConsts
8
15
8
8
6163566c07a1cdf2f456f83bddffb622df775c01
bigcode/the-stack
train
2c9302374d0b6717b59b31bb
train
function
def vectorize_data(data, word_idx, sentence_size, batch_size, candidates_size, max_memory_size, nn=False, max_story_size=1): """ Vectorize stories and queries. If a sentence length < sentence_size, the sentence will be padded with 0's. If a story length < memory_size, the story will be padded with emp...
def vectorize_data(data, word_idx, sentence_size, batch_size, candidates_size, max_memory_size, nn=False, max_story_size=1):
""" Vectorize stories and queries. If a sentence length < sentence_size, the sentence will be padded with 0's. If a story length < memory_size, the story will be padded with empty memories. Empty memories are 1-D arrays of length sentence_size filled with 0's. The answer array is returned as ...
context.append(r) else: r = tokenize(line) r.append('$r') r.append('#' + str(nid)) context.append(r) else: # clear context context = [] return data def vectorize_candidates(candidates, word_idx, sentence_s...
167
167
557
31
136
abhi608/task_oriented_nlp_system
memn2n_src/data_utils2.py
Python
vectorize_data
vectorize_data
129
187
129
129
f0612a25c8b9d731dd149814a008d32d746b3a61
bigcode/the-stack
train
c685e3dc4cf7d24a80200f02
train
function
def parse_dialogs_per_response(lines, candid_dic): ''' Parse dialogs provided in the babi tasks format ''' data = [] context = [] u = None r = None for line in lines: line = line.strip() if line: nid, line = line.split(' ', 1) nid = int(nid) ...
def parse_dialogs_per_response(lines, candid_dic):
''' Parse dialogs provided in the babi tasks format ''' data = [] context = [] u = None r = None for line in lines: line = line.strip() if line: nid, line = line.split(' ', 1) nid = int(nid) if '\t' in line: u, r = l...
a file name, read the file, retrieve the dialogs, and then convert the sentences into a single dialog. If max_length is supplied, any stories longer than max_length tokens will be discarded. ''' with open(f) as f: return parse_dialogs_per_response(f.readlines(), candid_dic) def parse_dialogs_per_re...
74
74
248
11
63
abhi608/task_oriented_nlp_system
memn2n_src/data_utils2.py
Python
parse_dialogs_per_response
parse_dialogs_per_response
82
117
82
82
7552658fa09f6412e55eba03ec23c877aa09f6bd
bigcode/the-stack
train
9d4dac10817898c2e00d2f23
train
function
def load_candidates(data_dir, task_id): assert task_id > 0 and task_id < 7 candidates = [] candidates_f = None candid_dic = {} if task_id == 6: candidates_f = 'dialog-babi-task6-dstc2-candidates.txt' else: candidates_f = 'dialog-babi-candidates.txt' with open(os.path.join(dat...
def load_candidates(data_dir, task_id):
assert task_id > 0 and task_id < 7 candidates = [] candidates_f = None candid_dic = {} if task_id == 6: candidates_f = 'dialog-babi-task6-dstc2-candidates.txt' else: candidates_f = 'dialog-babi-candidates.txt' with open(os.path.join(data_dir, candidates_f)) as f: for ...
stop_words = set(["a", "an", "the"]) fdtype = torch.FloatTensor ldtype = torch.LongTensor if torch.cuda.device_count() > 0: fdtype = torch.cuda.FloatTensor ldtype = torch.cuda.LongTensor def load_candidates(data_dir, task_id):
64
64
164
9
54
abhi608/task_oriented_nlp_system
memn2n_src/data_utils2.py
Python
load_candidates
load_candidates
17
32
17
17
e4b03654182271c50b3f3fd344657b655e5d364e
bigcode/the-stack
train
e228f169f262ff1a0d636125
train
function
def tokenize(sent): '''Return the tokens of a sentence including punctuation. >>> tokenize('Bob dropped the apple. Where is the apple?') ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple'] ''' sent = sent.lower() if sent == '<silence>': return [sent] result = [x.st...
def tokenize(sent):
'''Return the tokens of a sentence including punctuation. >>> tokenize('Bob dropped the apple. Where is the apple?') ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple'] ''' sent = sent.lower() if sent == '<silence>': return [sent] result = [x.strip() for x in re.sp...
candid_dic[line.strip().split(' ', 1)[1]] = i line = tokenize(line.strip())[1:] candidates.append(line) # return candidates,dict((' '.join(cand),i) for i,cand in enumerate(candidates)) return candidates, candid_dic def tokenize(sent):
64
64
161
4
59
abhi608/task_oriented_nlp_system
memn2n_src/data_utils2.py
Python
tokenize
tokenize
35
49
35
35
dfcb24273f3a6dad183f73fe88652600018a3324
bigcode/the-stack
train
1665b70b487ece9cd6e0d39b
train
function
def get_dialogs(f, candid_dic): '''Given a file name, read the file, retrieve the dialogs, and then convert the sentences into a single dialog. If max_length is supplied, any stories longer than max_length tokens will be discarded. ''' with open(f) as f: return parse_dialogs_per_response(f.readl...
def get_dialogs(f, candid_dic):
'''Given a file name, read the file, retrieve the dialogs, and then convert the sentences into a single dialog. If max_length is supplied, any stories longer than max_length tokens will be discarded. ''' with open(f) as f: return parse_dialogs_per_response(f.readlines(), candid_dic)
in f][0] train_data = get_dialogs(train_file, candid_dic) test_data = get_dialogs(test_file, candid_dic) val_data = get_dialogs(val_file, candid_dic) return train_data, test_data, val_data def get_dialogs(f, candid_dic):
64
64
75
9
54
abhi608/task_oriented_nlp_system
memn2n_src/data_utils2.py
Python
get_dialogs
get_dialogs
74
79
74
74
07f00454209b56eee61f79e94f3a6ea1c49814da
bigcode/the-stack
train
801e7fdb7c260fa7fbdaa7df
train
function
def load_dialog_task(data_dir, task_id, candid_dic, isOOV): '''Load the nth task. There are 20 tasks in total. Returns a tuple containing the training and testing data for the task. ''' assert task_id > 0 and task_id < 7 files = os.listdir(data_dir) files = [os.path.join(data_dir, f) for f in ...
def load_dialog_task(data_dir, task_id, candid_dic, isOOV):
'''Load the nth task. There are 20 tasks in total. Returns a tuple containing the training and testing data for the task. ''' assert task_id > 0 and task_id < 7 files = os.listdir(data_dir) files = [os.path.join(data_dir, f) for f in files] s = 'dialog-babi-task{}-'.format(task_id) tra...
x.strip() and x.strip() not in stop_words] if not result: result = ['<silence>'] if result[-1] == '.' or result[-1] == '?' or result[-1] == '!': result = result[:-1] return result def load_dialog_task(data_dir, task_id, candid_dic, isOOV):
77
77
258
17
59
abhi608/task_oriented_nlp_system
memn2n_src/data_utils2.py
Python
load_dialog_task
load_dialog_task
52
71
52
52
2ee030c83d588171eb7a619b1b019159c0d5e9bd
bigcode/the-stack
train