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
0546be3c174d789a59b04fbc
train
function
@pytest.fixture def expiry_time(): return 300
@pytest.fixture def expiry_time():
return 300
@pytest.fixture def get_data(): return 100 @pytest.fixture def dev_account(): return accounts[0] @pytest.fixture def node_account(): return accounts[1] @pytest.fixture def chainlink_fee(): return 1000000000000000000 @pytest.fixture def expiry_time():
64
64
12
7
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
expiry_time
expiry_time
53
55
53
54
7f296681fce079be6906f96dd94dfb1c485fffc8
bigcode/the-stack
train
c93f8b631e8ca809883cad2c
train
function
@pytest.fixture def round_id(): return 1
@pytest.fixture def round_id():
return 1
@pytest.fixture def fee_bps(): return 100 @pytest.fixture def keeper_id(): return 1 @pytest.fixture def pool_duration(): return 3600 @pytest.fixture def pool_threshold(): return 4000000000000000000000 @pytest.fixture def round_id():
64
64
12
7
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
round_id
round_id
83
85
83
84
77559c329098675be13d8a3271a5f5021d000075
bigcode/the-stack
train
232a1080fde68b9419b66a4a
train
class
class okex(Exchange): def describe(self): return self.deep_extend(super(okex, self).describe(), { 'id': 'okex', 'name': 'OKEX', 'countries': ['CN', 'US'], 'version': 'v5', 'rateLimit': 100, 'pro': True, 'certified': True, ...
class okex(Exchange):
def describe(self): return self.deep_extend(super(okex, self).describe(), { 'id': 'okex', 'name': 'OKEX', 'countries': ['CN', 'US'], 'version': 'v5', 'rateLimit': 100, 'pro': True, 'certified': True, 'has': { ...
DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.async_support.base.exchange import Exchange import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.b...
256
256
30,995
6
249
rozmary7london/ccxt
python/ccxt/async_support/okex.py
Python
okex
okex
30
2,940
30
31
f2a12b8809e13b2d34ba36622f701e9bb147050b
bigcode/the-stack
train
ded0ec2740e16de042517d0e
train
function
@app.get("/qrcode", status_code=status.HTTP_200_OK) def get_qrcode(data: str): """Get Countries and their respective states Args: country_name (str): serves as a filter for a particular country Returns: List[Country]: list of countries and their respective states """ img = qrcode....
@app.get("/qrcode", status_code=status.HTTP_200_OK) def get_qrcode(data: str):
"""Get Countries and their respective states Args: country_name (str): serves as a filter for a particular country Returns: List[Country]: list of countries and their respective states """ img = qrcode.make(data) type(img) # qrcode.image.pil.PilImage img.show() img.sa...
.responses import JSONResponse from fastapi import APIRouter, HTTPException, status from bigfastapi.schemas.qrcode_schemas import State app = APIRouter(tags=["qrcode"]) @app.get("/qrcode", status_code=status.HTTP_200_OK) def get_qrcode(data: str):
63
64
136
22
41
Smyja/bigfastapi
bigfastapi/qrcode.py
Python
get_qrcode
get_qrcode
27
45
27
28
86f3a38bde242b67a1ae4533b2684d20d9771830
bigcode/the-stack
train
9c952d8c66808c7f3a7f069b
train
class
class SecurityGroupServerRpcMixin(sg_db_rpc.SecurityGroupServerRpcMixin): @classmethod def get_port_from_device(cls, device): """Get port from the brocade specific db.""" # TODO(shh) context is not being passed as # an argument to this function; # # need to be fixed in:...
class SecurityGroupServerRpcMixin(sg_db_rpc.SecurityGroupServerRpcMixin): @classmethod
def get_port_from_device(cls, device): """Get port from the brocade specific db.""" # TODO(shh) context is not being passed as # an argument to this function; # # need to be fixed in: # file: neutron/db/securtygroups_rpc_base.py # function: securitygroup_rule...
_state(rpc_context, port_id, False) else: entry = {'device': device, 'exists': False} LOG.debug("%s can not be found in database", device) return entry class SecurityGroupServerRpcMixin(sg_db_rpc.SecurityGroupServerRpcMixin): @classmethod
65
65
217
20
44
gampel/neutron
neutron/plugins/brocade/NeutronPlugin.py
Python
SecurityGroupServerRpcMixin
SecurityGroupServerRpcMixin
140
165
140
142
62deb87ffc06aa115376683ecff486549eceb513
bigcode/the-stack
train
d10f07e947091b9aa80d65de
train
class
class BridgeRpcCallbacks(object): """Agent callback.""" target = messaging.Target(version='1.2') # Device names start with "tap" # history # 1.1 Support Security Group RPC # 1.2 Support get_devices_details_list def get_device_details(self, rpc_context, **kwargs): """Agent reque...
class BridgeRpcCallbacks(object):
"""Agent callback.""" target = messaging.Target(version='1.2') # Device names start with "tap" # history # 1.1 Support Security Group RPC # 1.2 Support get_devices_details_list def get_device_details(self, rpc_context, **kwargs): """Agent requests device details.""" ag...
The SSH username to use')), cfg.StrOpt('password', default='', secret=True, help=_('The SSH password to use')), cfg.StrOpt('ostype', default='NOS', help=_('Currently unused')) ] PHYSICAL_INTERFACE_OPTS = [cfg.StrOpt('physi...
125
125
418
6
119
gampel/neutron
neutron/plugins/brocade/NeutronPlugin.py
Python
BridgeRpcCallbacks
BridgeRpcCallbacks
80
137
80
80
29f53ebbc8d6c9d7770abfb736cafe7079869b2e
bigcode/the-stack
train
b830fb9f034169e39e895ba2
train
class
class BrocadePluginV2(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin, extraroute_db.ExtraRoute_db_mixin, SecurityGroupServerRpcMixin, l3_agentschedulers_db.L3AgentSchedulerDbMixin, a...
class BrocadePluginV2(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin, extraroute_db.ExtraRoute_db_mixin, SecurityGroupServerRpcMixin, l3_agentschedulers_db.L3AgentSchedulerDbMixin, a...
"""BrocadePluginV2 is a Neutron plugin. Provides L2 Virtual Network functionality using VDX. Upper layer driver class that interfaces to NETCONF layer below. """ def __init__(self): """Initialize Brocade Plugin. Specify switch address and db configuration. """ su...
target = messaging.Target(topic=topic, version='1.0') self.client = n_rpc.get_client(target) self.topic_network_delete = topics.get_topic_name(topic, topics.NETWORK, topics.DELETE...
256
256
2,456
80
176
gampel/neutron
neutron/plugins/brocade/NeutronPlugin.py
Python
BrocadePluginV2
BrocadePluginV2
200
503
200
206
96e78d0328106a67c68dce509f4b09407e0661a5
bigcode/the-stack
train
47c7497e08593fb47e6f2348
train
class
class AgentNotifierApi(sg_rpc.SecurityGroupAgentRpcApiMixin): """Agent side of the linux bridge rpc API. API version history: 1.0 - Initial version. 1.1 - Added get_active_networks_info, create_dhcp_port, and update_dhcp_port methods. """ def __init__(self, topic): ...
class AgentNotifierApi(sg_rpc.SecurityGroupAgentRpcApiMixin):
"""Agent side of the linux bridge rpc API. API version history: 1.0 - Initial version. 1.1 - Added get_active_networks_info, create_dhcp_port, and update_dhcp_port methods. """ def __init__(self, topic): self.topic = topic target = messaging.Target(topic=...
extend the db model to include device owners # make it appears that the device owner is of type network if port: port['device'] = device port['device_owner'] = AGENT_OWNER_PREFIX port['binding:vif_type'] = 'bridge' return port class AgentNotifierApi(sg_rpc.Se...
77
77
257
14
62
gampel/neutron
neutron/plugins/brocade/NeutronPlugin.py
Python
AgentNotifierApi
AgentNotifierApi
168
197
168
168
5f2d2fa92a79619100562c960e48604ce7ab5304
bigcode/the-stack
train
f4a1ce2824642884c4af5fbf
train
function
def find(root, key): if root is None: return None if key < root.key: return find(root.left, key) elif key > root.key: return find(root.right, key) else: return root
def find(root, key):
if root is None: return None if key < root.key: return find(root.left, key) elif key > root.key: return find(root.right, key) else: return root
from Tree.commons import insert, print_tree, is_leaf def find(root, key):
18
64
53
6
11
suyash248/data_structures
Tree/pairsWithGivenSum.py
Python
find
find
3
11
3
3
0ab2e829b4dce21598243b61c0aeb7a73880fb6d
bigcode/the-stack
train
b4cfaf41feb21e9756fd6d95
train
function
def pair_with_sum_v1(root, sum, parent=None): if root is None: return False parent = parent or root remaining = abs(sum - root.key) # If we don't use parent, we won't be able to find a pair if both elements of pair are at same level. found = find(parent, remaining) if found: ret...
def pair_with_sum_v1(root, sum, parent=None):
if root is None: return False parent = parent or root remaining = abs(sum - root.key) # If we don't use parent, we won't be able to find a pair if both elements of pair are at same level. found = find(parent, remaining) if found: return (root.key, found.key) else: fo...
find(root.left, key) elif key > root.key: return find(root.right, key) else: return root # Time complexity < O(nlog(n)) # Space complexity: O(1), (not considering recursion stack) def pair_with_sum_v1(root, sum, parent=None):
64
64
121
13
51
suyash248/data_structures
Tree/pairsWithGivenSum.py
Python
pair_with_sum_v1
pair_with_sum_v1
15
27
15
15
da56e08897d71713a376a710dc63326af8974a36
bigcode/the-stack
train
80893139281c2ddf1b7263b8
train
function
def pairs_with_sum_v2(root, sum): from Array.pairsWithSumInSortedArray import find_pair inorder_traversal = [] inorder(root, inorder_traversal) return find_pair(inorder_traversal, sum)
def pairs_with_sum_v2(root, sum):
from Array.pairsWithSumInSortedArray import find_pair inorder_traversal = [] inorder(root, inorder_traversal) return find_pair(inorder_traversal, sum)
, inorder_traversal=[]): if root: inorder(root.left, inorder_traversal) inorder_traversal.append(root.key) inorder(root.right, inorder_traversal) # Time complexity: O(n) # Space complexity: O(n) def pairs_with_sum_v2(root, sum):
64
64
52
10
54
suyash248/data_structures
Tree/pairsWithGivenSum.py
Python
pairs_with_sum_v2
pairs_with_sum_v2
51
55
51
51
ab7216d1adc2f39867dcfe012cecc1f28c40a564
bigcode/the-stack
train
d4ce74e6cc747fdd63f767d3
train
function
def inorder(root, inorder_traversal=[]): if root: inorder(root.left, inorder_traversal) inorder_traversal.append(root.key) inorder(root.right, inorder_traversal)
def inorder(root, inorder_traversal=[]):
if root: inorder(root.left, inorder_traversal) inorder_traversal.append(root.key) inorder(root.right, inorder_traversal)
if found: pair = (root.key, found.key) pairs.append(pair) pairs_with_sum_v1(root.left, sum, parent=root, pairs=pairs) or pairs_with_sum_v1(root.right, sum, parent=root, pairs=pairs) def inorder(root, inorder_traversal=[]):
64
64
43
10
54
suyash248/data_structures
Tree/pairsWithGivenSum.py
Python
inorder
inorder
43
47
43
43
27e24442c44f521bfed5176e636e670dc2ee080f
bigcode/the-stack
train
d13b3e2501d8fb88ed6dfa55
train
function
def pairs_with_sum_v1(root, sum, parent=None, pairs=[]): if root is None: return False parent = parent or root remaining = abs(sum - root.key) # If we don't use parent, we won't be able to find a pair if both elements of pair are at same level. found = find(parent, remaining) if found: ...
def pairs_with_sum_v1(root, sum, parent=None, pairs=[]):
if root is None: return False parent = parent or root remaining = abs(sum - root.key) # If we don't use parent, we won't be able to find a pair if both elements of pair are at same level. found = find(parent, remaining) if found: pair = (root.key, found.key) pairs.append...
if found: return (root.key, found.key) else: found = pair_with_sum_v1(root.left, sum, root) or pair_with_sum_v1(root.right, sum, root) return found def pairs_with_sum_v1(root, sum, parent=None, pairs=[]):
64
64
131
16
47
suyash248/data_structures
Tree/pairsWithGivenSum.py
Python
pairs_with_sum_v1
pairs_with_sum_v1
29
40
29
29
384fb59b37521ba3030eec30c1f32a332c567134
bigcode/the-stack
train
005a2c37481a6c1c938c01e1
train
class
class DERTest(unittest.TestCase): """ Test Diacritic Error Rate with and without Case Ending This is done by changing random diacritics and checking wether the DER function outputs align with the changes that we made. """ def setUp(self): self.case_ending_change = 2000 s...
class DERTest(unittest.TestCase):
""" Test Diacritic Error Rate with and without Case Ending This is done by changing random diacritics and checking wether the DER function outputs align with the changes that we made. """ def setUp(self): self.case_ending_change = 2000 self.not_case_ending_change = 5000 ...
""" DER Test Module """ import os import unittest import random from diacritization_evaluation.der import calculate_der from diacritization_evaluation.util import ( calculate_rate, extract_haraqat, get_case_ending_indices_from_un_diacritized_txt, get_different_haraqah, combine_txt_and_haraqat, ) ...
82
161
537
7
75
almodhfer/diacritization_evaluation
diacritization_evaluation/tests/der_test.py
Python
DERTest
DERTest
18
73
18
18
08e94f084d6ce733714fc6279db5edc3732ffcdd
bigcode/the-stack
train
aaeeb1a9bce59dca243253cf
train
class
class Report(object): def __init__(self, stuid, password, data_path): self.stuid = stuid self.password = password self.data_path = data_path def report(self): loginsuccess = False retrycount = 2 while (not loginsuccess) and retrycount: session = self....
class Report(object):
def __init__(self, stuid, password, data_path): self.stuid = stuid self.password = password self.data_path = data_path def report(self): loginsuccess = False retrycount = 2 while (not loginsuccess) and retrycount: session = self.login() co...
# encoding=utf8 import requests import json import time import datetime import pytz import re import sys import argparse import PIL import io try: from PIL import Image except ImportError: import Image import pytesseract from bs4 import BeautifulSoup class Report(object):
68
256
1,252
4
63
Morfit/USTC-ncov-AutoReport
report.py
Python
Report
Report
19
120
19
19
bae6403a28d3576f0491f1476a5fdf9151d9b474
bigcode/the-stack
train
cc227a31ef15996477995b0e
train
class
class MCMC: def __init__(self, model, observations = [], chain_length = 100, ensemble = None, likelihood_dictionary = None, walkers = 3, epsilon = 1E-6, cutoff = 50, flat = True, clean_chains = True): import copy import numpy as np ...
class MCMC:
def __init__(self, model, observations = [], chain_length = 100, ensemble = None, likelihood_dictionary = None, walkers = 3, epsilon = 1E-6, cutoff = 50, flat = True, clean_chains = True): import copy import numpy as np "...
class MCMC:
5
256
6,739
5
0
MaxRamgraber/Simple-AEM-Toolbox
Manuscript files/toolbox_MCMC.py
Python
MCMC
MCMC
1
770
1
2
64fda3609662fefd7ecbe5bc80802918261be33a
bigcode/the-stack
train
115f2f05761a83d093c8c60b
train
function
def weighted_avg_and_std(values, weights): """ Return the weighted average and standard deviation. values, weights -- Numpy ndarrays with the same shape. """ import numpy as np # print(values.shape) # print(weights.shape) average = np.average(values, we...
def weighted_avg_and_std(values, weights):
""" Return the weighted average and standard deviation. values, weights -- Numpy ndarrays with the same shape. """ import numpy as np # print(values.shape) # print(weights.shape) average = np.average(values, weights=weights,axis = 0) # Fast and num...
(values, weights=weights,axis = 0) # # Fast and numerically precise: # variance = np.average((values-average)**2, weights=weights,axis = 0) # # return (average, np.sqrt(variance)) def weighted_avg_and_std(values, weights):
63
64
111
9
54
MaxRamgraber/Simple-AEM-Toolbox
Manuscript files/toolbox_MCMC.py
Python
weighted_avg_and_std
weighted_avg_and_std
811
826
811
811
9b7527a1d07f134cf31707a9ea26c4dc0ee7b4f5
bigcode/the-stack
train
abd6b951e899abff7850484d
train
class
class Group: def __init__(self, name=None, header=None, footer=None, id=None): self.name = name self.header = header self.footer = footer self.id = id def __repr__(self): return "%s:%s" % (self.id, self.name) def __eq__(self, other): return (self.id is None...
class Group:
def __init__(self, name=None, header=None, footer=None, id=None): self.name = name self.header = header self.footer = footer self.id = id def __repr__(self): return "%s:%s" % (self.id, self.name) def __eq__(self, other): return (self.id is None or other.id i...
from sys import maxsize class Group:
9
64
128
3
5
ilyaYarosh88/barancev_round2
model/group.py
Python
Group
Group
5
23
5
6
540244ef2bc39abb276a68d95a8ee0d68fea5620
bigcode/the-stack
train
e20cff061f97cdb1aa49f085
train
function
def get_feature_sleep(tdf, sampling): X_axes = utils.as_float64(tdf.values[:, 1:]) result_axes = feature_set.compute_extra_features(X_axes, sampling) return result_axes
def get_feature_sleep(tdf, sampling):
X_axes = utils.as_float64(tdf.values[:, 1:]) result_axes = feature_set.compute_extra_features(X_axes, sampling) return result_axes
.mode.chained_assignment = None # default='warn' col = ["HEADER_TIME_STAMP","X_ACCELERATION_METERS_PER_SECOND_SQUARED", "Y_ACCELERATION_METERS_PER_SECOND_SQUARED","Z_ACCELERATION_METERS_PER_SECOND_SQUARED"] def get_feature_sleep(tdf, sampling):
64
64
43
9
55
binodthapachhetry/SWaN
build/lib/SWaN_accel/swan_first_pass.py
Python
get_feature_sleep
get_feature_sleep
14
17
14
14
8228d0806905239daae2a4e7a313c6199a3ac2c6
bigcode/the-stack
train
0448dd5fe3edf09a43ebb071
train
function
def main(df=None, file_path=None,sampling_rate=None): if(df is None) or (file_path is None) or (sampling_rate is None): print("One or all input arguments missing.") return try: import importlib.resources as pkg_resources except ImportError: # Try backported to PY<37 `import...
def main(df=None, file_path=None,sampling_rate=None):
if(df is None) or (file_path is None) or (sampling_rate is None): print("One or all input arguments missing.") return try: import importlib.resources as pkg_resources except ImportError: # Try backported to PY<37 `importlib_resources`. import importlib_resources as p...
import pickle, datetime import pandas as pd import numpy as np from SWaN_accel import config from SWaN_accel import utils from SWaN_accel import feature_set pd.options.mode.chained_assignment = None # default='warn' col = ["HEADER_TIME_STAMP","X_ACCELERATION_METERS_PER_SECOND_SQUARED", "Y_ACCELERATION_METERS...
156
168
563
13
142
binodthapachhetry/SWaN
build/lib/SWaN_accel/swan_first_pass.py
Python
main
main
20
73
20
21
7bfb4ef96772665a7177ed85467919df2befcb81
bigcode/the-stack
train
181b7830d6558ecc4874bfd9
train
function
def closeSshConnection(ssh_client): if ssh_client is not None: ssh_client.close()
def closeSshConnection(ssh_client):
if ssh_client is not None: ssh_client.close()
') ssh_client = paramiko.SSHClient() ssh_client.load_system_host_keys() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connecting to the k8s Master ssh_client.connect(**datos) return ssh_client def closeSshConnection(ssh_client):
64
64
22
9
54
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
closeSshConnection
closeSshConnection
112
114
112
112
d0bac41c1175f0af01244d6328353a71b3d92deb
bigcode/the-stack
train
e89442301fda2c57a7aa4600
train
function
def startEtm(paas_type): print('Deploying the ETM....') start_etm_on_k8s_command = 'kubectl create' if(paas_type == 'openstack'): start_etm_on_k8s_command += ' -f /kubernetes/ek/storage-class/openstack-storage-class.yaml' else: start_etm_on_k8s_command += ' -f /kubernetes/ek/storage-clas...
def startEtm(paas_type):
print('Deploying the ETM....') start_etm_on_k8s_command = 'kubectl create' if(paas_type == 'openstack'): start_etm_on_k8s_command += ' -f /kubernetes/ek/storage-class/openstack-storage-class.yaml' else: start_etm_on_k8s_command += ' -f /kubernetes/ek/storage-class/aws-storage-class.yaml'...
print('YAML as string modified: ' + yaml_as_string_modified) # writeFile(os.environ['PWD'] + '/cluster_api2.yml', yaml.dump(cluster_api_spec_as_dict, default_flow_style=False)) # #+ pathFile,yaml_as_string_modified) def startEtm(paas_type):
64
64
141
8
56
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
startEtm
startEtm
182
192
182
182
712d968e0c3d8148fb5891ff8483082b47f5d641
bigcode/the-stack
train
79009eb34d5e5d287fb56b8c
train
function
def startK8(args, dockerComposeProject): if(args.command == 'stop'): stopEpm(args, dockerComposeProject) elif(args.command == 'start'): info = checkParametersByPaas(args) epm_url = startAndWaitForEpm(args, dockerComposeProject) # Start EPM if(epm_url): #...
def startK8(args, dockerComposeProject):
if(args.command == 'stop'): stopEpm(args, dockerComposeProject) elif(args.command == 'start'): info = checkParametersByPaas(args) epm_url = startAndWaitForEpm(args, dockerComposeProject) # Start EPM if(epm_url): # STEP 1: REPLACE HERE WITH THE EPM IP !!!...
and args.paas_user and args.paas_pass and args.paas_project_name and args.ansible_file): interface_info = [{"key": "type", "value": args.paas_type}, {"key": "username", "value": args.paas_user}, {"key": "password", ...
256
256
903
10
245
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
startK8
startK8
222
316
222
222
0b8f358a1398862826f94e8c45d64fe6380ccfc4
bigcode/the-stack
train
5de9dfcde48777bcacbfde77
train
function
def uploadFile(file, target_path, ssh_client): print('Uploading file') entrada, salida, error = ssh_client.exec_command( 'sudo chmod 777 /etc/kubernetes/manifests/kube-apiserver.yaml') ftp_client = ssh_client.open_sftp() ftp_client.put('kube-apiserver.yaml', '/etc/kubernetes/m...
def uploadFile(file, target_path, ssh_client):
print('Uploading file') entrada, salida, error = ssh_client.exec_command( 'sudo chmod 777 /etc/kubernetes/manifests/kube-apiserver.yaml') ftp_client = ssh_client.open_sftp() ftp_client.put('kube-apiserver.yaml', '/etc/kubernetes/manifests/kube-apiserver.yaml') ftp_client.c...
8s cluster configuration:', admin_conf_content) # Setting the kubectl to access the cluster kube_file = open(os.environ['HOME'] + '/.kube/config', 'w') kube_file.write(admin_conf_content) kube_file.close() def uploadFile(file, target_path, ssh_client):
64
64
123
11
53
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
uploadFile
uploadFile
130
139
130
130
9596dc88943fdaa04071d602df6770be75b8f7b5
bigcode/the-stack
train
062ef3b9f0586fc30c9dc548
train
function
def modifyNodePortRangePort(ssh_client): if ssh_client is not None: yaml = YAML() entrada, salida, error = ssh_client.exec_command( 'sudo cat /etc/kubernetes/manifests/kube-apiserver.yaml') cluster_api_spec_from_k8s_cluster = salida.read() print('Yaml as dict:', cluster_a...
def modifyNodePortRangePort(ssh_client):
if ssh_client is not None: yaml = YAML() entrada, salida, error = ssh_client.exec_command( 'sudo cat /etc/kubernetes/manifests/kube-apiserver.yaml') cluster_api_spec_from_k8s_cluster = salida.read() print('Yaml as dict:', cluster_api_spec_from_k8s_cluster) cluster...
.yaml', '/etc/kubernetes/manifests/kube-apiserver.yaml') ftp_client.close() entrada, salida, error = ssh_client.exec_command( 'sudo chmod 600 /etc/kubernetes/manifests/kube-apiserver.yaml') def modifyNodePortRangePort(ssh_client):
64
64
190
10
54
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
modifyNodePortRangePort
modifyNodePortRangePort
142
157
142
142
72f88245105cb482bf3fd3935c07c7a2bdfe54e9
bigcode/the-stack
train
ef07b4cde67812c710b277dd
train
function
def stopEpm(args, dockerComposeProject): print('Stopping EPM...') if(not args.dev): stopEpmCommand = epmComposeCommandPrefix + \ dockerComposeProject + " down" result = subprocess.call(shlex.split(stopEpmCommand), stderr=FNULL)
def stopEpm(args, dockerComposeProject):
print('Stopping EPM...') if(not args.dev): stopEpmCommand = epmComposeCommandPrefix + \ dockerComposeProject + " down" result = subprocess.call(shlex.split(stopEpmCommand), stderr=FNULL)
PM adapter', 'EPM is ready now!') return epm_url else: print(FAIL + 'Error on start EPM' + ENDC) print('') stopEpm(args, dockerComposeProject) exit(1) def stopEpm(args, dockerComposeProject):
64
64
62
10
54
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
stopEpm
stopEpm
63
68
63
63
1497308fde4f0e3779ce9a85032e4f51d83e08d8
bigcode/the-stack
train
7a593954fed7d85340947927
train
function
def checkParametersByPaas(args): interface_info = [] if(args.paas_type and args.paas_type == 'openstack' and args.paas_url and args.paas_user and args.paas_pass and args.paas_project_name and args.ansible_file): interface_info = [{"key": "type", "value": args.paas_type}, {"key"...
def checkParametersByPaas(args):
interface_info = [] if(args.paas_type and args.paas_type == 'openstack' and args.paas_url and args.paas_user and args.paas_pass and args.paas_project_name and args.ansible_file): interface_info = [{"key": "type", "value": args.paas_type}, {"key": "username", ...
-storage-class.yaml' else: start_etm_on_k8s_command += ' -f /kubernetes/ek/storage-class/aws-storage-class.yaml' start_etm_on_k8s_command += ' -f /kubernetes/ek -f /kubernetes/ek/volumes' subprocess.call(shlex.split(start_etm_on_k8s_command)) def checkParametersByPaas(args):
84
84
280
8
76
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
checkParametersByPaas
checkParametersByPaas
195
219
195
195
f15a33ab0ab83be441c51c03f4bb2d84422ed465
bigcode/the-stack
train
cf88ee537c94e4575f6bf01f
train
function
def startAndWaitForEpm(args, dockerComposeProject): if(args.dev): result = 0 else: if(args.paas_domain): searchAndReplace(epmComposeFilePath, "entrypoint: python -m run --register-adapter elastest-epm elastest-epm-adapter-ansible", "entrypoint: python -m ...
def startAndWaitForEpm(args, dockerComposeProject):
if(args.dev): result = 0 else: if(args.paas_domain): searchAndReplace(epmComposeFilePath, "entrypoint: python -m run --register-adapter elastest-epm elastest-epm-adapter-ansible", "entrypoint: python -m run --register-adapter elastest-epm elastest-epm-ada...
epm_port = "8180" epm_adapter_ansible_service_name = "epm-adapter-ansible" epm_adapter_ansible_port = "50052" ansiblePath = "/data/ansible" epmComposeCommandPrefix = "docker-compose -f ../epm/deploy/docker-compose.yml -p " epmComposeFilePath = "../epm/deploy/docker-compose.yml" def startAndWaitForEpm(args, dockerCompo...
96
96
320
13
83
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
startAndWaitForEpm
startAndWaitForEpm
31
60
31
31
213e3d41cf5880d524f655029c8e622d9590b12c
bigcode/the-stack
train
f83c819aa17d66a03a85520c
train
function
def setK8sClientConfigurarion(ssh_client): if ssh_client is not None: entrada, salida, error = ssh_client.exec_command( 'sudo cat /etc/kubernetes/admin.conf') # Retrieve k8s client configuration from the cluster admin_conf_content = salida.read() print('K8s cluster config...
def setK8sClientConfigurarion(ssh_client):
if ssh_client is not None: entrada, salida, error = ssh_client.exec_command( 'sudo cat /etc/kubernetes/admin.conf') # Retrieve k8s client configuration from the cluster admin_conf_content = salida.read() print('K8s cluster configuration:', admin_conf_content) # Se...
_policy(paramiko.AutoAddPolicy()) # Connecting to the k8s Master ssh_client.connect(**datos) return ssh_client def closeSshConnection(ssh_client): if ssh_client is not None: ssh_client.close() def setK8sClientConfigurarion(ssh_client):
64
64
121
13
51
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
setK8sClientConfigurarion
setK8sClientConfigurarion
117
127
117
117
40f87636f33911bb2b7aca0ea3e7b49490ac07e2
bigcode/the-stack
train
664f69550b6feb7256fa8517
train
function
def getSshConnection(k8s_host): HOST = k8s_host PUERTO = 22 USUARIO = 'ubuntu' datos = dict(hostname=HOST, port=PUERTO, username=USUARIO, key_filename=ansiblePath + '/key') # key_filename='/home/frdiaz/.elastest/k8s/key') # ansiblePath + '/key') ssh_client = paramiko.SSHClien...
def getSshConnection(k8s_host):
HOST = k8s_host PUERTO = 22 USUARIO = 'ubuntu' datos = dict(hostname=HOST, port=PUERTO, username=USUARIO, key_filename=ansiblePath + '/key') # key_filename='/home/frdiaz/.elastest/k8s/key') # ansiblePath + '/key') ssh_client = paramiko.SSHClient() ssh_client.load_system_h...
:', admin_conf_content) # # Setting the kubectl to access the cluster # kube_file = open('~/.kube/config', 'w') # kube_file.write(admin_conf_content) # kube_file.close() # ssh_client.close() def getSshConnection(k8s_host):
64
64
146
10
54
elastest/elastest-toolbox
scripts/k8sDeployment.py
Python
getSshConnection
getSshConnection
96
109
96
96
cc667dd373b547437aa5c88093553822d09f6385
bigcode/the-stack
train
d3e3f9d9a627ba784931814f
train
class
class PageTree(object): """ Structure to manipulate a set of pages. Allows filtering efficiently by Site. """ def __init__(self): """Constructor. While using dict values would be faster for the remove() operation, keeping list values is important, because the order in whi...
class PageTree(object):
""" Structure to manipulate a set of pages. Allows filtering efficiently by Site. """ def __init__(self): """Constructor. While using dict values would be faster for the remove() operation, keeping list values is important, because the order in which the pages were...
+= 1 StoredPage.SPpath = path StoredPage.SPstore = shelve.open(path) self.SPkey = str(self) self.SPcontentSet = False def SPgetContents(self): """Get stored content.""" return StoredPage.SPstore[self.SPkey] def SPsetContents(self, contents): ""...
149
149
497
5
144
jayvdb/pywikibot-core
scripts/interwiki.py
Python
PageTree
PageTree
710
784
710
711
f0a4c8d52c0922fcee9308974dafac3fffa0295c
bigcode/the-stack
train
ab87370622ba18bb1e1945bb
train
class
class LinkMustBeRemoved(SaveError): # noqa """ An interwiki link has to be removed, but this can't be done because of user preferences or because the user chose not to change the page. """
class LinkMustBeRemoved(SaveError): # noqa
""" An interwiki link has to be removed, but this can't be done because of user preferences or because the user chose not to change the page. """
unicode = str docuReplacements = { '&pagegenerators_help;': pagegenerators.parameterHelp } class SaveError(pywikibot.Error): """An attempt to save a page with changed interwiki has failed.""" class LinkMustBeRemoved(SaveError): # noqa
63
64
49
13
50
jayvdb/pywikibot-core
scripts/interwiki.py
Python
LinkMustBeRemoved
LinkMustBeRemoved
380
385
380
381
4bae5767bdd61a99884b1d047926bc6d42a47652
bigcode/the-stack
train
f874757d33b74115c09c8ab2
train
class
class Subject(interwiki_graph.Subject): """ Class to follow the progress of a single 'subject'. (i.e. a page with all its translations) Subject is a transitive closure of the binary relation on Page: "has_a_langlink_pointing_to". A formal way to compute that closure would be: With P a s...
class Subject(interwiki_graph.Subject):
""" Class to follow the progress of a single 'subject'. (i.e. a page with all its translations) Subject is a transitive closure of the binary relation on Page: "has_a_langlink_pointing_to". A formal way to compute that closure would be: With P a set of pages, NL ('NextLevel') a function ...
yield page except KeyError: pass def __len__(self): """Length of the object.""" return self.size def add(self, page): """Add a page to the tree.""" site = page.site if site not in self.tree: self.tree[site] = [] se...
256
256
10,927
7
248
jayvdb/pywikibot-core
scripts/interwiki.py
Python
Subject
Subject
787
2,078
787
788
fdd68982c348b6f31753d6b99ee201a2ab022a40
bigcode/the-stack
train
d58e9c20a622f84a44e0b9bc
train
class
class InterwikiBot(object): """ A class keeping track of a list of subjects. It controls which pages are queried from which languages when. """ def __init__(self, conf=None): """Constructor.""" self.subjects = [] # We count how many pages still need to be loaded per site. ...
class InterwikiBot(object):
""" A class keeping track of a list of subjects. It controls which pages are queried from which languages when. """ def __init__(self, conf=None): """Constructor.""" self.subjects = [] # We count how many pages still need to be loaded per site. # This allows us to f...
Page.site] = linkedPage for expectedPage in expectedPages - linkedPages: if expectedPage != page: try: linkedPage = linkedPagesDict[expectedPage.site] pywikibot.warning( ...
256
256
2,077
6
250
jayvdb/pywikibot-core
scripts/interwiki.py
Python
InterwikiBot
InterwikiBot
2,081
2,349
2,081
2,082
a2379571d20ebe384e61453dfd6960f4429f8d16
bigcode/the-stack
train
05de0481e1186ef48061d58a
train
class
class GiveUpOnPage(pywikibot.Error): """User chose not to work on this page and its linked pages any more.""" pass
class GiveUpOnPage(pywikibot.Error):
"""User chose not to work on this page and its linked pages any more.""" pass
.""" class LinkMustBeRemoved(SaveError): # noqa """ An interwiki link has to be removed, but this can't be done because of user preferences or because the user chose not to change the page. """ class GiveUpOnPage(pywikibot.Error):
63
64
32
12
51
jayvdb/pywikibot-core
scripts/interwiki.py
Python
GiveUpOnPage
GiveUpOnPage
388
392
388
389
ad54e6e008aa316b67d3484adc06a202ec41e6dd
bigcode/the-stack
train
5660d272fd62a364577f3579
train
function
def botMayEdit(page): """Test for allowed edits.""" tmpl = [] try: tmpl, loc = moved_links[page.site.code] except KeyError: pass if not isinstance(tmpl, list): tmpl = [tmpl] try: tmpl += ignoreTemplates[page.site.code] except KeyError: pass tmpl +=...
def botMayEdit(page):
"""Test for allowed edits.""" tmpl = [] try: tmpl, loc = moved_links[page.site.code] except KeyError: pass if not isinstance(tmpl, list): tmpl = [tmpl] try: tmpl += ignoreTemplates[page.site.code] except KeyError: pass tmpl += ignoreTemplates['_def...
useFrom else old[modifying[0]]} mcomment += i18n.twtranslate(insite, commentname, changes) mods = i18n.twtranslate('en', commentname, en_changes) return mods, mcomment, adding, removing, modifying def botMayEdit(page):
64
64
128
6
57
jayvdb/pywikibot-core
scripts/interwiki.py
Python
botMayEdit
botMayEdit
2,405
2,424
2,405
2,405
1a1f5e13688576d0a043af8d19bee66cea20cedb
bigcode/the-stack
train
f8a51b09c31291adcc54dd49
train
function
def page_empty_check(page): """ Return True if page should be skipped as it is almost empty. Pages in content namespaces are considered empty if they contain less than 50 characters, and other pages are considered empty if they are not category pages and contain less than 4 characters excluding int...
def page_empty_check(page):
""" Return True if page should be skipped as it is almost empty. Pages in content namespaces are considered empty if they contain less than 50 characters, and other pages are considered empty if they are not category pages and contain less than 4 characters excluding interlanguage links and cat...
we should maybe make # titletranslate expect a list of pagelinks. hintStrings = ['%s:%s' % (hintedPage.site.lang, hintedPage.title()) for hintedPage in pagelist] bot.add(page, hints=hintStrings) def page_empty_check(page):
64
64
184
6
58
jayvdb/pywikibot-core
scripts/interwiki.py
Python
page_empty_check
page_empty_check
2,444
2,466
2,444
2,444
927f64781dce951919fa4104332b1965fe1fafc9
bigcode/the-stack
train
bfd36af5c26db8f54a5b76e0
train
function
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ singlePageTitle = '' opthintsonly = False # Which namespaces should be processed? # default to [] ...
def main(*args):
""" Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ singlePageTitle = '' opthintsonly = False # Which namespaces should be processed? # default to [] which means all n...
is a quite ugly hack, in the future we should maybe make # titletranslate expect a list of pagelinks. hintStrings = ['%s:%s' % (hintedPage.site.lang, hintedPage.title()) for hintedPage in pagelist] bot.add(page, hints=hintStrings) def p...
256
256
1,512
5
250
jayvdb/pywikibot-core
scripts/interwiki.py
Python
main
main
2,469
2,654
2,469
2,469
0b60eb1b6a1c89b982bd9a5bf5166bf3440f7326
bigcode/the-stack
train
8806a597043c73ddbdfe47c7
train
class
class SaveError(pywikibot.Error): """An attempt to save a page with changed interwiki has failed."""
class SaveError(pywikibot.Error):
"""An attempt to save a page with changed interwiki has failed."""
.tools import first_upper from pywikibot.tools.formatter import color_format if sys.version_info[0] > 2: unicode = str docuReplacements = { '&pagegenerators_help;': pagegenerators.parameterHelp } class SaveError(pywikibot.Error):
64
64
25
10
54
jayvdb/pywikibot-core
scripts/interwiki.py
Python
SaveError
SaveError
375
377
375
376
2b8bec99b577866fd489fee612a8addec7c27609
bigcode/the-stack
train
4bfc2477d3457012edec6fad
train
function
def compareLanguages(old, new, insite, summary): """Compare changes and setup i18n message.""" oldiw = set(old) newiw = set(new) # sort by language code adding = sorted(newiw - oldiw) removing = sorted(oldiw - newiw) modifying = sorted(site for site in oldiw & newiw i...
def compareLanguages(old, new, insite, summary):
"""Compare changes and setup i18n message.""" oldiw = set(old) newiw = set(new) # sort by language code adding = sorted(newiw - oldiw) removing = sorted(oldiw - newiw) modifying = sorted(site for site in oldiw & newiw if old[site] != new[site]) if not summary and...
self.pageGenerator is None def plus(self, site, count=1): """Helper routine that the Subject class expects in a counter.""" try: self.counts[site] += count except KeyError: self.counts[site] = count def minus(self, site, count=1): """Helper routine that...
150
150
502
12
138
jayvdb/pywikibot-core
scripts/interwiki.py
Python
compareLanguages
compareLanguages
2,352
2,402
2,352
2,352
31911a0de928da777e47f0fa7348a4a9fbe6fde8
bigcode/the-stack
train
9ee4bef0e25217260ce8b3af
train
class
class InterwikiBotConfig(object): """Container class for interwikibot's settings.""" autonomous = False confirm = False always = False select = False followredirect = True initialredirect = False force = False cleanup = False remove = [] maxquerysize = 50 same = False ...
class InterwikiBotConfig(object):
"""Container class for interwikibot's settings.""" autonomous = False confirm = False always = False select = False followredirect = True initialredirect = False force = False cleanup = False remove = [] maxquerysize = 50 same = False skip = set() skipauto = Fals...
'/dok'), 'uk': ([u'документація', u'doc', u'documentation'], u'/Документація'), 'vi': (u'documentation', u'/doc'), 'zh': ([u'documentation', u'doc'], u'/doc'), } # A list of template names in different languages. # Pages which contain these shouldn't be changed. ignoreTemplates = { '_default': [u'delet...
256
256
1,284
7
249
jayvdb/pywikibot-core
scripts/interwiki.py
Python
InterwikiBotConfig
InterwikiBotConfig
465
632
465
466
aeb688ecd850a071325f623e2a39b7053642c7df
bigcode/the-stack
train
d9f5091947d15ce56875efba
train
function
def readWarnfile(filename, bot): """Read old interlanguage conficts.""" import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints (hints, removeHints) = reader.getHints() for page, pagelist in hints.items(): # The WarnfileReader gives us a list of pagelinks, b...
def readWarnfile(filename, bot):
"""Read old interlanguage conficts.""" import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints (hints, removeHints) = reader.getHints() for page, pagelist in hints.items(): # The WarnfileReader gives us a list of pagelinks, but # titletranslate.py ex...
: pass tmpl += ignoreTemplates['_default'] if tmpl != []: templates = page.templatesWithParams() for template in templates: if template[0].title(withNamespace=False).lower() in tmpl: return False return True def readWarnfile(filename, bot):
64
64
169
8
55
jayvdb/pywikibot-core
scripts/interwiki.py
Python
readWarnfile
readWarnfile
2,427
2,441
2,427
2,427
fa9aca3d91a17b289c763d4d1db5f415097ff166
bigcode/the-stack
train
6dbe3ef45fbfcafd68088bde
train
class
class StoredPage(pywikibot.Page): """ Store the Page contents on disk. This is to avoid sucking too much memory when a big number of Page objects will be loaded at the same time. """ # Please prefix the class members names by SP # to avoid possible name clashes with pywikibot.Page # ...
class StoredPage(pywikibot.Page):
""" Store the Page contents on disk. This is to avoid sucking too much memory when a big number of Page objects will be loaded at the same time. """ # Please prefix the class members names by SP # to avoid possible name clashes with pywikibot.Page # path to the shelve SPpath = Non...
self.asynchronous = True elif arg.startswith('-summary'): if len(arg) == 8: self.summary = pywikibot.input( u'What summary do you want to use?') else: self.summary = arg[9:] elif arg.startswith('-lack:'): remainder ...
136
136
454
10
125
jayvdb/pywikibot-core
scripts/interwiki.py
Python
StoredPage
StoredPage
635
707
635
636
cebcd9e61490ca46e273669eaf653164b95d38dc
bigcode/the-stack
train
475c3809ce6ac1457014d1de
train
function
def render_body(context, **pageargs): __M_caller = context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) self = context.get('self', UNDEFINED) request = context.get('request', UNDEFINED) def content(): return render_content(context....
def render_body(context, **pageargs):
__M_caller = context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) self = context.get('self', UNDEFINED) request = context.get('request', UNDEFINED) def content(): return render_content(context._locals(__M_locals)) __M_writ...
= 10 _modified_time = 1425352092.470661 _enable_loop = True _template_filename = '/Users/Nate/chf_dmp/account/templates/base_ajax.htm' _template_uri = '/account/templates/base_ajax.htm' _source_encoding = 'ascii' import os, os.path, re _exports = ['content'] from django_mako_plus.controller import static_files def r...
86
86
288
9
76
nateyj/colonial-heritage
account/cached_templates/templates/account/templates/base_ajax.htm.py
Python
render_body
render_body
20
50
20
20
3095b17030e7b68607265509359784b501a14e71
bigcode/the-stack
train
aa4bc13d6a639b9b76e4edbf
train
function
def render_content(context, **pageargs): __M_caller = context.caller_stack._push_frame() try: def content(): return render_content(context) __M_writer = context.writer() __M_writer('\n Sub-templates should place their ajax content here.\n') return '' finally: ...
def render_content(context, **pageargs):
__M_caller = context.caller_stack._push_frame() try: def content(): return render_content(context) __M_writer = context.writer() __M_writer('\n Sub-templates should place their ajax content here.\n') return '' finally: context.caller_stack._pop_frame()
context['self'].content(**pageargs) __M_writer(' \n\n') __M_writer(str(static_renderer.get_template_js(request, context))) __M_writer('\n') return '' finally: context.caller_stack._pop_frame() def render_content(context, **pageargs):
64
64
78
9
55
nateyj/colonial-heritage
account/cached_templates/templates/account/templates/base_ajax.htm.py
Python
render_content
render_content
53
63
53
53
7d98a502be8e2b60722312b9935231ec1cdfa3c9
bigcode/the-stack
train
a6d76a6b3f7060b3cb72a8db
train
function
def inference( model, data_loader, dataset_name, iou_types=("bbox",), box_only=False, bbox_aug=False, device="cuda", expected_results=(), expected_results_sigma_tol=4, output_folder=None, ): # convert to a torch.device for efficiency ...
def inference( model, data_loader, dataset_name, iou_types=("bbox",), box_only=False, bbox_aug=False, device="cuda", expected_results=(), expected_results_sigma_tol=4, output_folder=None, ): # convert to a torch.device for efficiency
device = torch.device(device) num_devices = get_world_size() logger = logging.getLogger("maskrcnn_benchmark.inference") dataset = data_loader.dataset logger.info("Start evaluation on {} dataset({} images).".format(dataset_name, len(dataset))) total_timer = Timer() inference_timer = Timer() ...
rcnn_benchmark.inference") # logger.warning( # "Number of images that were gathered from multiple processes is not " # "a contiguous set. Some images might be missing from the evaluation" # ) # convert to a list predictions = [predictions[i] for i in image_ids] return...
141
141
470
66
74
Jerrypiglet/scalenet
RELEASE_ScaleNet_minimal/maskrcnn_rui/engine/inference.py
Python
inference
inference
87
149
87
99
8eac62a4c21e12ed6bfb7ee465e8fb188cbf73a7
bigcode/the-stack
train
9b53fac872faeef08f4060f6
train
function
def compute_on_dataset(model, data_loader, device, bbox_aug, timer=None): model.eval() results_dict_cpu = {} results_dict_gpu = {} cpu_device = torch.device("cpu") for idx, batch in enumerate(tqdm(data_loader)): images, targets, image_ids = batch with torch.no_grad(): if ...
def compute_on_dataset(model, data_loader, device, bbox_aug, timer=None):
model.eval() results_dict_cpu = {} results_dict_gpu = {} cpu_device = torch.device("cpu") for idx, batch in enumerate(tqdm(data_loader)): images, targets, image_ids = batch with torch.no_grad(): if timer: timer.tic() if bbox_aug: ...
rcnn_benchmark.utils.comm import is_main_process, get_world_size from maskrcnn_benchmark.utils.comm import all_gather from maskrcnn_benchmark.utils.comm import synchronize from maskrcnn_benchmark.utils.timer import Timer, get_time_str from .bbox_aug import im_detect_bbox_aug def compute_on_dataset(model, data_loader, d...
81
81
271
17
63
Jerrypiglet/scalenet
RELEASE_ScaleNet_minimal/maskrcnn_rui/engine/inference.py
Python
compute_on_dataset
compute_on_dataset
17
47
17
17
692e7d8420e6a5e20ff0c5bc35c54072866068f9
bigcode/the-stack
train
ca77263759502cf721c23c27
train
function
def _dict_to_list(predictions): if predictions is None: return # convert a dict where the key is the index in a list image_ids = list(sorted(predictions.keys())) # if len(image_ids) != image_ids[-1] + 1: # logger = logging.getLogger("maskrcnn_benchmark.inference") # logger.warnin...
def _dict_to_list(predictions):
if predictions is None: return # convert a dict where the key is the index in a list image_ids = list(sorted(predictions.keys())) # if len(image_ids) != image_ids[-1] + 1: # logger = logging.getLogger("maskrcnn_benchmark.inference") # logger.warning( # "Number of imag...
all_predictions if not is_main_process(): return # merge the list of dicts predictions = {} for p in all_predictions: predictions.update(p) if return_dict: return predictions return _dict_to_list(predictions) def _dict_to_list(predictions):
64
64
144
8
56
Jerrypiglet/scalenet
RELEASE_ScaleNet_minimal/maskrcnn_rui/engine/inference.py
Python
_dict_to_list
_dict_to_list
70
83
70
70
cb8c10929b2f437fef6629f6cdc760cee3b65c7d
bigcode/the-stack
train
96e443ef0f68175ee6c394a5
train
function
def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu, return_dict=False, only_gather=False): if _dict_to_list is None: return if get_world_size()==1: return predictions_per_gpu all_predictions = all_gather(predictions_per_gpu) if only_gather: return all_predictions ...
def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu, return_dict=False, only_gather=False):
if _dict_to_list is None: return if get_world_size()==1: return predictions_per_gpu all_predictions = all_gather(predictions_per_gpu) if only_gather: return all_predictions if not is_main_process(): return # merge the list of dicts predictions = {} for p i...
, image_ids[0], output[0].bbox.device) # torch.cuda.synchronize() print('==============results_dict_cpu.keys()=', results_dict_cpu.keys()) return results_dict_cpu def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu, return_dict=False, only_gather=False):
64
64
125
23
40
Jerrypiglet/scalenet
RELEASE_ScaleNet_minimal/maskrcnn_rui/engine/inference.py
Python
_accumulate_predictions_from_multiple_gpus
_accumulate_predictions_from_multiple_gpus
50
68
50
50
58fc9a1cca38c70d06a24b2dfce2233ba39ef339
bigcode/the-stack
train
a63a056fc69ef69e1eeaf14b
train
class
class BasePerformance(events_lib.EventSequence): """Stores a polyphonic sequence as a stream of performance events. Events are PerformanceEvent objects that encode event type and value. """ __metaclass__ = abc.ABCMeta def __init__(self, start_step, num_velocity_bins, max_shift_steps, ...
class BasePerformance(events_lib.EventSequence):
"""Stores a polyphonic sequence as a stream of performance events. Events are PerformanceEvent objects that encode event type and value. """ __metaclass__ = abc.ABCMeta def __init__(self, start_step, num_velocity_bins, max_shift_steps, program=None, is_drum=None): """Construct...
(optional) instrument. Args: sequence: The NoteSequence from which MIDI program and is_drum will be extracted. instrument: The instrument in `sequence` from which MIDI program and is_drum will be extracted, or None to consider all instruments. Returns: A tuple containing program and i...
256
256
3,000
8
247
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
BasePerformance
BasePerformance
135
502
135
135
3663e0804e50d2f3c1c4a4f1678ff9adfd385d52
bigcode/the-stack
train
29507b1a52cecb915171ef10
train
class
class NotePerformanceError(Exception): pass
class NotePerformanceError(Exception):
pass
* qpm) sequence = self._to_sequence( seconds_per_step=seconds_per_step, velocity=velocity, instrument=instrument, program=program, max_note_duration=max_note_duration) sequence.tempos.add(qpm=qpm) return sequence class NotePerformanceE...
64
64
9
6
57
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
NotePerformanceError
NotePerformanceError
693
694
693
693
e38b191d924eee2292ce2994b4b8213363aac2eb
bigcode/the-stack
train
80a1f08bd54a841b74d14732
train
class
class NotePerformance(BasePerformance): """Stores a polyphonic sequence as a stream of performance events. Events are PerformanceEvent objects that encode event type and value. In this version, the performance is encoded in 4-event tuples: TIME_SHIFT, NOTE_ON, VELOCITY, DURATION. """ def __init__(self...
class NotePerformance(BasePerformance):
"""Stores a polyphonic sequence as a stream of performance events. Events are PerformanceEvent objects that encode event type and value. In this version, the performance is encoded in 4-event tuples: TIME_SHIFT, NOTE_ON, VELOCITY, DURATION. """ def __init__(self, quantized_sequence, num_velocity_bins,...
. Args: velocity: MIDI velocity to give each note. Between 1 and 127 (inclusive). If the performance contains velocity events, those will be used instead. instrument: MIDI instrument to give each note. program: MIDI program to give each note, or None to use the program ...
256
256
1,629
6
249
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
NotePerformance
NotePerformance
705
915
705
705
f3eecde783e847749dce1b77e34da0d236da8539
bigcode/the-stack
train
738e46ec26c0f6102faabaf0
train
function
def velocity_to_bin(velocity, num_velocity_bins): return ((velocity - MIN_MIDI_VELOCITY) // _velocity_bin_size(num_velocity_bins) + 1)
def velocity_to_bin(velocity, num_velocity_bins):
return ((velocity - MIN_MIDI_VELOCITY) // _velocity_bin_size(num_velocity_bins) + 1)
_type and self.event_value == other.event_value) def _velocity_bin_size(num_velocity_bins): return int(math.ceil( (MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1) / num_velocity_bins)) def velocity_to_bin(velocity, num_velocity_bins):
64
64
38
11
53
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
velocity_to_bin
velocity_to_bin
93
95
93
93
9b357e9c2b5ab3359e11b284a98298c507bfd26a
bigcode/the-stack
train
3e1ee072efe93785bfb759c6
train
class
class TooManyDurationStepsError(NotePerformanceError): pass
class TooManyDurationStepsError(NotePerformanceError):
pass
instrument=instrument, program=program, max_note_duration=max_note_duration) sequence.tempos.add(qpm=qpm) return sequence class NotePerformanceError(Exception): pass class TooManyTimeShiftStepsError(NotePerformanceError): pass class TooManyDurationStepsError(NotePerf...
64
64
13
10
53
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
TooManyDurationStepsError
TooManyDurationStepsError
701
702
701
701
247ef18270f0602e37ba8f0fcf466b6fea766527
bigcode/the-stack
train
7c4a5410820f5cf08f6eb813
train
class
class TooManyTimeShiftStepsError(NotePerformanceError): pass
class TooManyTimeShiftStepsError(NotePerformanceError):
pass
_per_step=seconds_per_step, velocity=velocity, instrument=instrument, program=program, max_note_duration=max_note_duration) sequence.tempos.add(qpm=qpm) return sequence class NotePerformanceError(Exception): pass class TooManyTimeShiftStepsError(Note...
64
64
14
11
52
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
TooManyTimeShiftStepsError
TooManyTimeShiftStepsError
697
698
697
697
2d9c080be4a22e22bf75350c1f90cbcab5b1865c
bigcode/the-stack
train
49c068a30f678b507000cbb7
train
class
class MetricPerformance(BasePerformance): """Performance with quarter-note relative timing.""" def __init__(self, quantized_sequence=None, steps_per_quarter=None, start_step=0, num_velocity_bins=0, max_shift_quarters=DEFAULT_MAX_SHIFT_QUARTERS, instrument=None, ...
class MetricPerformance(BasePerformance):
"""Performance with quarter-note relative timing.""" def __init__(self, quantized_sequence=None, steps_per_quarter=None, start_step=0, num_velocity_bins=0, max_shift_quarters=DEFAULT_MAX_SHIFT_QUARTERS, instrument=None, program=None, is_drum=None): """...
program=program, is_drum=is_drum) @property def steps_per_second(self): return self._steps_per_second def to_sequence(self, velocity=100, instrument=0, program=None, max_note_duration=None): """Con...
252
252
840
6
246
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
MetricPerformance
MetricPerformance
596
690
596
596
017838ab1cb72600463816711f240916200bb4d0
bigcode/the-stack
train
038defc40c6380c5efc458b9
train
class
class Performance(BasePerformance): """Performance with absolute timing and unknown meter.""" def __init__(self, quantized_sequence=None, steps_per_second=None, start_step=0, num_velocity_bins=0, max_shift_steps=DEFAULT_MAX_SHIFT_STEPS, instrument=None, progra...
class Performance(BasePerformance):
"""Performance with absolute timing and unknown meter.""" def __init__(self, quantized_sequence=None, steps_per_second=None, start_step=0, num_velocity_bins=0, max_shift_steps=DEFAULT_MAX_SHIFT_STEPS, instrument=None, program=None, is_drum=None): """Co...
s' % event.event_type) # There could be remaining pitches that were never ended. End them now # and create notes. for pitch in pitch_start_steps_and_velocities: for pitch_start_step, pitch_velocity in pitch_start_steps_and_velocities[ pitch]: if step ...
228
228
760
5
222
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
Performance
Performance
505
593
505
505
54baaf8abc185114193b3de4c37af9be5eee0ebd
bigcode/the-stack
train
c03a6d895991706dfad4db0e
train
function
def _velocity_bin_size(num_velocity_bins): return int(math.ceil( (MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1) / num_velocity_bins))
def _velocity_bin_size(num_velocity_bins):
return int(math.ceil( (MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1) / num_velocity_bins))
r)' % (self.event_type, self.event_value) def __eq__(self, other): if not isinstance(other, PerformanceEvent): return False return (self.event_type == other.event_type and self.event_value == other.event_value) def _velocity_bin_size(num_velocity_bins):
64
64
41
9
55
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
_velocity_bin_size
_velocity_bin_size
88
90
88
88
c4fe22bfb32970cc2722b4d55a70dbaea18b1051
bigcode/the-stack
train
ff2f2a5f1a0f0885e2699d27
train
function
def velocity_bin_to_velocity(velocity_bin, num_velocity_bins): return ( MIN_MIDI_VELOCITY + (velocity_bin - 1) * _velocity_bin_size(num_velocity_bins))
def velocity_bin_to_velocity(velocity_bin, num_velocity_bins):
return ( MIN_MIDI_VELOCITY + (velocity_bin - 1) * _velocity_bin_size(num_velocity_bins))
_VELOCITY + 1) / num_velocity_bins)) def velocity_to_bin(velocity, num_velocity_bins): return ((velocity - MIN_MIDI_VELOCITY) // _velocity_bin_size(num_velocity_bins) + 1) def velocity_bin_to_velocity(velocity_bin, num_velocity_bins):
64
64
42
13
51
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
velocity_bin_to_velocity
velocity_bin_to_velocity
98
101
98
98
86296883c4113d640a12b11216e36635224d1d9b
bigcode/the-stack
train
439bb521029e8670f1882855
train
class
class PerformanceEvent(object): """Class for storing events in a performance.""" # Start of a new note. NOTE_ON = 1 # End of a note. NOTE_OFF = 2 # Shift time forward. TIME_SHIFT = 3 # Change current velocity. VELOCITY = 4 # Duration of preceding NOTE_ON. # For Note-based en...
class PerformanceEvent(object):
"""Class for storing events in a performance.""" # Start of a new note. NOTE_ON = 1 # End of a note. NOTE_OFF = 2 # Shift time forward. TIME_SHIFT = 3 # Change current velocity. VELOCITY = 4 # Duration of preceding NOTE_ON. # For Note-based encoding, used instead of NOTE_OFF...
MIN_MIDI_PITCH = constants.MIN_MIDI_PITCH MAX_MIDI_VELOCITY = constants.MAX_MIDI_VELOCITY MIN_MIDI_VELOCITY = constants.MIN_MIDI_VELOCITY MAX_NUM_VELOCITY_BINS = MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1 STANDARD_PPQ = constants.STANDARD_PPQ DEFAULT_MAX_SHIFT_STEPS = 100 DEFAULT_MAX_SHIFT_QUARTERS = 4 DEFAULT_PROG...
116
116
388
5
110
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
PerformanceEvent
PerformanceEvent
44
85
44
44
cdc273aa766993caad16ab3952a2617027b6db2c
bigcode/the-stack
train
943670a4cf6b285e51e29b0f
train
function
def _program_and_is_drum_from_sequence(sequence, instrument=None): """Get MIDI program and is_drum from sequence and (optional) instrument. Args: sequence: The NoteSequence from which MIDI program and is_drum will be extracted. instrument: The instrument in `sequence` from which MIDI program and ...
def _program_and_is_drum_from_sequence(sequence, instrument=None):
"""Get MIDI program and is_drum from sequence and (optional) instrument. Args: sequence: The NoteSequence from which MIDI program and is_drum will be extracted. instrument: The instrument in `sequence` from which MIDI program and is_drum will be extracted, or None to consider all instrume...
return ((velocity - MIN_MIDI_VELOCITY) // _velocity_bin_size(num_velocity_bins) + 1) def velocity_bin_to_velocity(velocity_bin, num_velocity_bins): return ( MIN_MIDI_VELOCITY + (velocity_bin - 1) * _velocity_bin_size(num_velocity_bins)) def _program_and_is_drum_from_sequence(s...
82
82
274
14
68
sleep-yearning/magenta
magenta/music/performance_lib.py
Python
_program_and_is_drum_from_sequence
_program_and_is_drum_from_sequence
104
132
104
104
3f4923a0b6388002136f4d3907f6605a2010a528
bigcode/the-stack
train
0ae75edd69b023d24dacb8fc
train
function
def comp_periodicity(self, p): """Compute the periodicity factor of the lamination Parameters ---------- self : LamSquirrelCage A LamSquirrelCage object Returns ------- per_a : int Number of spatial periodicities of the lamination is_antiper_a : bool True if an ...
def comp_periodicity(self, p):
"""Compute the periodicity factor of the lamination Parameters ---------- self : LamSquirrelCage A LamSquirrelCage object Returns ------- per_a : int Number of spatial periodicities of the lamination is_antiper_a : bool True if an spatial anti-periodicity is pos...
# -*- coding: utf-8 -*- from numpy import gcd def comp_periodicity(self, p):
21
67
225
8
12
EmileDvs/pyleecan
pyleecan/Methods/Machine/LamSquirrelCage/comp_periodicity.py
Python
comp_periodicity
comp_periodicity
5
34
5
5
7d6c722bfc478ded4054a6e28b544b3e15d6e04e
bigcode/the-stack
train
ae2798999a1b4b6e8364c3d9
train
function
def sql_format(x): if type(x) is str: x = x.replace("'", "''") x = x.replace('\n', "' || chr(10) || '") return f"'{x}'" elif x is None: return 'null' elif type(x) is bool: return 'true' if x else 'false' elif type(x) is int: return str(x) elif type(x) ...
def sql_format(x):
if type(x) is str: x = x.replace("'", "''") x = x.replace('\n', "' || chr(10) || '") return f"'{x}'" elif x is None: return 'null' elif type(x) is bool: return 'true' if x else 'false' elif type(x) is int: return str(x) elif type(x) is datetime.date: ...
2), ('Turkish', 2), ('Italian', 2), ('Somali', 2), ('Lithuanian', 2), ('German', 1), ('Persian', 1), ('Romanian', 1), ]) def sql_format(x):
64
64
199
5
59
uk-gov-mirror/ministryofjustice.hmpps-interventions-service
user_research/migration_generator.py
Python
sql_format
sql_format
360
380
360
360
9b14545ffc305ae09821f68f4f7645a2b78afbd1
bigcode/the-stack
train
833fc9da8a4855ccaed4f9dd
train
function
def random_date_between(d1, d2, allow_past=False): today = datetime.date.today() if not allow_past and (d1 < today or d2 < today): raise RuntimeError("dates can't be in the past") if d2 < d1: raise RuntimeError("d2 should be after d1") return today + datetime.timedelta(random.randint(...
def random_date_between(d1, d2, allow_past=False):
today = datetime.date.today() if not allow_past and (d1 < today or d2 < today): raise RuntimeError("dates can't be in the past") if d2 < d1: raise RuntimeError("d2 should be after d1") return today + datetime.timedelta(random.randint((d1 - today).days, (d2 - today).days))
return sql_format(f"{{{','.join(x)}}}") else: raise RuntimeError(f"can't format var with type '{type(x)}' ({x})") def random_bool(): return random.choice([True, False]) def random_date_between(d1, d2, allow_past=False):
64
64
97
15
49
uk-gov-mirror/ministryofjustice.hmpps-interventions-service
user_research/migration_generator.py
Python
random_date_between
random_date_between
387
396
387
387
164942b1ce64f18ab6ba79d843fab437765c2a41
bigcode/the-stack
train
9507446ae19143afcc20fef8
train
function
def random_bool(): return random.choice([True, False])
def random_bool():
return random.choice([True, False])
elif type(x) is uuid.UUID: return sql_format(str(x)) elif type(x) is list: return sql_format(f"{{{','.join(x)}}}") else: raise RuntimeError(f"can't format var with type '{type(x)}' ({x})") def random_bool():
64
64
13
4
60
uk-gov-mirror/ministryofjustice.hmpps-interventions-service
user_research/migration_generator.py
Python
random_bool
random_bool
383
384
383
383
98c13020d6d2c0da71b7e63879592bd5b7e388cb
bigcode/the-stack
train
d67d24bb6dd9cb253034a3ca
train
function
def generate_reference_number(service_category_id): # don't care about ambiguous pairs right now letters = lambda k: ''.join(random.choices(string.ascii_uppercase, k=k)) numbers = lambda k: ''.join(random.choices(string.digits, k=k)) return f'{letters(2)}{numbers(4)}{service_category_reference_codes[ser...
def generate_reference_number(service_category_id): # don't care about ambiguous pairs right now
letters = lambda k: ''.join(random.choices(string.ascii_uppercase, k=k)) numbers = lambda k: ''.join(random.choices(string.digits, k=k)) return f'{letters(2)}{numbers(4)}{service_category_reference_codes[service_category_id]}'
'childcare responsibilities', 'work', 'regular hospital appointments' ]) return f'{day_of_the_week}s between {start_time}:00 and {end_time}:00 due to {reason}.' def generate_reference_number(service_category_id): # don't care about ambiguous pairs right now
63
64
80
18
45
uk-gov-mirror/ministryofjustice.hmpps-interventions-service
user_research/migration_generator.py
Python
generate_reference_number
generate_reference_number
412
416
412
413
dd1cc26263a7508f4bafff385a2395bf23ddfcba
bigcode/the-stack
train
2357e4908f7114960ce47d5b
train
function
def random_when_unavailable(): day_of_the_week = random.choice(['Weekday', 'Weekend', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']) start_time = random.randint(9, 15) end_time = random.randint(start_time, 20) reason = random.choice([ 'childcare responsibilities',...
def random_when_unavailable():
day_of_the_week = random.choice(['Weekday', 'Weekend', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']) start_time = random.randint(9, 15) end_time = random.randint(start_time, 20) reason = random.choice([ 'childcare responsibilities', 'work', 'regul...
): raise RuntimeError("dates can't be in the past") if d2 < d1: raise RuntimeError("d2 should be after d1") return today + datetime.timedelta(random.randint((d1 - today).days, (d2 - today).days)) def random_when_unavailable():
64
64
117
6
58
uk-gov-mirror/ministryofjustice.hmpps-interventions-service
user_research/migration_generator.py
Python
random_when_unavailable
random_when_unavailable
399
409
399
399
64b787608788cb3fbdf04100b744b176d400ad60
bigcode/the-stack
train
715a28cad16368ecf32131d9
train
class
class BuildCommand(Command): """ Render timeline project to output directory using the specified template. build {file? : File to write the timeline to.} {--stdout : Write to standard output instead of file.} """ def handle(self): output = self.argument("file") ...
class BuildCommand(Command):
""" Render timeline project to output directory using the specified template. build {file? : File to write the timeline to.} {--stdout : Write to standard output instead of file.} """ def handle(self): output = self.argument("file") self.line("""<info>Outputing ...
from cleo import Command import json from ...timeline import Project class BuildCommand(Command):
20
64
189
5
14
jduprey/mktimeline
src/mktimeline/console/commands/build.py
Python
BuildCommand
BuildCommand
6
31
6
6
e05247881795e4fd785c9392f83d18919d0d56f2
bigcode/the-stack
train
de8bc92c7760e31bfec64d10
train
class
class Lattice: def __init__(self): raise NotImplementedError def reveal(self): raise NotImplementedError def assign(self, value): raise NotImplementedError def merge(self, other): raise NotImplementedError
class Lattice:
def __init__(self): raise NotImplementedError def reveal(self): raise NotImplementedError def assign(self, value): raise NotImplementedError def merge(self, other): raise NotImplementedError
law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Lattice:
64
64
54
4
60
saurav-c/fluent
kvs/client/python/anna/lattices.py
Python
Lattice
Lattice
15
26
15
15
3fc0bd52778a05e1880ece236bc8ea77b88bddd1
bigcode/the-stack
train
9ed468876bdf0c6fccc8704c
train
class
class SetLattice(Lattice): def __init__(self, value={}): if type(value) != set: raise ValueError('SetLattice can only be formed from a set.') self.val = value def reveal(self): return self.val def assign(self, value): if type(value) != set: raise Va...
class SetLattice(Lattice):
def __init__(self, value={}): if type(value) != set: raise ValueError('SetLattice can only be formed from a set.') self.val = value def reveal(self): return self.val def assign(self, value): if type(value) != set: raise ValueError('SetLattice can on...
Error('LWWPairLattice must be a timestamp-bytes pair.') self.ts = value[0] self.val = value[1] def merge(self, other): if other.ts > self.ts: return other else: return self class SetLattice(Lattice):
64
64
173
7
56
saurav-c/fluent
kvs/client/python/anna/lattices.py
Python
SetLattice
SetLattice
56
85
56
56
08e4aceb114c9ea1830fb6042e963240b70fbe7c
bigcode/the-stack
train
844640a62b0ed4e44cd05bca
train
class
class LWWPairLattice(Lattice): def __init__(self, timestamp, value): if type(timestamp) != int or type(value) != bytes: raise ValueError('LWWPairLattice must be a timestamp-bytes pair.') self.ts = timestamp self.val = value def reveal(self): return (self.ts, self.va...
class LWWPairLattice(Lattice):
def __init__(self, timestamp, value): if type(timestamp) != int or type(value) != bytes: raise ValueError('LWWPairLattice must be a timestamp-bytes pair.') self.ts = timestamp self.val = value def reveal(self): return (self.ts, self.val) def assign(self, value)...
. class Lattice: def __init__(self): raise NotImplementedError def reveal(self): raise NotImplementedError def assign(self, value): raise NotImplementedError def merge(self, other): raise NotImplementedError class LWWPairLattice(Lattice):
64
64
190
9
54
saurav-c/fluent
kvs/client/python/anna/lattices.py
Python
LWWPairLattice
LWWPairLattice
28
54
28
28
40b7f44b3d95d42ffab0e505a9a3c90b9ad17505
bigcode/the-stack
train
3e2a1ecb3e078e863fc92e19
train
function
def windower(sequence, position, wing_size): # window size = wing_size*2 +1 position = int(position) wing_size = int(wing_size) if (position - wing_size) < 0: return sequence[:wing_size + position] if (position + wing_size) > len(sequence): return sequence[position - wing_size:] ...
def windower(sequence, position, wing_size): # window size = wing_size*2 +1
position = int(position) wing_size = int(wing_size) if (position - wing_size) < 0: return sequence[:wing_size + position] if (position + wing_size) > len(sequence): return sequence[position - wing_size:] else: return sequence[position - wing_size:position + wing_size]
blearn.combine import SMOTETomek from sklearn.decomposition import PCA from sklearn.discriminant_analysis import LinearDiscriminantAnalysis import matplotlib.pyplot as plt print("I am running") def windower(sequence, position, wing_size): # window size = wing_size*2 +1
64
64
94
22
42
vzg100/ProtienFolding
index.py
Python
windower
windower
33
42
33
34
f21ea6f7dcbe51b90f0ad0f893abb0f2a61b2748
bigcode/the-stack
train
66e72b21cde627e7db6296dd
train
function
def featurify(temp_window, size): # assumes temp_window = ProteinAnalysis(seq) q = [temp_window.gravy(), temp_window.aromaticity(), temp_window.isoelectric_point() ] z = temp_window.amino_acids_content order = {} counter = 0 aa = "GALMFWKQESPVICYHRNDT" for i in ...
def featurify(temp_window, size): # assumes temp_window = ProteinAnalysis(seq)
q = [temp_window.gravy(), temp_window.aromaticity(), temp_window.isoelectric_point() ] z = temp_window.amino_acids_content order = {} counter = 0 aa = "GALMFWKQESPVICYHRNDT" for i in range(len(aa)): order[aa[i]] = i counter +=1 if len(temp_windo...
return sequence[:wing_size + position] if (position + wing_size) > len(sequence): return sequence[position - wing_size:] else: return sequence[position - wing_size:position + wing_size] def featurify(temp_window, size): # assumes temp_window = ProteinAnalysis(seq)
64
64
168
19
45
vzg100/ProtienFolding
index.py
Python
featurify
featurify
45
69
45
46
529bdc0ca6a49a6df00ee810bb2573bcc09c0253
bigcode/the-stack
train
b3c6bd6bc633def4341e8d10
train
function
def report(results, answers, classy,shift=0): tp, fp, fn, tn = 0, 0, 0, 0 for i in range(len(results)): if results[i] == 1 and answers[i+shift] == 1: tp += 1 elif results[i] == 0 and answers[i+shift] == 0: tn += 1 elif results[i] == 1 and answers[i+shift] == 0: ...
def report(results, answers, classy,shift=0):
tp, fp, fn, tn = 0, 0, 0, 0 for i in range(len(results)): if results[i] == 1 and answers[i+shift] == 1: tp += 1 elif results[i] == 0 and answers[i+shift] == 0: tn += 1 elif results[i] == 1 and answers[i+shift] == 0: fp += 1 else: fn...
)): q.append(-1) return q def random_seq(locked, wing_size, center): amino_acids = "GALMFWKQESPVICYHRNDT" t1, t2 = "", "" for i in range(wing_size): t1 += amino_acids[randint(0, 19)] t2 += amino_acids[randint(0, 19)] final_seq = t1 + center + t2 if final_seq not i...
139
139
465
12
127
vzg100/ProtienFolding
index.py
Python
report
report
87
126
87
87
9821e8177dc82a8512985e54b33641142ee3d5e9
bigcode/the-stack
train
c44c8d89e93d3d2c72de13af
train
function
def random_seq(locked, wing_size, center): amino_acids = "GALMFWKQESPVICYHRNDT" t1, t2 = "", "" for i in range(wing_size): t1 += amino_acids[randint(0, 19)] t2 += amino_acids[randint(0, 19)] final_seq = t1 + center + t2 if final_seq not in locked: return final_seq else: ...
def random_seq(locked, wing_size, center):
amino_acids = "GALMFWKQESPVICYHRNDT" t1, t2 = "", "" for i in range(wing_size): t1 += amino_acids[randint(0, 19)] t2 += amino_acids[randint(0, 19)] final_seq = t1 + center + t2 if final_seq not in locked: return final_seq else: random_seq(locked, wing_size, center...
for i in temp_window.sequence: q.append(order[i]) else: for i in temp_window.sequence: q.append(order[i]) for i in range(size - len(temp_window.sequence)): q.append(-1) return q def random_seq(locked, wing_size, center):
64
64
116
11
52
vzg100/ProtienFolding
index.py
Python
random_seq
random_seq
74
84
74
74
8062ff37e2ded95ff238745762b2f2d581830725
bigcode/the-stack
train
61d4a3c43923e98b012eecbf
train
class
class Classy: def __init__(self, data="phosphosites.csv", delimit=",", amino_acid="Y", sites="code", modification="phosphorylation", window_size=7, pos="position", training_ratio=.7, header_line=0, seq="sequence", neg_per_seq=5, lines_to_read=10000, classy="forest", imba=[]): ...
class Classy:
def __init__(self, data="phosphosites.csv", delimit=",", amino_acid="Y", sites="code", modification="phosphorylation", window_size=7, pos="position", training_ratio=.7, header_line=0, seq="sequence", neg_per_seq=5, lines_to_read=10000, classy="forest", imba=[]): self.classy...
# false discovery rate acc = (tp + tn) / (tp + fp + tn + fn) roc = roc_auc_score(answers, results) inf = (tpr+spc)-1 mkd = (ppv+npv)-1 print("Sensitivity:"+str(tpr)) print("Specificity :" + str(spc)) print("Positive Predictive Value:" + str(ppv)) print...
256
256
2,077
4
251
vzg100/ProtienFolding
index.py
Python
Classy
Classy
130
310
130
131
c111ff72500a7ef99cf8979d7c233092e47278c0
bigcode/the-stack
train
eb0ad556fe33a45d2c927f88
train
function
@perms_check(0) def session_auth(self, data): """ :param self: class Handler :param data: { 'session': str (flask session) } :return: __auth(self, user, data['session']) """ session = sessions.decode_flask_cookie(self.secret_key, data['session']) user = session['user'] retur...
@perms_check(0) def session_auth(self, data):
""" :param self: class Handler :param data: { 'session': str (flask session) } :return: __auth(self, user, data['session']) """ session = sessions.decode_flask_cookie(self.secret_key, data['session']) user = session['user'] return __auth(self, user, data['session'])
logged in') if (data['user'] in self.temp.users) and (self.temp.users[data['user']]['password'] == data['password']): return __auth(self, data['user']) raise Exception('Wrong login or password') @perms_check(0) def session_auth(self, data):
64
64
93
14
50
pufit/online-games
WSServer/commands.py
Python
session_auth
session_auth
90
102
90
91
2e2935de60a0cf6b66d5ce3719b86bf5265d6b06
bigcode/the-stack
train
16e3140f69a370d5bf3a70dc
train
function
@perms_check(1) def stop_typing(self, _): if not self.typing: raise Exception('You are not typing') self.typing = False self.channel.send({'type': 'user_stop_typing', 'data': {'user': self.user, 'user_id': self.user_id}}) return {'type': 'stop_typing_ok', 'data': ''}
@perms_check(1) def stop_typing(self, _):
if not self.typing: raise Exception('You are not typing') self.typing = False self.channel.send({'type': 'user_stop_typing', 'data': {'user': self.user, 'user_id': self.user_id}}) return {'type': 'stop_typing_ok', 'data': ''}
= True self.channel.send({'type': 'user_start_typing', 'data': {'user': self.user, 'user_id': self.user_id}}) return {'type': 'start_typing_ok', 'data': ''} @perms_check(1) def stop_typing(self, _):
63
64
83
15
49
pufit/online-games
WSServer/commands.py
Python
stop_typing
stop_typing
309
315
309
310
965250a5b80a0ae374a40680fa2fd762667c8075
bigcode/the-stack
train
08d8eed39b9091a161a3af96
train
function
@perms_check(0) def games_list(self, _): """ :return: list """ lst = [{ 'name': self.temp.games[i].name, 'creator': self.temp.games[i].creator, 'players': len(self.temp.games[i].players), 'type': self.temp.games[i].type, 'slots': self.temp.games[i].slots, ...
@perms_check(0) def games_list(self, _):
""" :return: list """ lst = [{ 'name': self.temp.games[i].name, 'creator': self.temp.games[i].creator, 'players': len(self.temp.games[i].players), 'type': self.temp.games[i].type, 'slots': self.temp.games[i].slots, 'config': self.temp.games[i].config }...
] for i in games.game_types} } self.temp.db_save(USERS, self.temp.users) return __auth(self, data['user'], auth_type='reg_ok') raise Exception('This login is already in use') @perms_check(0) def games_list(self, _):
64
64
119
14
50
pufit/online-games
WSServer/commands.py
Python
games_list
games_list
137
150
137
138
5ed7ae70df71fdef752b9ebfdc57883cbe73e366
bigcode/the-stack
train
524df7b7540ca9398ec3a594
train
function
@perms_check(1) def start_game(self, _): if not self.game: raise Exception('You are not connected to any game') if self.user != self.game.creator: raise Exception('You are not creator of this game') if len(self.game.players) == 1: raise Exception('You need one more player') Threa...
@perms_check(1) def start_game(self, _):
if not self.game: raise Exception('You are not connected to any game') if self.user != self.game.creator: raise Exception('You are not creator of this game') if len(self.game.players) == 1: raise Exception('You need one more player') Thread(self.game.start_game) self.game.cha...
'id': player, 'name': self.game.players[player].name, 'player_information': self.game.players[player].user.get_information() } for player in self.game.players } } } return resp @perms_check(1) def start_game(self, _)...
64
64
110
14
49
pufit/online-games
WSServer/commands.py
Python
start_game
start_game
254
264
254
255
0a635e1f8bcb8ad2a063cf3a34284d3b60641b39
bigcode/the-stack
train
e75504213ac6ced3d94c0de9
train
function
@perms_check(1) def join(self, data): """ :param self: class Handler :type data: str :param data: name of the game :raise: This game dose not exist Game already started :return: dict """ if not self.temp.games.get(data): raise Exception('This game dose not exist') ...
@perms_check(1) def join(self, data):
""" :param self: class Handler :type data: str :param data: name of the game :raise: This game dose not exist Game already started :return: dict """ if not self.temp.games.get(data): raise Exception('This game dose not exist') if self.temp.games[data].started: ...
name']] = game resp = { 'type': 'game_created', 'data': { 'name': game.name, 'creator': game.creator, 'players': 0, 'type': game.type, 'slots': game.slots, 'config': game.config } } self.temp.main_channel.send(re...
105
105
352
13
92
pufit/online-games
WSServer/commands.py
Python
join
join
195
251
195
196
7078e5ad17e4d8bdef805c2d1944de0ba0d1968e
bigcode/the-stack
train
ed3a07bdc278fa40ca6b738e
train
function
@perms_check(0) def leave(self, _): if not self.game: return {'type': 'leave_error', 'data': 'You are not connected to any game'} if self.game.started: self.temp.give_score(self, self.game.type, -1) else: self.temp.main_channel.send({ 'type': 'game_player_left', ...
@perms_check(0) def leave(self, _):
if not self.game: return {'type': 'leave_error', 'data': 'You are not connected to any game'} if self.game.started: self.temp.give_score(self, self.game.type, -1) else: self.temp.main_channel.send({ 'type': 'game_player_left', 'data': self.game.name })...
== 1: raise Exception('You need one more player') Thread(self.game.start_game) self.game.channel.send({'type': 'game_started', 'data': ''}) return {'type': 'game', 'data': ''} @perms_check(0) def leave(self, _):
63
64
192
13
51
pufit/online-games
WSServer/commands.py
Python
leave
leave
267
290
267
268
b7bd625fa43be93b357f16e03716e67d1d8ad0e5
bigcode/the-stack
train
152a9b68e5158684bbdcd012
train
function
@perms_check(0) def auth(self, data): """ :param self: class Handler :param data: { 'user': str 'password': str } :raise: You are already logged in Wrong login or password :return: __auth(self, data['user']) """ if self.user: raise Exception('You are...
@perms_check(0) def auth(self, data):
""" :param self: class Handler :param data: { 'user': str 'password': str } :raise: You are already logged in Wrong login or password :return: __auth(self, data['user']) """ if self.user: raise Exception('You are already logged in') if (data['use...
sessions.encode_flask_cookie(self.secret_key, resp['data']) resp['data']['session'] = session self.channel.send({ 'type': 'user_logged_in', 'data': self.get_information() }) return resp @perms_check(0) def auth(self, data):
64
64
135
13
50
pufit/online-games
WSServer/commands.py
Python
auth
auth
69
87
69
70
fc2f7582240aaeab6384f6ff58b40b31e0b51239
bigcode/the-stack
train
f6ba1278833b8114d981e195
train
function
def perms_check(user_rights): def decorator(func): def wrapper(self, data): if self.user_rights >= user_rights: return func(self, data) else: return {'type': 'denied', 'data': 'Not enough rights'} return wrapper return decorator
def perms_check(user_rights):
def decorator(func): def wrapper(self, data): if self.user_rights >= user_rights: return func(self, data) else: return {'type': 'denied', 'data': 'Not enough rights'} return wrapper return decorator
"""Commands""" import json import time import sessions import games from config import * from channel import Channel from server import Thread def perms_check(user_rights):
37
64
65
7
29
pufit/online-games
WSServer/commands.py
Python
perms_check
perms_check
16
24
16
16
22a74a3712fbeb4c6291b57743b3dfe03391a15b
bigcode/the-stack
train
ff3a74ef721522276e3d5259
train
function
@perms_check(0) def ping(_, data): """ :return: dict """ if not data: return {'type': 'pong', 'data': 'Pong!'} return {'type': 'pong', 'data': time.time() - data}
@perms_check(0) def ping(_, data):
""" :return: dict """ if not data: return {'type': 'pong', 'data': 'Pong!'} return {'type': 'pong', 'data': time.time() - data}
name': self.channel.name, 'users_count': user_count, 'unauthorized_count': user_count - len(self.channel.handlers), 'users': users } } return {'type': 'channel_information', 'data': ''} @perms_check(0) def ping(_, data):
63
64
60
12
52
pufit/online-games
WSServer/commands.py
Python
ping
ping
361
368
361
362
522fea93fc5893c8b7218ba60ea404970dd33969
bigcode/the-stack
train
17b288af2938385c8f5a6bd5
train
function
@perms_check(0) def reg(self, data): """ :param self: class Handler :param data: { 'user': str, 'password: str } :raise: This login is already in use :return: __auth(self, data['user'], auth_type='reg_ok') """ if len(data['user']) < 3: raise Exception('Too small...
@perms_check(0) def reg(self, data):
""" :param self: class Handler :param data: { 'user': str, 'password: str } :raise: This login is already in use :return: __auth(self, data['user'], auth_type='reg_ok') """ if len(data['user']) < 3: raise Exception('Too small name') if len(data['password']) ...
{ 'session': str (flask session) } :return: __auth(self, user, data['session']) """ session = sessions.decode_flask_cookie(self.secret_key, data['session']) user = session['user'] return __auth(self, user, data['session']) @perms_check(0) def reg(self, data):
77
78
263
13
64
pufit/online-games
WSServer/commands.py
Python
reg
reg
105
134
105
106
94b966ac8bcc74269d2ec7439e8839e8cd7b877a
bigcode/the-stack
train
f8a6302e1019299ecad441a2
train
function
@perms_check(0) def send_message(self, data): """ :param self: class Handler :param data: { 'text': str } :return: dict """ resp = { 'type': 'message', 'data': { 'name': self.user, 'rights': self.user_rights, 'time': time.time(), ...
@perms_check(0) def send_message(self, data):
""" :param self: class Handler :param data: { 'text': str } :return: dict """ resp = { 'type': 'message', 'data': { 'name': self.user, 'rights': self.user_rights, 'time': time.time(), 'text': data['text'] } }...
ing = False self.channel.send({'type': 'user_stop_typing', 'data': {'user': self.user, 'user_id': self.user_id}}) return {'type': 'stop_typing_ok', 'data': ''} @perms_check(0) def send_message(self, data):
63
64
116
14
50
pufit/online-games
WSServer/commands.py
Python
send_message
send_message
318
337
318
319
0923eb94e54af424b963ee54f3ee79093b56ec1b
bigcode/the-stack
train
d7221f98273a0e2d77b7f361
train
function
@perms_check(0) def get_channel_information(self, _): if self.channel: users = {} user_count = 0 for handler in self.channel.handlers: user_count += 1 if handler.user: users[handler.user] = handler.get_information() return { 'type':...
@perms_check(0) def get_channel_information(self, _):
if self.channel: users = {} user_count = 0 for handler in self.channel.handlers: user_count += 1 if handler.user: users[handler.user] = handler.get_information() return { 'type': 'channel', 'data': { 'nam...
, 'rights': self.user_rights, 'time': time.time(), 'text': data['text'] } } self.channel.send(resp) return {'type': 'send_ok', 'data': ''} @perms_check(0) def get_channel_information(self, _):
63
64
130
15
49
pufit/online-games
WSServer/commands.py
Python
get_channel_information
get_channel_information
340
358
340
341
a19ee2957a80285bd45c9d3e2c30378333c75609
bigcode/the-stack
train
efccdc08bc4f935b80a82fb3
train
function
def __auth(self, user, session=None, auth_type='auth_ok'): """ :param self: class Handler :type user: str :param user: user name :type session: str, None :param session: flask session :type auth_type: str :param auth_type: type of answer :return: { 'type': auth_type, ...
def __auth(self, user, session=None, auth_type='auth_ok'):
""" :param self: class Handler :type user: str :param user: user name :type session: str, None :param session: flask session :type auth_type: str :param auth_type: type of answer :return: { 'type': auth_type, 'data': self.get_information(), 'session': str } ...
from server import Thread def perms_check(user_rights): def decorator(func): def wrapper(self, data): if self.user_rights >= user_rights: return func(self, data) else: return {'type': 'denied', 'data': 'Not enough rights'} return wrapper ...
87
87
293
16
70
pufit/online-games
WSServer/commands.py
Python
__auth
__auth
27
66
27
27
5cfae996eed5345e5bf6bb080a17409471ffe122
bigcode/the-stack
train
37418485a84f3d82a06999dd
train
function
@perms_check(1) def create_game(self, data): """ :param self: class Handler :param data: { 'name': str, 'type': str, (see games.__init__.py) 'slots': int, ... additional settings of the game } :raise: This game already exist Bad slots Bad name...
@perms_check(1) def create_game(self, data):
""" :param self: class Handler :param data: { 'name': str, 'type': str, (see games.__init__.py) 'slots': int, ... additional settings of the game } :raise: This game already exist Bad slots Bad name other game.__init__ exceptions ...
.games[i].creator, 'players': len(self.temp.games[i].players), 'type': self.temp.games[i].type, 'slots': self.temp.games[i].slots, 'config': self.temp.games[i].config } for i in self.temp.games] return {'type': 'ret_game_list', 'data': lst} @perms_check(1) def create_game(self, d...
88
88
294
14
74
pufit/online-games
WSServer/commands.py
Python
create_game
create_game
153
192
153
154
fa234ca5ff457c22438b71fcd47af84f79f27372
bigcode/the-stack
train
b32faea13d4c5384bb2f2898
train
function
@perms_check(1) def action(self, data): action_type = data['action_type'].replace('__', '') resp = games.game_types[self.game.type][1].__getattribute__(action_type)(self, data) return {'type': 'action_%s_ok' % action_type, 'data': resp}
@perms_check(1) def action(self, data):
action_type = data['action_type'].replace('__', '') resp = games.game_types[self.game.type][1].__getattribute__(action_type)(self, data) return {'type': 'action_%s_ok' % action_type, 'data': resp}
': 'game_deleted', 'data': self.game.name }) self.game = None self.me = None self.temp.main_channel.join(self) return {'type': 'leave_ok', 'data': 'Left'} @perms_check(1) def action(self, data):
63
64
69
13
50
pufit/online-games
WSServer/commands.py
Python
action
action
293
297
293
294
12c87ee0693aaac171e6012d45cb41b6b5a92205
bigcode/the-stack
train
2ea29b47ce915dcd0724da6b
train
function
@perms_check(1) def start_typing(self, _): if self.typing: raise Exception('You are already typing') self.typing = True self.channel.send({'type': 'user_start_typing', 'data': {'user': self.user, 'user_id': self.user_id}}) return {'type': 'start_typing_ok', 'data': ''}
@perms_check(1) def start_typing(self, _):
if self.typing: raise Exception('You are already typing') self.typing = True self.channel.send({'type': 'user_start_typing', 'data': {'user': self.user, 'user_id': self.user_id}}) return {'type': 'start_typing_ok', 'data': ''}
_type'].replace('__', '') resp = games.game_types[self.game.type][1].__getattribute__(action_type)(self, data) return {'type': 'action_%s_ok' % action_type, 'data': resp} @perms_check(1) def start_typing(self, _):
64
64
82
15
49
pufit/online-games
WSServer/commands.py
Python
start_typing
start_typing
300
306
300
301
54010eee0f8f02a0a06a575015f27b8b3db5ccff
bigcode/the-stack
train
25b476cf01940d85a82fe0fe
train
function
def error(*_): """ System method :return: dict """ return {'type': 'error', 'data': 'Bad request'}
def error(*_):
""" System method :return: dict """ return {'type': 'error', 'data': 'Bad request'}
perms_check(0) def ping(_, data): """ :return: dict """ if not data: return {'type': 'pong', 'data': 'Pong!'} return {'type': 'pong', 'data': time.time() - data} def error(*_):
64
64
34
5
59
pufit/online-games
WSServer/commands.py
Python
error
error
371
376
371
371
6a1b8c5b9a7dcb8df464959b85893569f2856f1c
bigcode/the-stack
train
b7824f0fce569e6657a56c7d
train
class
class HyperpriorExponShared(BaseHyperprior): """ Class governing hyperprior for factor H and W. Model places a hyperprior on each feature k, and jointly shared across D observed features and N observations. This hyperprior IS shared with W. PRIOR ON W: W ~ Exponenti...
class HyperpriorExponShared(BaseHyperprior):
""" Class governing hyperprior for factor H and W. Model places a hyperprior on each feature k, and jointly shared across D observed features and N observations. This hyperprior IS shared with W. PRIOR ON W: W ~ Exponential(hyperprior) """ def __init__(self...
.alpha = alpha + 0.5*D def update(self, mean_sq_H): self.beta = self.hyperprior_beta + 0.5*np.sum(mean_sq_H, axis=0) self.moments(self.alpha, self.beta) class HyperpriorExponShared(BaseHyperprior):
64
64
157
10
54
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
HyperpriorExponShared
HyperpriorExponShared
581
598
581
581
bec4aa921117e61d1b41e377a745331bdfcc61aa
bigcode/the-stack
train
a5c86ed92b21cf6c39b20985
train
class
class FactorBernoulli: def __init__(self, K, N): self.K = K self.N = N self.mean = np.empty([K,N]) self.mean_sq = np.empty_like(self.mean) self.var = np.empty_like(self.mean) self.etrpy = np.empty_like(self.mean) def initialize_preset(self, init_mean, init_var):...
class FactorBernoulli:
def __init__(self, K, N): self.K = K self.N = N self.mean = np.empty([K,N]) self.mean_sq = np.empty_like(self.mean) self.var = np.empty_like(self.mean) self.etrpy = np.empty_like(self.mean) def initialize_preset(self, init_mean, init_var): self.mean = ini...
ents(mu, sigma_sq) new_mean, new_var, new_etrpy, new_mean_sq = moments self.mean[k,:] = new_mean self.var[k,:] = new_var self.etrpy[k,:] = new_etrpy self.mean_sq[k,:] = new_mean_sq def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_H_sq_sum, ...
221
221
738
6
215
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
FactorBernoulli
FactorBernoulli
412
488
412
413
552f73dd1c71eb18d76b9a6b948c890988ae8af6
bigcode/the-stack
train
75f5451029fd938d7a315b7b
train
class
class FactorHExpon(BaseH): def __init__(self, lower_bound, upper_bound, K, D): super().__init__(lower_bound, upper_bound, K, D) def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_R_sq_sum, prod_mix): sigma_sq = np.reciprocal(noise_R_sq_sum) if sigma_sq<...
class FactorHExpon(BaseH):
def __init__(self, lower_bound, upper_bound, K, D): super().__init__(lower_bound, upper_bound, K, D) def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_R_sq_sum, prod_mix): sigma_sq = np.reciprocal(noise_R_sq_sum) if sigma_sq<0: import sys ...
""" transposed_tmp = ln_mean_hyperprior - self.mean_sq*mean_hyperprior prior_elbo = np.sum(-0.5*np.log(2*np.pi) + 0.5*transposed_tmp + np.log(2)) entropy_elbo = np.sum(self.etrpy) return prior_elbo + entropy_elbo class FactorHExpon(BaseH):
88
88
296
8
79
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
FactorHExpon
FactorHExpon
136
172
136
137
a4d535122d88a94d20dc97929b8af345f15e0dc9
bigcode/the-stack
train
0814d5d0164c99876571bc36
train
class
class BaseNPBW(BaseW): def __init__(self, lower_bound, upper_bound, K, N): super().__init__(lower_bound, upper_bound, K, N) def update(self, X, mean_H, mean_sq_H, mean_Z, mean_sq_Z, mean_hyperpriors, mean_noise): if mean_hyperpriors.ndim <= 1: # mean_hyperpriors has...
class BaseNPBW(BaseW):
def __init__(self, lower_bound, upper_bound, K, N): super().__init__(lower_bound, upper_bound, K, N) def update(self, X, mean_H, mean_sq_H, mean_Z, mean_sq_Z, mean_hyperpriors, mean_noise): if mean_hyperpriors.ndim <= 1: # mean_hyperpriors has shape (K) m...
pon, BaseFactorW): def __init__(self, lower_bound, upper_bound, K, N): # BaseFactorW has to be last!! super().__init__(lower_bound, upper_bound, K, N) class FactorWTruncNorm(BaseWTruncNorm, BaseFactorW): # BaseFactorW has to be last!! def __init__(self, lower_bound, upper_bound, K, N): super(...
111
111
372
7
104
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
BaseNPBW
BaseNPBW
366
400
366
367
52e34f9bb113cde5aab8a65c474c12978fb648e2
bigcode/the-stack
train
b2b56a0b5684822eb9ae7b7b
train
class
class HyperpriorTruncNormWSparsity(BaseHyperprior): def __init__(self, alpha, beta): super().__init__(alpha, beta) self.alpha = alpha + 0.5 def update(self, mean_sq_W): self.beta = self.hyperprior_beta + 0.5*mean_sq_W self.moments(self.alpha, self.beta)
class HyperpriorTruncNormWSparsity(BaseHyperprior):
def __init__(self, alpha, beta): super().__init__(alpha, beta) self.alpha = alpha + 0.5 def update(self, mean_sq_W): self.beta = self.hyperprior_beta + 0.5*mean_sq_W self.moments(self.alpha, self.beta)
self.beta = self.hyperprior_beta + 0.5*(np.sum(mean_sq_H, axis=0) + np.sum(mean_sq_W*mean_sparse_lambda, axis=1)) self.moments(self.alpha, self.beta) class HyperpriorTruncNormWSparsity(BaseHyperprior):
64
64
82
13
51
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
HyperpriorTruncNormWSparsity
HyperpriorTruncNormWSparsity
660
669
660
661
3d20c8a32d497598bd0e4ff08e74a1ce8a71384e
bigcode/the-stack
train
36f3a5cfbfef47adbf2e789e
train
class
class BaseW(FactorTruncNormVB): def __init__(self, lower_bound, upper_bound, K, N): super().__init__(lower_bound, upper_bound, K) self.N = N self.mean = np.empty([K,N]) self.mean_sq = np.empty_like(self.mean) self.var = np.empty_like(self.mean) self.etrpy = np.empty_...
class BaseW(FactorTruncNormVB):
def __init__(self, lower_bound, upper_bound, K, N): super().__init__(lower_bound, upper_bound, K) self.N = N self.mean = np.empty([K,N]) self.mean_sq = np.empty_like(self.mean) self.var = np.empty_like(self.mean) self.etrpy = np.empty_like(self.mean) def initiali...
- elbo_part: float """ prior_elbo = self.D*np.sum(ln_mean_hyperprior) prior_elbo -= np.sum(self.mean*mean_hyperprior) # utilize broadcasting entropy_elbo = np.sum(self.etrpy) return prior_elbo + entropy_elbo class BaseW(FactorTruncNormVB):
76
76
255
10
65
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
BaseW
BaseW
174
202
174
175
1d08743f5b1e339bacba7042f3545442c2ebe221
bigcode/the-stack
train
661df6f67fa92f775260251d
train
class
class HyperpriorExponSharedWithSparsity(HyperpriorExponShared): """ Class governing hyperprior for factor W alone. Model places a hyperprior on each element in W - thus being sparsity-promoting. PRIOR ON W: W ~ Exponential(hyperprior) """ def __init__(self, alpha, beta...
class HyperpriorExponSharedWithSparsity(HyperpriorExponShared):
""" Class governing hyperprior for factor W alone. Model places a hyperprior on each element in W - thus being sparsity-promoting. PRIOR ON W: W ~ Exponential(hyperprior) """ def __init__(self, alpha, beta, D, N, K): super().__init__(alpha, beta, D, N) ...
self.beta = self.hyperprior_beta + 0.5*(np.sum(mean_sq_H, axis=0) + np.sum(mean_sq_W, axis=1)) self.moments(self.alpha, self.beta) class HyperpriorExponSharedWithSparsity(HyperpriorExponShared):
64
64
173
17
47
ammunk/Bayesian-Non-Parametric-NMF
npbNMF/variational_distributions.py
Python
HyperpriorExponSharedWithSparsity
HyperpriorExponSharedWithSparsity
620
637
620
620
e89389eaa03c3c7a436a37a9776c25731b193097
bigcode/the-stack
train