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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
113ba387326109dba464bb34 | train | class | class DockerTunnel(tunnel.SSHTunnel):
__is_empty = False
def __enter__(self):
if self.__is_empty:
return self
return super().__enter__()
def __exit__(self, *a):
if self.__is_empty:
return
return super().__exit__(*a)
def __bool__(self):
return not self.__is_empty
__nonzero_... | class DockerTunnel(tunnel.SSHTunnel):
| __is_empty = False
def __enter__(self):
if self.__is_empty:
return self
return super().__enter__()
def __exit__(self, *a):
if self.__is_empty:
return
return super().__exit__(*a)
def __bool__(self):
return not self.__is_empty
__nonzero__ = __bool__
@property
def docker_... | proc = shell_popen(command, stdin=subprocess.PIPE)
proc.communicate(script.encode())
return proc.returncode
def send_file(src, dst):
command = ['scp', src, get_remote_string() + ':' + dst]
return shell_call(command)
class DockerTunnel(tunnel.SSHTunnel):
| 64 | 64 | 157 | 10 | 54 | NiklasRosenstein/wicked | src/docker_remote/client/__init__.py | Python | DockerTunnel | DockerTunnel | 122 | 151 | 122 | 123 | 28e73b0a348a92b8c6615524db2a7e6603d14263 | bigcode/the-stack | train |
c74f42548615730779ddf01a | train | function | def get_remote_string():
"""
Returns the host and username as a single string.
"""
host, user = get_remote_config()
if user:
host = '{}@{}'.format(user, host)
return host
| def get_remote_string():
| """
Returns the host and username as a single string.
"""
host, user = get_remote_config()
if user:
host = '{}@{}'.format(user, host)
return host
| username, applying
default values.
"""
host = config.get('remote.host', 'localhost')
user = config.get('remote.user', None) or None
if host != 'localhost' and not user:
user = 'root'
return host, user
def get_remote_string():
| 64 | 64 | 48 | 5 | 58 | NiklasRosenstein/wicked | src/docker_remote/client/__init__.py | Python | get_remote_string | get_remote_string | 61 | 69 | 61 | 61 | 4750b706a33a210ef298fd69af8b62a30cc14da2 | bigcode/the-stack | train |
a6294fb1efe325b6a9464b79 | train | class | class Client:
"""
This class wraps the docker-remote client workflow.
"""
def __init__(self, host=None, user=None, local_port=None, remote_port=None,
create_tunnel=None, tool_name=None):
if create_tunnel is None:
create_tunnel = (os.getenv('DOCKER_REMOTE_SHELL', '') != '1')
self.ho... | class Client:
| """
This class wraps the docker-remote client workflow.
"""
def __init__(self, host=None, user=None, local_port=None, remote_port=None,
create_tunnel=None, tool_name=None):
if create_tunnel is None:
create_tunnel = (os.getenv('DOCKER_REMOTE_SHELL', '') != '1')
self.host = host
... | host))
return DockerTunnel(host, user, None, local_port, remote_port)
def run_bash_script(script):
command = ['ssh', get_remote_string(), 'bash', '-s']
proc = shell_popen(command, stdin=subprocess.PIPE)
proc.communicate(script.encode())
return proc.returncode
def send_file(src, dst):
command = ['scp', ... | 256 | 256 | 1,373 | 3 | 252 | NiklasRosenstein/wicked | src/docker_remote/client/__init__.py | Python | Client | Client | 154 | 320 | 154 | 154 | 9c760626eb43bc8d3938e0692f57561f0105a5f4 | bigcode/the-stack | train |
c6ec5e8da402dafa7d23b596 | train | function | def create_remotepy_client(host=None, user=None, tool_name=None):
"""
Creates a new RemotePy client for the configured host.
"""
if host is None and user is None:
host, user = get_remote_config()
if host == 'localhost' and not user:
log.info('Creating local RemotePy client.')
return remotepy.Loc... | def create_remotepy_client(host=None, user=None, tool_name=None):
| """
Creates a new RemotePy client for the configured host.
"""
if host is None and user is None:
host, user = get_remote_config()
if host == 'localhost' and not user:
log.info('Creating local RemotePy client.')
return remotepy.LocalClient()
else:
log.info('Creating SSH RemotePy client ({}@... | def get_remote_string():
"""
Returns the host and username as a single string.
"""
host, user = get_remote_config()
if user:
host = '{}@{}'.format(user, host)
return host
def create_remotepy_client(host=None, user=None, tool_name=None):
| 64 | 64 | 121 | 16 | 47 | NiklasRosenstein/wicked | src/docker_remote/client/__init__.py | Python | create_remotepy_client | create_remotepy_client | 72 | 85 | 72 | 72 | 4ee8d43d937553881300933bf6e3fb9ddca96848 | bigcode/the-stack | train |
55f35805bda3c3b1dbca68c6 | train | function | def create_docker_tunnel(host=None, user=None, local_port=None,
remote_port=None):
"""
Creates an SSH tunnel for the Docker daemon on the remote machine. Returns
a #DockerTunnel instance. Note that the #DockerTunnel instance may be empty
if no tunnel needs to be created.
"""
if hos... | def create_docker_tunnel(host=None, user=None, local_port=None,
remote_port=None):
| """
Creates an SSH tunnel for the Docker daemon on the remote machine. Returns
a #DockerTunnel instance. Note that the #DockerTunnel instance may be empty
if no tunnel needs to be created.
"""
if host is None and user is None:
host, user = get_remote_config()
if host == 'localhost' and not user:
... | ()
else:
log.info('Creating SSH RemotePy client ({}@{}).'.format(user, host))
return remotepy.SSHClient(host, user, None, tool_name=tool_name)
def create_docker_tunnel(host=None, user=None, local_port=None,
remote_port=None):
| 64 | 64 | 209 | 21 | 43 | NiklasRosenstein/wicked | src/docker_remote/client/__init__.py | Python | create_docker_tunnel | create_docker_tunnel | 88 | 107 | 88 | 89 | 6277703e1c216e00252bc16f389a9ba3fbbbaa3f | bigcode/the-stack | train |
e34315d8531617d6a343acc5 | train | function | def set_remote_config(host, user=None):
"""
Sets the global configuration for the host and optionally the username. If
no username is specified, it will be set to #None, thus the previous user
setting will be overwritten.
"""
if not user:
user, host = host.partition('@')[::2]
if not host:
use... | def set_remote_config(host, user=None):
| """
Sets the global configuration for the host and optionally the username. If
no username is specified, it will be set to #None, thus the previous user
setting will be overwritten.
"""
if not user:
user, host = host.partition('@')[::2]
if not host:
user, host = '', user
config.set('remote.... | .
import contextlib
import os
import nr.fs
import subprocess
import yaml
from . import log
from .. import config, host
from ..core import remotepy, tunnel
from ..core.subprocess import shell_call, shell_convert, shell_popen
def set_remote_config(host, user=None):
| 64 | 64 | 101 | 9 | 54 | NiklasRosenstein/wicked | src/docker_remote/client/__init__.py | Python | set_remote_config | set_remote_config | 33 | 45 | 33 | 33 | 7c5cc2a8efac49d90a1725911f35a9e8a9401bef | bigcode/the-stack | train |
8d871ec336a6b77b714a8a36 | train | class | class Identifiable:
"""
OpenCLSim Identifiable with tags and a description.
Parameters
----------
name
a name
ID : UUID
a unique id generated with uuid
description
Text that can be used to describe a simulation object.
Note that this field does not influence ... | class Identifiable:
| """
OpenCLSim Identifiable with tags and a description.
Parameters
----------
name
a name
ID : UUID
a unique id generated with uuid
description
Text that can be used to describe a simulation object.
Note that this field does not influence the simulation.
... | """Component to identify the simulation objecs."""
import uuid
class Identifiable:
| 16 | 64 | 149 | 4 | 11 | thijsreedijk/OpenCLSim | openclsim/core/identifiable.py | Python | Identifiable | Identifiable | 6 | 27 | 6 | 6 | adc8d36413e712cf5e72f93dd66eac54af3396cb | bigcode/the-stack | train |
0b921acd6f31bb3593bf8218 | train | function | def load_data():
history_path = sorted(Path('./data').glob('*.history'))[-1]
with history_path.open(mode='rb') as f:
return pickle.load(f)
| def load_data():
| history_path = sorted(Path('./data').glob('*.history'))[-1]
with history_path.open(mode='rb') as f:
return pickle.load(f)
|
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
from pathlib import Path
import numpy as np
import pickle
#%% 파라미터 준비
RN_EPOCHS = 100 # 학습 횟수
#%% 학습 데이터 로드
def load_data():
| 64 | 64 | 39 | 4 | 59 | jisuk500/ML_learning | AlphaZero_book/chap6/train_network.py | Python | load_data | load_data | 24 | 27 | 24 | 24 | 226a93f9d6d244fc24b680e4ddc512026700ac8b | bigcode/the-stack | train |
a097f251d570529534801492 | train | function | def train_network():
# 학습 데이터 로드
history = load_data()
xs, y_policies, y_values = zip(*history)
# 학습을 위한 입력 데이터 형태로 변환
a,b,c = DN_INPUT_SHAPE
xs = np.array(xs)
xs = xs.reshape(len(xs), c,a,b).transpose(0,2,3,1)
y_policies = np.array(y_policies)
y_values = np.array(y_values)
... | def train_network():
# 학습 데이터 로드
| history = load_data()
xs, y_policies, y_values = zip(*history)
# 학습을 위한 입력 데이터 형태로 변환
a,b,c = DN_INPUT_SHAPE
xs = np.array(xs)
xs = xs.reshape(len(xs), c,a,b).transpose(0,2,3,1)
y_policies = np.array(y_policies)
y_values = np.array(y_values)
# 베스트 플레이어 모델 로드
model = loa... |
import numpy as np
import pickle
#%% 파라미터 준비
RN_EPOCHS = 100 # 학습 횟수
#%% 학습 데이터 로드
def load_data():
history_path = sorted(Path('./data').glob('*.history'))[-1]
with history_path.open(mode='rb') as f:
return pickle.load(f)
#%% 듀얼 네트워크 학습
def train_network():
# 학습 데이터 로드
| 102 | 102 | 341 | 12 | 89 | jisuk500/ML_learning | AlphaZero_book/chap6/train_network.py | Python | train_network | train_network | 31 | 73 | 31 | 32 | 864fcae90bd3c23040b2f37c3d457f3c8bf19542 | bigcode/the-stack | train |
13a2a9e71c5d85d2db60c8b8 | train | function | def matpower(cov, a, err=1e-3):
value, vector = la.eigh(cov)
indv = value > err
trcov = vector[:,indv] @ np.diag(np.power(value[indv], a)) @ vector[:,indv].T
return trcov
| def matpower(cov, a, err=1e-3):
| value, vector = la.eigh(cov)
indv = value > err
trcov = vector[:,indv] @ np.diag(np.power(value[indv], a)) @ vector[:,indv].T
return trcov
| = n * np.sum(self.values[decsort[r:p]])
self.pval[r] = 1 - stats.chi2.cdf(self.test[r], (p-r)*(2*self.m-r))
return covX
def matpower(cov, a, err=1e-3):
| 63 | 64 | 68 | 15 | 47 | SDR-VariableSelection/ADMMFTIRE | build/lib/FTIRE/FT3.py | Python | matpower | matpower | 125 | 129 | 125 | 125 | a13849dc1be68d42495c82890b09bc72ab6b3acb | bigcode/the-stack | train |
61c6259bbbb7391c11ce5345 | train | class | class FT:
"""FT method to apply for X and Y"""
def __init__(self, X, y, d = 1, m = 30, weighted = False, W = None, spX = False):
self.d = d
self.m = m
self.X = np.array(X)
self.y = np.array(y)
self.M = None
self.B = None
self.values = None
self.pva... | class FT:
| """FT method to apply for X and Y"""
def __init__(self, X, y, d = 1, m = 30, weighted = False, W = None, spX = False):
self.d = d
self.m = m
self.X = np.array(X)
self.y = np.array(y)
self.M = None
self.B = None
self.values = None
self.pval = None
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 21:53:32 2020
@author: jiayingweng
"""
import numpy as np
from scipy import stats
import scipy.linalg as la
import FTIRE
__all__ = ['FT']
#%%
class FT:
| 71 | 256 | 1,033 | 3 | 68 | SDR-VariableSelection/ADMMFTIRE | build/lib/FTIRE/FT3.py | Python | FT | FT | 17 | 122 | 17 | 17 | 626515867956bdccb335c290dc883e0e1cbac97d | bigcode/the-stack | train |
8cfb104ee534492f20b2be9a | train | class | class A2C_CNN:
def __init__(self, sess, window_size, obs_stack, output_size, num_worker, num_step, actor, critic):
self.sess = sess
self.window_size = window_size
self.obs_stack = obs_stack
self.output_size = output_size
self.actor = actor
self.critic = critic
... | class A2C_CNN:
| def __init__(self, sess, window_size, obs_stack, output_size, num_worker, num_step, actor, critic):
self.sess = sess
self.window_size = window_size
self.obs_stack = obs_stack
self.output_size = output_size
self.actor = actor
self.critic = critic
self.gamma =... | range(train_size)]
targets_batch = [targets[sample_range[i]] for i in range(train_size)]
advs_batch = [advs[sample_range[i]] for i in range(train_size)]
self.sess.run(self.critic_train_op, feed_dict={self.critic.input: state_batch,
self.targets: t... | 228 | 228 | 763 | 7 | 220 | kcs93023/tensorflow_RL | agent/discrete/seperate/a2c.py | Python | A2C_CNN | A2C_CNN | 80 | 154 | 80 | 80 | d5e62411142387862a4848247c6d21352a533dc6 | bigcode/the-stack | train |
fec0c2a526f5b946b9150643 | train | class | class A2C:
def __init__(self, sess, output_size, num_worker, num_step, actor, critic):
self.sess = sess
self.output_size = output_size
self.actor = actor
self.critic = critic
self.gamma = 0.99
self.lamda = 0.9
self.lr = 0.00025
self.batch_size = 32
... | class A2C:
| def __init__(self, sess, output_size, num_worker, num_step, actor, critic):
self.sess = sess
self.output_size = output_size
self.actor = actor
self.critic = critic
self.gamma = 0.99
self.lamda = 0.9
self.lr = 0.00025
self.batch_size = 32
self... | import numpy as np
import tensorflow as tf
import copy
class A2C:
| 18 | 222 | 740 | 5 | 12 | kcs93023/tensorflow_RL | agent/discrete/seperate/a2c.py | Python | A2C | A2C | 6 | 78 | 6 | 6 | 9095a859be2fb0eb23cadd2ca310fd7cb80a7cab | bigcode/the-stack | train |
f493401a6e0920d38a31cf6b | train | class | class static_runtime(KubernetesBuilder):
def __init__(self, config, cluster_config):
KubernetesBuilder.__init__(self, config, cluster_config)
self.nginxConf = """
nginx.conf: |
worker_processes 3;
error_log /dev/stderr;
events {
worker_connections 10240;
... | class static_runtime(KubernetesBuilder):
| def __init__(self, config, cluster_config):
KubernetesBuilder.__init__(self, config, cluster_config)
self.nginxConf = """
nginx.conf: |
worker_processes 3;
error_log /dev/stderr;
events {
worker_connections 10240;
}
http {
log_fo... | from generator.kubernetes import KubernetesBuilder
class static_runtime(KubernetesBuilder):
| 15 | 160 | 535 | 7 | 7 | urvil38/kubepaas-generator | runtime/static_runtime.py | Python | static_runtime | static_runtime | 4 | 83 | 4 | 5 | 6435cb0cf43837ec53e69015d12e19004a953a3e | bigcode/the-stack | train |
2c5a28d291136f6bb036a70b | train | class | class CardDownloader:
def __init__(self, number_of_cards = 0):
self.processed_cards = {}
with open("cards.csv") as reader:
csv_reader = csv.DictReader(reader)
# Get total cards to set completion bar
total_cards = 0
for line in csv_reader:
... | class CardDownloader:
| def __init__(self, number_of_cards = 0):
self.processed_cards = {}
with open("cards.csv") as reader:
csv_reader = csv.DictReader(reader)
# Get total cards to set completion bar
total_cards = 0
for line in csv_reader:
total_cards += 1
... | import csv
import scrython
import urllib.request
from ratelimit import limits, sleep_and_retry
from tqdm import tqdm
class CardDownloader:
| 32 | 137 | 458 | 4 | 27 | tommygod3/mtg-image-download | download/all/download.py | Python | CardDownloader | CardDownloader | 8 | 59 | 8 | 8 | 5ee3a15dcb31b2933bdad56a4a8e79b7545d53f6 | bigcode/the-stack | train |
31958bdc033b6c079f42fe86 | train | function | def fetch_data(files, folder, data_size=None):
"""Download files to folder and checks their sha checksums.
Parameters
----------
files : dictionary
For each file in `files` the value should be (url, sha). The file will
be downloaded from url if the file does not already exist or if the
... | def fetch_data(files, folder, data_size=None):
| """Download files to folder and checks their sha checksums.
Parameters
----------
files : dictionary
For each file in `files` the value should be (url, sha). The file will
be downloaded from url if the file does not already exist or if the
file exists but the sha checksum does n... | 256)
raise FetcherError(msg)
def _get_file_data(fname, url):
with contextlib.closing(urlopen(url)) as opener:
try:
response_size = opener.headers['content-length']
except KeyError:
response_size = None
with open(fname, 'wb') as data:
if resp... | 110 | 110 | 369 | 11 | 99 | tantheta01/fury | fury/data/fetcher.py | Python | fetch_data | fetch_data | 144 | 187 | 144 | 144 | 6854ed846165a3787b13f79c520872a8020b519c | bigcode/the-stack | train |
21f1c9f950f29b03ca138f12 | train | function | def _get_file_data(fname, url):
with contextlib.closing(urlopen(url)) as opener:
try:
response_size = opener.headers['content-length']
except KeyError:
response_size = None
with open(fname, 'wb') as data:
if response_size is None:
copyfile... | def _get_file_data(fname, url):
| with contextlib.closing(urlopen(url)) as opener:
try:
response_size = opener.headers['content-length']
except KeyError:
response_size = None
with open(fname, 'wb') as data:
if response_size is None:
copyfileobj(opener, data)
el... | wrong with the file
or that the upstream file has been updated.
You can try downloading the file again
or updating to the newest version of
Fury.""" % (filename, stored_sha256, computed_sha256)
raise FetcherError(msg)
def _get_file_data(fname, url):
| 64 | 64 | 90 | 9 | 55 | tantheta01/fury | fury/data/fetcher.py | Python | _get_file_data | _get_file_data | 130 | 141 | 130 | 130 | a502b979db71ffd4d5387be6cbbf2e613e6ce68b | bigcode/the-stack | train |
6863e08945e92e094ba7d14c | train | function | def update_progressbar(progress, total_length):
"""Show progressbar.
Takes a number between 0 and 1 to indicate progress from 0 to 100%.
"""
# Try to set the bar_length according to the console size
try:
columns = os.popen('tput cols', 'r').read()
bar_length = int(columns) - 46
... | def update_progressbar(progress, total_length):
| """Show progressbar.
Takes a number between 0 and 1 to indicate progress from 0 to 100%.
"""
# Try to set the bar_length according to the console size
try:
columns = os.popen('tput cols', 'r').read()
bar_length = int(columns) - 46
if bar_length < 1:
bar_length = ... | MODEL_DATA_URL = \
"https://raw.githubusercontent.com/fury-gl/fury-data/master/models/"
TEXTURE_DATA_URL = \
"https://raw.githubusercontent.com/fury-gl/fury-data/master/textures/"
class FetcherError(Exception):
pass
def update_progressbar(progress, total_length):
| 64 | 64 | 210 | 9 | 54 | tantheta01/fury | fury/data/fetcher.py | Python | update_progressbar | update_progressbar | 40 | 59 | 40 | 40 | 3421ea55165da3a5fba3ec060b07168799d84119 | bigcode/the-stack | train |
36b930b7b3b22c71658538a8 | train | function | def _already_there_msg(folder):
"""Print a message indicating that dataset is already in place."""
msg = 'Dataset is already in place. If you want to fetch it again '
msg += 'please first remove the folder %s ' % folder
print(msg)
| def _already_there_msg(folder):
| """Print a message indicating that dataset is already in place."""
msg = 'Dataset is already in place. If you want to fetch it again '
msg += 'please first remove the folder %s ' % folder
print(msg)
| 0
while True:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
copied += len(buf)
progress = float(copied) / float(total_length)
update_progressbar(progress, total_length)
def _already_there_msg(folder):
| 64 | 64 | 58 | 8 | 56 | tantheta01/fury | fury/data/fetcher.py | Python | _already_there_msg | _already_there_msg | 74 | 78 | 74 | 74 | aab33be3a9798efda4e4029f87408cb82997c0af | bigcode/the-stack | train |
b45d6e50210e9b463185caae | train | function | def read_viz_models(fname):
"""Read specific model.
Parameters
----------
fname : str
Filename of the model.
This should be found in folder HOME/.fury/models/.
Returns
--------
path : str
Complete path of models.
"""
folder = pjoin(fury_home, 'models')
... | def read_viz_models(fname):
| """Read specific model.
Parameters
----------
fname : str
Filename of the model.
This should be found in folder HOME/.fury/models/.
Returns
--------
path : str
Complete path of models.
"""
folder = pjoin(fury_home, 'models')
return pjoin(folder, fname)
| be found in folder HOME/.fury/style/.
Default is infinity.png.
Returns
--------
path : str
Complete path of icon.
"""
folder = pjoin(fury_home, 'icons', style)
return pjoin(folder, fname)
def read_viz_models(fname):
| 64 | 64 | 81 | 7 | 57 | tantheta01/fury | fury/data/fetcher.py | Python | read_viz_models | read_viz_models | 382 | 398 | 382 | 382 | 523fbb8755f683b03aba273702f383f69dab7fa9 | bigcode/the-stack | train |
26daa15bdfe1dc408eb64cf5 | train | function | def copyfileobj_withprogress(fsrc, fdst, total_length, length=16 * 1024):
copied = 0
while True:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
copied += len(buf)
progress = float(copied) / float(total_length)
update_progressbar(progress, to... | def copyfileobj_withprogress(fsrc, fdst, total_length, length=16 * 1024):
| copied = 0
while True:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
copied += len(buf)
progress = float(copied) / float(total_length)
update_progressbar(progress, total_length)
| f}% of {2}".format(
"#" * block + "-" * (bar_length - block), progress * 100, size_string)
sys.stdout.write(text)
sys.stdout.flush()
def copyfileobj_withprogress(fsrc, fdst, total_length, length=16 * 1024):
| 64 | 64 | 83 | 23 | 41 | tantheta01/fury | fury/data/fetcher.py | Python | copyfileobj_withprogress | copyfileobj_withprogress | 62 | 71 | 62 | 62 | 2321b15e2691f2b7c4af1f5ba3539a9154835f8d | bigcode/the-stack | train |
e77e360e15e90502aa56aeed | train | function | def read_viz_icons(style='icomoon', fname='infinity.png'):
"""Read specific icon from specific style.
Parameters
----------
style : str
Current icon style. Default is icomoon.
fname : str
Filename of icon. This should be found in folder HOME/.fury/style/.
Default is infinity... | def read_viz_icons(style='icomoon', fname='infinity.png'):
| """Read specific icon from specific style.
Parameters
----------
style : str
Current icon style. Default is icomoon.
fname : str
Filename of icon. This should be found in folder HOME/.fury/style/.
Default is infinity.png.
Returns
--------
path : str
Comp... | '85043336E023C4C9394CFD6D48D257A5564B4F895BFCEC01C70E4898CC77F003'],
doc="Download textures for fury"
)
def read_viz_icons(style='icomoon', fname='infinity.png'):
| 64 | 64 | 115 | 16 | 48 | tantheta01/fury | fury/data/fetcher.py | Python | read_viz_icons | read_viz_icons | 361 | 379 | 361 | 361 | aeb87cd35215bbe809a3f07c818b1943541f1d6b | bigcode/the-stack | train |
5f76348303a7723cd0126d37 | train | function | def _make_fetcher(name, folder, baseurl, remote_fnames, local_fnames,
sha_list=None, doc="", data_size=None, msg=None,
unzip=False):
"""Create a new fetcher.
Parameters
----------
name : str
The name of the fetcher function.
folder : str
The full ... | def _make_fetcher(name, folder, baseurl, remote_fnames, local_fnames,
sha_list=None, doc="", data_size=None, msg=None,
unzip=False):
| """Create a new fetcher.
Parameters
----------
name : str
The name of the fetcher function.
folder : str
The full path to the folder in which the files would be placed locally.
Typically, this is something like 'pjoin(fury_home, 'foo')'
baseurl : str
The URL from... | print('Data size is approximately %s' % data_size)
all_skip = True
for f in files:
url, sha = files[f]
fullpath = pjoin(folder, f)
if os.path.exists(fullpath) and (_get_file_sha(fullpath) == sha.lower()):
continue
all_skip = False
print('Downloading "... | 176 | 176 | 588 | 38 | 138 | tantheta01/fury | fury/data/fetcher.py | Python | _make_fetcher | _make_fetcher | 190 | 260 | 190 | 192 | 0d108d7e488426825d40eb0747e983c26e96d727 | bigcode/the-stack | train |
219dfde175f01ed932d0a314 | train | class | class FetcherError(Exception):
pass
| class FetcherError(Exception):
| pass
| .githubusercontent.com/fury-gl/fury-data/master/examples/"
MODEL_DATA_URL = \
"https://raw.githubusercontent.com/fury-gl/fury-data/master/models/"
TEXTURE_DATA_URL = \
"https://raw.githubusercontent.com/fury-gl/fury-data/master/textures/"
class FetcherError(Exception):
| 63 | 64 | 9 | 6 | 57 | tantheta01/fury | fury/data/fetcher.py | Python | FetcherError | FetcherError | 36 | 37 | 36 | 36 | b2a41a14de60862581054c56d2537203d8f25a8c | bigcode/the-stack | train |
e259cc07ff1d9d5cbe8284a0 | train | function | def _get_file_sha(filename):
"""Generate SHA checksum for the entire file in blocks of 256.
Parameters
----------
filename : str
The path to the file whose sha checksum is to be generated
Returns
-------
sha256_data : str
The computed sha hash from the input file
"""
... | def _get_file_sha(filename):
| """Generate SHA checksum for the entire file in blocks of 256.
Parameters
----------
filename : str
The path to the file whose sha checksum is to be generated
Returns
-------
sha256_data : str
The computed sha hash from the input file
"""
sha256_data = sha256()
... | _already_there_msg(folder):
"""Print a message indicating that dataset is already in place."""
msg = 'Dataset is already in place. If you want to fetch it again '
msg += 'please first remove the folder %s ' % folder
print(msg)
def _get_file_sha(filename):
| 64 | 64 | 125 | 7 | 57 | tantheta01/fury | fury/data/fetcher.py | Python | _get_file_sha | _get_file_sha | 81 | 99 | 81 | 81 | c3aaa9512c4f26d73caf5b5b898d1ebd23706f54 | bigcode/the-stack | train |
aa5cf529b5af31515a0a3c66 | train | function | def read_viz_textures(fname):
"""Read specific texture.
Parameters
----------
fname: str
Filename of the texture.
This should be found in folder HOME/.fury/textures/.
Returns
-------
path : str
Complete path of textures.
"""
folder = pjoin(fury_home, 'textu... | def read_viz_textures(fname):
| """Read specific texture.
Parameters
----------
fname: str
Filename of the texture.
This should be found in folder HOME/.fury/textures/.
Returns
-------
path : str
Complete path of textures.
"""
folder = pjoin(fury_home, 'textures')
return pjoin(folder,... | of the model.
This should be found in folder HOME/.fury/models/.
Returns
--------
path : str
Complete path of models.
"""
folder = pjoin(fury_home, 'models')
return pjoin(folder, fname)
def read_viz_textures(fname):
| 64 | 64 | 82 | 8 | 56 | tantheta01/fury | fury/data/fetcher.py | Python | read_viz_textures | read_viz_textures | 401 | 417 | 401 | 401 | 1d0d9189f3b18a8f5102862100eeffac10a91fe9 | bigcode/the-stack | train |
b56f59761e62dabf7a280de2 | train | function | def check_sha(filename, stored_sha256=None):
"""Check the generated sha checksum.
Parameters
----------
filename : str
The path to the file whose checksum is to be compared
stored_sha256 : str, optional
Used to verify the generated SHA checksum.
Default: None, checking is sk... | def check_sha(filename, stored_sha256=None):
| """Check the generated sha checksum.
Parameters
----------
filename : str
The path to the file whose checksum is to be compared
stored_sha256 : str, optional
Used to verify the generated SHA checksum.
Default: None, checking is skipped
"""
if stored_sha256 is not No... | sha256_data = sha256()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(256*sha256_data.block_size), b''):
sha256_data.update(chunk)
return sha256_data.hexdigest()
def check_sha(filename, stored_sha256=None):
| 64 | 64 | 202 | 10 | 54 | tantheta01/fury | fury/data/fetcher.py | Python | check_sha | check_sha | 102 | 127 | 102 | 102 | 34064185b1f5dd3d0ca468e3ee01ff7e8d8a97ab | bigcode/the-stack | train |
e16735c5c07de1a9ccd99a54 | train | function | @pytest.fixture
def b_py(testdir):
return testdir.makepyfile(test_b="""
def test_b():
assert False
def test_pass():
assert True
""")
| @pytest.fixture
def b_py(testdir):
| return testdir.makepyfile(test_b="""
def test_b():
assert False
def test_pass():
assert True
""")
| 4 / 0
def call_multiply():
multiply()
""")
@pytest.fixture
def a_py(testdir):
return testdir.makepyfile(test_a="""
import lib
def test_a():
lib.call_multiply();
""")
@pytest.fixture
def b_py(testdir):
| 64 | 64 | 41 | 9 | 55 | tarpas/pytest-runtime-info | tests/test_plugin.py | Python | b_py | b_py | 28 | 36 | 28 | 29 | 5f089144e3c12352a3a047506c6e2485fe41a440 | bigcode/the-stack | train |
25146d4a113dfbc095207c76 | train | function | @pytest.fixture
def lib_py(testdir):
return testdir.makepyfile(lib="""
def multiply():
return 2 * 4 / 0
def call_multiply():
multiply()
""")
| @pytest.fixture
def lib_py(testdir):
| return testdir.makepyfile(lib="""
def multiply():
return 2 * 4 / 0
def call_multiply():
multiply()
""")
| import pytest_runtime_info
import os
import json
import pytest
@pytest.fixture
def lib_py(testdir):
| 23 | 64 | 46 | 9 | 13 | tarpas/pytest-runtime-info | tests/test_plugin.py | Python | lib_py | lib_py | 7 | 15 | 7 | 8 | c81821bc45c1cc9e7dbe3ca4a237e34a1225b0e6 | bigcode/the-stack | train |
3df0bb0f4890aff4ce7b23b1 | train | function | def test_plugin(testdir, lib_py, a_py, b_py):
result_file = pytest_runtime_info.get_temp_file_path()
try:
file_modified = os.stat(result_file).st_mtime
except Exception:
file_modified = 0
test_result = testdir.runpytest()
# test if failed
test_result.assert_outcomes(failed=2, pas... | def test_plugin(testdir, lib_py, a_py, b_py):
| result_file = pytest_runtime_info.get_temp_file_path()
try:
file_modified = os.stat(result_file).st_mtime
except Exception:
file_modified = 0
test_result = testdir.runpytest()
# test if failed
test_result.assert_outcomes(failed=2, passed=1)
# test if result file was modified
... | import pytest_runtime_info
import os
import json
import pytest
@pytest.fixture
def lib_py(testdir):
return testdir.makepyfile(lib="""
def multiply():
return 2 * 4 / 0
def call_multiply():
multiply()
""")
@pytest.fixture
def a_py(testdir):
return testdir.makepyfil... | 154 | 163 | 546 | 15 | 139 | tarpas/pytest-runtime-info | tests/test_plugin.py | Python | test_plugin | test_plugin | 39 | 72 | 39 | 39 | 3ca069ddc241aec27e61f4d4a01284b0a9c78a2d | bigcode/the-stack | train |
3ed1b8c1088b91ee598c7f66 | train | function | @pytest.fixture
def a_py(testdir):
return testdir.makepyfile(test_a="""
import lib
def test_a():
lib.call_multiply();
""")
| @pytest.fixture
def a_py(testdir):
| return testdir.makepyfile(test_a="""
import lib
def test_a():
lib.call_multiply();
""")
| import os
import json
import pytest
@pytest.fixture
def lib_py(testdir):
return testdir.makepyfile(lib="""
def multiply():
return 2 * 4 / 0
def call_multiply():
multiply()
""")
@pytest.fixture
def a_py(testdir):
| 64 | 64 | 38 | 9 | 55 | tarpas/pytest-runtime-info | tests/test_plugin.py | Python | a_py | a_py | 18 | 25 | 18 | 19 | 15c15b298c4b76094b9222af707077202f6accbe | bigcode/the-stack | train |
9ab913c30f40b92bdf8a31e0 | train | class | class Service:
def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self.__resource.metadata.name
... | class Service:
| def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self.__resource.metadata.name
self.sele... | #!/usr/bin/env python3
class Service:
| 10 | 64 | 92 | 3 | 6 | IMMORTALxJO/kubegraph | src/classes/service.py | Python | Service | Service | 4 | 15 | 4 | 5 | 79c090f86f3701fef1c4a76eab6e16cc0e139f43 | bigcode/the-stack | train |
c03ac3ba29bd7e9360ba7978 | train | class | class Machprobe():
def __init__(self, ne, Te, Ti, m_i, I):
self.ne = ne
self.I = I
self.Cs =sqrt(e*(Te+Ti)/(m_i))
d_alpha = arccos((s**2 + R**2 - h**2)/(2*s*R))
self.A_eff = l_p*(R*sin(alpha)+r_p-max(R*sin(alpha)-r_p, s*sin(alpha-d_alpha)))
#print('Te : {} eV'.format(... | class Machprobe():
| def __init__(self, ne, Te, Ti, m_i, I):
self.ne = ne
self.I = I
self.Cs =sqrt(e*(Te+Ti)/(m_i))
d_alpha = arccos((s**2 + R**2 - h**2)/(2*s*R))
self.A_eff = l_p*(R*sin(alpha)+r_p-max(R*sin(alpha)-r_p, s*sin(alpha-d_alpha)))
#print('Te : {} eV'.format(Te))
#print... | 27 #[kg] mass of BF2+
k = 1.38e-23 #[m2kg/s2K] Boltzmann const
alpha = pi/2 # [rad] angle between B-field and Rotation center to Wire center
gamma = (1+0.5)/(2+0.5)
class Machprobe():
| 71 | 71 | 238 | 4 | 67 | GUNU-GO/SNUPI | Python_Projects/Mach_Probe/Mach_Probe_Analysis.py | Python | Machprobe | Machprobe | 18 | 33 | 18 | 18 | 0b8c6047a020a9a0a5a4bd0661da09812755836d | bigcode/the-stack | train |
42bb2e44cea6fda4e1540107 | train | function | def create_app(config_name):
app = Flask(__name__)
# creating configurations
app.config.from_object(config_options[config_name])
# config_options[config_name].init_app(app)
# initializing flask extensions
bootstrap.init_app(app)
db.init_app(app)
login_manager.init_app(app)
# regi... | def create_app(config_name):
| app = Flask(__name__)
# creating configurations
app.config.from_object(config_options[config_name])
# config_options[config_name].init_app(app)
# initializing flask extensions
bootstrap.init_app(app)
db.init_app(app)
login_manager.init_app(app)
# registering main blueprint
fro... | _options
from flask_login import LoginManager
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = 'auth.login'
def create_app(config_name):
| 64 | 64 | 157 | 6 | 58 | VirginiaNdungu1/ugatuzi | app/__init__.py | Python | create_app | create_app | 17 | 41 | 17 | 18 | a6936652c75112999094ab3ef719382474b8970f | bigcode/the-stack | train |
2fbf66f08b2780dab30a8bbd | train | function | @register_model_architecture('extract_pacsum', 'extract_pacsum')
def base_architecture(args):
# args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
# args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
# args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 204... | @register_model_architecture('extract_pacsum', 'extract_pacsum')
def base_architecture(args):
# args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
# args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
# args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 204... | args.attention_dropout = getattr(args, 'attention_dropout', 0.)
args.relu_dropout = getattr(args, 'relu_dropout', 0.)
args.dropout = getattr(args, 'dropout', 0.1)
| @register_model_architecture('extract_pacsum', 'extract_pacsum')
def base_architecture(args):
# args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
# args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
# args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 204... | 212 | 78 | 261 | 212 | 0 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | base_architecture | base_architecture | 291 | 305 | 291 | 302 | cc5661d264068ddc25c81dde6a605cee4a65f570 | bigcode/the-stack | train |
c5939502d0eb1b86243b9874 | train | class | @register_model('extract_pacsum')
class ExtractPacsum(FairseqModel):
def __init__(self, args, encoder, decoder):
super().__init__(encoder, decoder)
self.args = args
@staticmethod
def add_args(parser):
"""Add model-specific arguments to the parser."""
parser.add_ar... | @register_model('extract_pacsum')
class ExtractPacsum(FairseqModel):
| def __init__(self, args, encoder, decoder):
super().__init__(encoder, decoder)
self.args = args
@staticmethod
def add_args(parser):
"""Add model-specific arguments to the parser."""
parser.add_argument('--dropout', type=float, metavar='D',
... | assert bsz == src_emb.size(0)
seqlen = src_emb.size(1)
offset = torch.linspace(0, (bsz-1)*seqlen, bsz).type(sent_ends.type())
sent_ends_abs = sent_ends + offset.view(-1, 1)
sent_ends_repr = src_emb.contiguous().view(bsz*seqlen, -1)[sent_ends_abs]
sent_ends_repr = sent_ends_repr.view(bsz, nsent... | 138 | 138 | 460 | 18 | 119 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | ExtractPacsum | ExtractPacsum | 35 | 78 | 35 | 37 | 2f07c0ff1d5e4acdff1da837edb098f597e50d35 | bigcode/the-stack | train |
4fb1879e282ed54f42c00351 | train | function | def Embedding(num_embeddings, embedding_dim, padding_idx):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
return m
| def Embedding(num_embeddings, embedding_dim, padding_idx):
| m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
return m
| in state_dict:
del state_dict['decoder.embed_positions.weights']
if 'decoder.embed_positions._float_tensor' not in state_dict:
state_dict['decoder.embed_positions._float_tensor'] = torch.FloatTensor()
'''
return state_dict
def Embedding(num_embeddings, e... | 64 | 64 | 56 | 12 | 51 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | Embedding | Embedding | 263 | 266 | 263 | 263 | 81ac5be066ab0b2261d8c64d9e7267fc21e85063 | bigcode/the-stack | train |
d4dd0a31f2dcb0668ed4ded2 | train | function | def LayerNorm(embedding_dim):
m = nn.LayerNorm(embedding_dim)
return m
| def LayerNorm(embedding_dim):
| m = nn.LayerNorm(embedding_dim)
return m
|
def Embedding(num_embeddings, embedding_dim, padding_idx):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
return m
def LayerNorm(embedding_dim):
| 64 | 64 | 21 | 7 | 56 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | LayerNorm | LayerNorm | 269 | 271 | 269 | 269 | ddcb22d2f47b4878e32c9abad2025d2b839f19ad | bigcode/the-stack | train |
e3def616d09d4f3890366598 | train | class | class TransformerEncoder(FairseqEncoder):
"""Transformer encoder."""
def __init__(self, args, dictionary, left_pad=False):
super().__init__(dictionary)
self.dropout = args.dropout
from pytorch_transformers import RobertaModel, BertModel
from pytorch_transformers.file_ut... | class TransformerEncoder(FairseqEncoder):
| """Transformer encoder."""
def __init__(self, args, dictionary, left_pad=False):
super().__init__(dictionary)
self.dropout = args.dropout
from pytorch_transformers import RobertaModel, BertModel
from pytorch_transformers.file_utils import PYTORCH_TRANSFORMERS_CACHE
... | list: roberta-base, "
"roberta-large", choices=['roberta-base', 'roberta-large', 'bert-base-uncased', 'bert-large-uncased'])
# parser.add_argument('--sentence-transformer-arch', default='fairseq', help="sentence level transformer architecture [fairseq, bert]")
parser.... | 254 | 256 | 951 | 8 | 245 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | TransformerEncoder | TransformerEncoder | 82 | 166 | 82 | 82 | 26374ba59ca4e9cbf441dbf5af1998f24e0ef8f1 | bigcode/the-stack | train |
7c83b19248a44f0192eac5b5 | train | function | def get_sent_end_repr(src_emb, sent_ends):
bsz, nsent = sent_ends.size()
assert bsz == src_emb.size(0)
seqlen = src_emb.size(1)
offset = torch.linspace(0, (bsz-1)*seqlen, bsz).type(sent_ends.type())
sent_ends_abs = sent_ends + offset.view(-1, 1)
sent_ends_repr = src_emb.contiguous().view(b... | def get_sent_end_repr(src_emb, sent_ends):
| bsz, nsent = sent_ends.size()
assert bsz == src_emb.size(0)
seqlen = src_emb.size(1)
offset = torch.linspace(0, (bsz-1)*seqlen, bsz).type(sent_ends.type())
sent_ends_abs = sent_ends + offset.view(-1, 1)
sent_ends_repr = src_emb.contiguous().view(bsz*seqlen, -1)[sent_ends_abs]
sent_ends... | ,
)
from . import (
FairseqIncrementalDecoder, FairseqEncoder, FairseqModel,
register_model, register_model_architecture, FairseqDecoder,
)
from pytorch_transformers.modeling_bert import BertEncoder, BertLayerNorm
def get_sent_end_repr(src_emb, sent_ends):
| 64 | 64 | 145 | 12 | 51 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | get_sent_end_repr | get_sent_end_repr | 23 | 32 | 23 | 23 | 2910aff9eb31193ee3aed8bc7e19672c0e43ee02 | bigcode/the-stack | train |
c4728476f42a0b6771aab12f | train | class | class PacsumDecoder(FairseqDecoder):
def __init__(self, args, tgt_dic):
super().__init__(tgt_dic)
self.topk = 3
self.args=args
@torch.no_grad()
def forward(self, encoder_out):
embed = encoder_out['encoder_out']['embed']
mask = encoder_out['encoder_doc_mask... | class PacsumDecoder(FairseqDecoder):
| def __init__(self, args, tgt_dic):
super().__init__(tgt_dic)
self.topk = 3
self.args=args
@torch.no_grad()
def forward(self, encoder_out):
embed = encoder_out['encoder_out']['embed']
mask = encoder_out['encoder_doc_mask']
bsz, n_sent = mask.shape
... | _pad_mask, # bsz x n_sent
}
# def reorder_encoder_out(self, encoder_out_dict, new_order):
# if encoder_out_dict['encoder_out'] is not None:
# encoder_out_dict['encoder_out'] = \
# encoder_out_dict['encoder_out'].index_select(1, new_order)
# if encoder_out... | 256 | 256 | 1,007 | 9 | 246 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | PacsumDecoder | PacsumDecoder | 168 | 260 | 168 | 169 | 0cee810596158db937eb170e4f3a258b422730ac | bigcode/the-stack | train |
d937fcd3456de5a2b8e73d50 | train | function | def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
nn.init.constant_(m.bias, 0.)
return m
| def Linear(in_features, out_features, bias=True):
| m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
nn.init.constant_(m.bias, 0.)
return m
| padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
return m
def LayerNorm(embedding_dim):
m = nn.LayerNorm(embedding_dim)
return m
def Linear(in_features, out_features, bias=True):
| 64 | 64 | 50 | 11 | 52 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | Linear | Linear | 274 | 278 | 274 | 274 | 61601aa0add61edd259221e0af106b5c9faab761 | bigcode/the-stack | train |
0c97ef5096af244b28c961fb | train | function | def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):
if learned:
m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
nn.init.constant_(m.weight[padding_i... | def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):
| if learned:
m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
nn.init.constant_(m.weight[padding_idx], 0)
else:
m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_... | out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
nn.init.constant_(m.bias, 0.)
return m
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):
| 64 | 64 | 107 | 19 | 44 | xssstory/STAS | fairseq/models/extract_pacsum.py | Python | PositionalEmbedding | PositionalEmbedding | 281 | 288 | 281 | 281 | d296d86e61ae907141c6c315d893224721768357 | bigcode/the-stack | train |
30e899c313a630678f4cf927 | train | function | def test_verify_exp_in_future(app):
"""Test that token expiry is verified as being in future."""
payload = dict(
foo=1, exp=datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
)
t = _jwt_encode_dangerous(payload)
with pytest.raises(jwt.exceptions.ExpiredSignatureError):
_jwt_d... | def test_verify_exp_in_future(app):
| """Test that token expiry is verified as being in future."""
payload = dict(
foo=1, exp=datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
)
t = _jwt_encode_dangerous(payload)
with pytest.raises(jwt.exceptions.ExpiredSignatureError):
_jwt_decode(t)
| =1)
t = _jwt_encode(payload)
old_key = app.secret_key
try:
app.secret_key = 'foo'
with pytest.raises(jwt.exceptions.DecodeError):
_jwt_decode(t)
finally:
app.secret_key = old_key
def test_verify_exp_in_future(app):
| 64 | 64 | 73 | 8 | 55 | rjw57/componentsdb | tests/test_jwt.py | Python | test_verify_exp_in_future | test_verify_exp_in_future | 44 | 51 | 44 | 44 | c96cd4a6634de87c3c7fee941b9a3654ec9370a5 | bigcode/the-stack | train |
22266e1b57886b376c76e9f8 | train | function | def test_verify_exp_present(app):
"""Test that token expiry is verified as being present."""
payload = dict(foo=1)
t = _jwt_encode_dangerous(payload)
with pytest.raises(jwt.exceptions.MissingRequiredClaimError):
_jwt_decode(t)
| def test_verify_exp_present(app):
| """Test that token expiry is verified as being present."""
payload = dict(foo=1)
t = _jwt_encode_dangerous(payload)
with pytest.raises(jwt.exceptions.MissingRequiredClaimError):
_jwt_decode(t)
| as being in future."""
payload = dict(
foo=1, exp=datetime.datetime.utcnow() - datetime.timedelta(seconds=1)
)
t = _jwt_encode_dangerous(payload)
with pytest.raises(jwt.exceptions.ExpiredSignatureError):
_jwt_decode(t)
def test_verify_exp_present(app):
| 64 | 64 | 56 | 7 | 57 | rjw57/componentsdb | tests/test_jwt.py | Python | test_verify_exp_present | test_verify_exp_present | 53 | 58 | 53 | 53 | 460f80bbfa296053a22436d13508789301e637cc | bigcode/the-stack | train |
1a18447deff72adbf8afbbba | train | function | def test_verify_user_token(user):
"""Verifying the current token should set current_user."""
# NB: not "is None" since current_user is a proxy
assert current_user == None
t = user.token
set_current_user_with_token(t)
assert current_user.id == user.id
| def test_verify_user_token(user):
| """Verifying the current token should set current_user."""
# NB: not "is None" since current_user is a proxy
assert current_user == None
t = user.token
set_current_user_with_token(t)
assert current_user.id == user.id
| (jwt.exceptions.MissingRequiredClaimError):
_jwt_decode(t)
def test_user_token(user):
"""Users should be able to create tokens which refer to themselves."""
t = user.token
id_ = User.decode_token(t)
assert id_ == user.id
def test_verify_user_token(user):
| 64 | 64 | 65 | 7 | 56 | rjw57/componentsdb | tests/test_jwt.py | Python | test_verify_user_token | test_verify_user_token | 66 | 72 | 66 | 66 | 307ddb23b8c5d03b79579d15fde58237c02e0785 | bigcode/the-stack | train |
e2e8f541a108b51ecb0641d8 | train | function | def test_user_token(user):
"""Users should be able to create tokens which refer to themselves."""
t = user.token
id_ = User.decode_token(t)
assert id_ == user.id
| def test_user_token(user):
| """Users should be able to create tokens which refer to themselves."""
t = user.token
id_ = User.decode_token(t)
assert id_ == user.id
| (t)
def test_verify_exp_present(app):
"""Test that token expiry is verified as being present."""
payload = dict(foo=1)
t = _jwt_encode_dangerous(payload)
with pytest.raises(jwt.exceptions.MissingRequiredClaimError):
_jwt_decode(t)
def test_user_token(user):
| 64 | 64 | 43 | 6 | 58 | rjw57/componentsdb | tests/test_jwt.py | Python | test_user_token | test_user_token | 60 | 64 | 60 | 60 | 667c4079af0b183f981ac77c01a2d46131ad6771 | bigcode/the-stack | train |
3bb955337508e4ba22058e53 | train | function | def test_verify_sig(app):
"""Test that token is verified."""
payload = dict(foo=1)
t = _jwt_encode(payload)
old_key = app.secret_key
try:
app.secret_key = 'foo'
with pytest.raises(jwt.exceptions.DecodeError):
_jwt_decode(t)
finally:
app.secret_key = old_key
| def test_verify_sig(app):
| """Test that token is verified."""
payload = dict(foo=1)
t = _jwt_encode(payload)
old_key = app.secret_key
try:
app.secret_key = 'foo'
with pytest.raises(jwt.exceptions.DecodeError):
_jwt_decode(t)
finally:
app.secret_key = old_key
| p['foo'] == 1
def test_token_has_exp(app):
"""Test that token has exp field in payload."""
payload = dict(foo=1)
t = _jwt_encode(payload)
p = _jwt_decode(t)
assert 'exp' in p
def test_verify_sig(app):
| 64 | 64 | 75 | 6 | 57 | rjw57/componentsdb | tests/test_jwt.py | Python | test_verify_sig | test_verify_sig | 32 | 42 | 32 | 32 | 72bbc53d69334be84e9f0219bd1b05b13af5fe86 | bigcode/the-stack | train |
db86f48c26d6c08dd25624cb | train | function | def test_token_enc_dec(app):
"""Test basic encoding and decoding of token."""
payload = dict(foo=1)
t = _jwt_encode(payload)
p = _jwt_decode(t)
assert p['foo'] == 1
| def test_token_enc_dec(app):
| """Test basic encoding and decoding of token."""
payload = dict(foo=1)
t = _jwt_encode(payload)
p = _jwt_decode(t)
assert p['foo'] == 1
| -outer-name, unused-argument
import datetime
import jwt
import pytest
from componentsdb.app import current_user, set_current_user_with_token
from componentsdb.model import (
User,
_jwt_encode, _jwt_decode, _jwt_encode_dangerous
)
def test_token_enc_dec(app):
| 64 | 64 | 51 | 7 | 57 | rjw57/componentsdb | tests/test_jwt.py | Python | test_token_enc_dec | test_token_enc_dec | 18 | 23 | 18 | 18 | 0c6e14ac4249685d7f27557885b638274d50faf7 | bigcode/the-stack | train |
4882630300be90011069827b | train | function | def test_token_has_exp(app):
"""Test that token has exp field in payload."""
payload = dict(foo=1)
t = _jwt_encode(payload)
p = _jwt_decode(t)
assert 'exp' in p
| def test_token_has_exp(app):
| """Test that token has exp field in payload."""
payload = dict(foo=1)
t = _jwt_encode(payload)
p = _jwt_decode(t)
assert 'exp' in p
| _encode_dangerous
)
def test_token_enc_dec(app):
"""Test basic encoding and decoding of token."""
payload = dict(foo=1)
t = _jwt_encode(payload)
p = _jwt_decode(t)
assert p['foo'] == 1
def test_token_has_exp(app):
| 64 | 64 | 50 | 7 | 56 | rjw57/componentsdb | tests/test_jwt.py | Python | test_token_has_exp | test_token_has_exp | 25 | 30 | 25 | 25 | f999ff1948ce8ee2155d93eb4629a812231a7b23 | bigcode/the-stack | train |
91659365eb02e23468e79a65 | train | function | def glyphstr(glyphs):
def f(x):
if len(x) == 1:
return list(x)[0]
else:
return '[%s]' % ' '.join(sorted(list(x)))
return ' '.join(f(g.glyphSet()) for g in glyphs)
| def glyphstr(glyphs):
| def f(x):
if len(x) == 1:
return list(x)[0]
else:
return '[%s]' % ' '.join(sorted(list(x)))
return ' '.join(f(g.glyphSet()) for g in glyphs)
| Tools import CapturingLogHandler
from fontTools.feaLib.error import FeatureLibError
from fontTools.feaLib.parser import Parser, SymbolTable
from io import StringIO
import warnings
import fontTools.feaLib.ast as ast
import os
import unittest
def glyphstr(glyphs):
| 64 | 64 | 62 | 7 | 56 | gregdavill/fonttools | Tests/feaLib/parser_test.py | Python | glyphstr | glyphstr | 12 | 18 | 12 | 12 | 950872507948a2b2f0eed8cadf45d2c29ea9fdb3 | bigcode/the-stack | train |
edf0f2fff5253d21cde3b137 | train | function | def mapping(s):
b = []
for a in s.glyphs:
b.extend(a.glyphSet())
c = []
for a in s.replacements:
c.extend(a.glyphSet())
if len(c) == 1:
c = c * len(b)
return dict(zip(b, c))
| def mapping(s):
| b = []
for a in s.glyphs:
b.extend(a.glyphSet())
c = []
for a in s.replacements:
c.extend(a.glyphSet())
if len(c) == 1:
c = c * len(b)
return dict(zip(b, c))
| str(glyphs):
def f(x):
if len(x) == 1:
return list(x)[0]
else:
return '[%s]' % ' '.join(sorted(list(x)))
return ' '.join(f(g.glyphSet()) for g in glyphs)
def mapping(s):
| 64 | 64 | 70 | 4 | 60 | gregdavill/fonttools | Tests/feaLib/parser_test.py | Python | mapping | mapping | 21 | 30 | 21 | 21 | b100003adc230fff99c270d2dc2c1143cb701182 | bigcode/the-stack | train |
9e561ddecd8d9ae9bb9c8b09 | train | class | class SymbolTableTest(unittest.TestCase):
def test_scopes(self):
symtab = SymbolTable()
symtab.define("foo", 23)
self.assertEqual(symtab.resolve("foo"), 23)
symtab.enter_scope()
self.assertEqual(symtab.resolve("foo"), 23)
symtab.define("foo", 42)
self.assertEq... | class SymbolTableTest(unittest.TestCase):
| def test_scopes(self):
symtab = SymbolTable()
symtab.define("foo", 23)
self.assertEqual(symtab.resolve("foo"), 23)
symtab.enter_scope()
self.assertEqual(symtab.resolve("foo"), 23)
symtab.define("foo", 42)
self.assertEqual(symtab.resolve("foo"), 42)
sym... | p = Parser(featurefile, glyphNames, followIncludes=followIncludes)
return p.parse()
@staticmethod
def getpath(testfile):
path, _ = os.path.split(__file__)
return os.path.join(path, "data", testfile)
class SymbolTableTest(unittest.TestCase):
| 64 | 64 | 128 | 8 | 56 | gregdavill/fonttools | Tests/feaLib/parser_test.py | Python | SymbolTableTest | SymbolTableTest | 1,854 | 1,867 | 1,854 | 1,854 | afaa075ad5281e1519af0551f06417ce4c8d5f97 | bigcode/the-stack | train |
8f82bd6686c62d825f27554c | train | class | class ParserTest(unittest.TestCase):
def __init__(self, methodName):
unittest.TestCase.__init__(self, methodName)
# Python 3 renamed assertRaisesRegexp to assertRaisesRegex,
# and fires deprecation warnings if a program uses the old name.
if not hasattr(self, "assertRaisesRegex"):
... | class ParserTest(unittest.TestCase):
| def __init__(self, methodName):
unittest.TestCase.__init__(self, methodName)
# Python 3 renamed assertRaisesRegexp to assertRaisesRegex,
# and fires deprecation warnings if a program uses the old name.
if not hasattr(self, "assertRaisesRegex"):
self.assertRaisesRegex = se... | h.sc i.sc j.sc k.sc l.sc m.sc
n.sc o.sc p.sc q.sc r.sc s.sc t.sc u.sc v.sc w.sc x.sc y.sc z.sc
a.swash b.swash x.swash y.swash z.swash
foobar foo.09 foo.1234 foo.9876
one two five six acute grave dieresis umlaut cedilla ogonek macron
a_f_f_i o_f_f_i f_i f_f_i one.fitted one.oldstyle a.1 a.2 a.3 c_t... | 255 | 256 | 20,683 | 7 | 248 | gregdavill/fonttools | Tests/feaLib/parser_test.py | Python | ParserTest | ParserTest | 54 | 1,851 | 54 | 54 | 30d5110acad654a4bf2b2d2318926037b23c4b9b | bigcode/the-stack | train |
ce560199635d9611be6ee800 | train | class | class DrlMain(object):
def __init__(self):
self.name = 'DrlMain'
def startup(self):
#holt_winters = HoltWinters()
#holt_winters.startup()
engine = BitcoinTradingEngine()
engine.startup()
| class DrlMain(object):
| def __init__(self):
self.name = 'DrlMain'
def startup(self):
#holt_winters = HoltWinters()
#holt_winters.startup()
engine = BitcoinTradingEngine()
engine.startup()
| #
from app.drl.holt_winters import HoltWinters
from app.drl.bitcoin_trading_engine import BitcoinTradingEngine
class DrlMain(object):
| 34 | 64 | 58 | 6 | 27 | yt7589/aqp | app/drl/drl_main.py | Python | DrlMain | DrlMain | 5 | 13 | 5 | 5 | 6b98ad8ac06e07f66f429b7a5ef5416bf09dea89 | bigcode/the-stack | train |
4fd2c9f512df6e4d5edd0b65 | train | class | class contact(hierarchy_design.hierarchy_design):
"""
Object for a contact shape with its conductor enclosures.
Creates a contact array minimum active or poly enclosure and metal1 enclosure.
This class has enclosure on two or four sides of the contact.
The direction specifies whether the first and s... | class contact(hierarchy_design.hierarchy_design):
| """
Object for a contact shape with its conductor enclosures.
Creates a contact array minimum active or poly enclosure and metal1 enclosure.
This class has enclosure on two or four sides of the contact.
The direction specifies whether the first and second layer have asymmetric extension in the H or ... | # See LICENSE for licensing information.
#
#Copyright (c) 2016-2019 Regents of the University of California and The Board
#of Regents for the Oklahoma Agricultural and Mechanical College
#(acting for and on behalf of Oklahoma State University)
#All rights reserved.
#
import hierarchy_design
import debug
import utils
fr... | 88 | 256 | 1,921 | 9 | 78 | xinjie0831/OpenRAM | compiler/base/contact.py | Python | contact | contact | 15 | 189 | 15 | 15 | 0293cbcfee4a368315eff988c2dab59921f5479d | bigcode/the-stack | train |
9644dfdd33290b3e0d078b26 | train | function | def position_of_radec(ra_hours, dec_degrees, distance_au=_GIGAPARSEC_AU,
epoch=None, t=None, center=None, target=None,
observer_data=None):
"""Build a position object from a right ascension and declination.
If a specific ``distance_au`` is not provided, Skyfield retu... | def position_of_radec(ra_hours, dec_degrees, distance_au=_GIGAPARSEC_AU,
epoch=None, t=None, center=None, target=None,
observer_data=None):
| """Build a position object from a right ascension and declination.
If a specific ``distance_au`` is not provided, Skyfield returns a
position vector a gigaparsec in length. This puts the position at a
great enough distance that it will stand at the same right ascension
and declination from any vie... | is not None:
cls = Geometric
else:
cls = ICRF
return cls(position_au, velocity_au_per_d, t, center, target, observer_data)
def position_of_radec(ra_hours, dec_degrees, distance_au=_GIGAPARSEC_AU,
epoch=None, t=None, center=None, target=None,
observer_... | 85 | 85 | 286 | 43 | 42 | benwu95/python-skyfield | skyfield/positionlib.py | Python | position_of_radec | position_of_radec | 34 | 55 | 34 | 36 | 4931a5685c6a48fc213bba50224953f13433c13a | bigcode/the-stack | train |
30f9b1beb76b1dd54fadc597 | train | class | class Astrometric(ICRF):
"""An astrometric (x,y,z) position relative to a particular observer.
The *astrometric position* of a body is its position relative to an
observer, adjusted for light-time delay. It is the position of the
body back when it emitted (or reflected) the light that is now
reach... | class Astrometric(ICRF):
| """An astrometric (x,y,z) position relative to a particular observer.
The *astrometric position* of a body is its position relative to an
observer, adjusted for light-time delay. It is the position of the
body back when it emitted (or reflected) the light that is now
reaching the observer's eyes o... | is then divided by the speed of light to
find how long it takes its light to arrive. Finally, the light
travel time is subtracted from `t` and the body is asked for a
series of increasingly exact positions to learn where it was
when it emitted the light that is now reaching this positi... | 206 | 206 | 689 | 7 | 199 | benwu95/python-skyfield | skyfield/positionlib.py | Python | Astrometric | Astrometric | 534 | 602 | 534 | 534 | 82a645c21e93bb8adca3d105760e3d97de9a07f6 | bigcode/the-stack | train |
1a5368083bc7377311108b36 | train | function | def build_position(position_au, velocity_au_per_d=None, t=None,
center=None, target=None, observer_data=None):
if center == 0:
cls = Barycentric
elif center == 399:
cls = Geocentric
elif observer_data is not None:
cls = Geometric
else:
cls = ICRF
re... | def build_position(position_au, velocity_au_per_d=None, t=None,
center=None, target=None, observer_data=None):
| if center == 0:
cls = Barycentric
elif center == 399:
cls = Geocentric
elif observer_data is not None:
cls = Geometric
else:
cls = ICRF
return cls(position_au, velocity_au_per_d, t, center, target, observer_data)
| GALACTIC']
_GIGAPARSEC_AU = 206264806247096.38 # 1e9 * 360 * 3600 / tau
def build_position(position_au, velocity_au_per_d=None, t=None,
center=None, target=None, observer_data=None):
| 64 | 64 | 102 | 28 | 35 | benwu95/python-skyfield | skyfield/positionlib.py | Python | build_position | build_position | 22 | 32 | 22 | 23 | 19a61b130f74edec96bc63c949879036a908d169 | bigcode/the-stack | train |
a8adf0bb3a70b764b4b51b6f | train | function | def position_from_radec(ra_hours, dec_degrees, distance=1.0, epoch=None,
t=None, center=None, target=None, observer_data=None):
"""DEPRECATED version of ``position_of_radec()``.
Problems:
* The ``distance`` parameter specifies no unit, contrary to Skyfield
best practices. I ... | def position_from_radec(ra_hours, dec_degrees, distance=1.0, epoch=None,
t=None, center=None, target=None, observer_data=None):
| """DEPRECATED version of ``position_of_radec()``.
Problems:
* The ``distance`` parameter specifies no unit, contrary to Skyfield
best practices. I have no idea what I was thinking.
* The default ``distance`` is far too small, since most objects for
which users specify an RA and declinati... | v(epoch.MT, position_au)
return build_position(position_au, None, t, center, target, observer_data)
def position_from_radec(ra_hours, dec_degrees, distance=1.0, epoch=None,
t=None, center=None, target=None, observer_data=None):
| 64 | 64 | 209 | 36 | 28 | benwu95/python-skyfield | skyfield/positionlib.py | Python | position_from_radec | position_from_radec | 57 | 75 | 57 | 58 | 4cefd90c26f194b8fe4db327c8f918ee5bf34891 | bigcode/the-stack | train |
9a1fd1a1d0519085602ef2d9 | train | function | def _to_altaz(position_au, observer_data, temperature_C, pressure_mbar):
"""Compute (alt, az, distance) relative to the observer's horizon.
"""
elevation_m = observer_data.elevation_m
R = observer_data.altaz_rotation
if (elevation_m is None) or (R is None):
raise ValueError('to compute an ... | def _to_altaz(position_au, observer_data, temperature_C, pressure_mbar):
| """Compute (alt, az, distance) relative to the observer's horizon.
"""
elevation_m = observer_data.elevation_m
R = observer_data.altaz_rotation
if (elevation_m is None) or (R is None):
raise ValueError('to compute an altazimuth position, you must'
' observe from a ... | I'm deferring the refactoring for now, to get
# this new feature to users more quickly.
from .toposlib import Topos
return Topos(latitude=Angle(radians=lat),
longitude=Angle(radians=lon),
elevation_m=elevation_m)
def _to_altaz(position_au, observer_data... | 79 | 79 | 266 | 19 | 60 | benwu95/python-skyfield | skyfield/positionlib.py | Python | _to_altaz | _to_altaz | 712 | 740 | 712 | 712 | cdaeb7dee246b87d085fbabea65bb727e520e8ea | bigcode/the-stack | train |
5e0f7f91a2faca0ca84fc58b | train | class | class Geometric(ICRF):
"""An (x,y,z) vector between two instantaneous position.
A geometric position is the difference between the Solar System
positions of two bodies at exactly the same instant. It is *not*
corrected for the fact that, in real physics, it will take time for
light to travel from ... | class Geometric(ICRF):
| """An (x,y,z) vector between two instantaneous position.
A geometric position is the difference between the Solar System
positions of two bodies at exactly the same instant. It is *not*
corrected for the fact that, in real physics, it will take time for
light to travel from one position to the oth... | ')
alt = _interpret_angle('alt', alt, alt_degrees)
az = _interpret_angle('az', az, az_degrees)
r = distance.au
p = from_spherical(r, alt, az)
p = einsum('ji...,j...->i...', R, p)
return Apparent(p)
# For compatibility with my original name for the class. Not an
# impor... | 115 | 115 | 386 | 6 | 108 | benwu95/python-skyfield | skyfield/positionlib.py | Python | Geometric | Geometric | 454 | 490 | 454 | 454 | e41e1c8a24e12f3184845847a3b7030bd347ef21 | bigcode/the-stack | train |
72f81a29c8a5b68db4554dbd | train | class | class Apparent(ICRF):
"""An apparent (x,y,z) position relative to a particular observer.
The *apparent position* of a body is its position relative to an
observer adjusted for light-time delay, deflection (light rays
bending as they pass large masses like the Sun or Jupiter), and
aberration (light ... | class Apparent(ICRF):
| """An apparent (x,y,z) position relative to a particular observer.
The *apparent position* of a body is its position relative to an
observer adjusted for light-time delay, deflection (light rays
bending as they pass large masses like the Sun or Jupiter), and
aberration (light slanting because of th... | _deflection = array((False,))
else:
limb_angle, nadir_angle = compute_limb_angle(
target_au, gcrs_position)
include_earth_deflection = nadir_angle >= 0.8
add_deflection(target_au, bcrs_position,
observer_data.ephemeris, t, include_earth_def... | 128 | 128 | 428 | 6 | 122 | benwu95/python-skyfield | skyfield/positionlib.py | Python | Apparent | Apparent | 605 | 644 | 605 | 605 | d68bc90974671fc7e596d831efd0a08bb4c6afdd | bigcode/the-stack | train |
765956b936cebbeca520a800 | train | class | class Barycentric(ICRF):
"""An (x,y,z) position measured from the Solar System barycenter.
Skyfield generates a `Barycentric` position measured from the
gravitational center of the Solar System whenever you ask a body for
its location at a particular time:
>>> t = ts.utc(2003, 8, 29)
>>> mars.... | class Barycentric(ICRF):
| """An (x,y,z) position measured from the Solar System barycenter.
Skyfield generates a `Barycentric` position measured from the
gravitational center of the Solar System whenever you ask a body for
its location at a particular time:
>>> t = ts.utc(2003, 8, 29)
>>> mars.at(t)
<Barycentric BC... | ``temperature_C`` either the temperature in degrees
centigrade, or the string ``'standard'`` (in which case 10°C is
used).
When calculating refraction, Skyfield uses the observer’s
elevation above sea level to estimate the atmospheric pressure.
If you want to override that valu... | 115 | 115 | 385 | 7 | 108 | benwu95/python-skyfield | skyfield/positionlib.py | Python | Barycentric | Barycentric | 493 | 529 | 493 | 493 | be412c0c37262cc63416aaa0977fa3c304d12e3c | bigcode/the-stack | train |
c16fbfe98bcef27e6c5faeef | train | function | def ITRF_to_GCRS(t, rITRF):
# Todo: wobble
spin = rot_z(t.gast / 24.0 * tau)
position = mxv(spin, array(rITRF))
return mxv(t.MT, position)
| def ITRF_to_GCRS(t, rITRF):
# Todo: wobble
| spin = rot_z(t.gast / 24.0 * tau)
position = mxv(spin, array(rITRF))
return mxv(t.MT, position)
| alt = refract(alt * RAD2DEG, temperature_C, pressure_mbar)
alt = Angle(degrees=alt)
return alt, Angle(radians=az), Distance(r_au)
def ITRF_to_GCRS(t, rITRF):
# Todo: wobble
| 64 | 64 | 60 | 21 | 43 | benwu95/python-skyfield | skyfield/positionlib.py | Python | ITRF_to_GCRS | ITRF_to_GCRS | 742 | 748 | 742 | 745 | d12b6cecd39fdb5dd9b8822957e674b1e6218622 | bigcode/the-stack | train |
1688578733c1f080d6729f23 | train | function | def ITRF_to_GCRS2(t, rITRF, vITRF, _high_accuracy=False):
# TODO: wobble
spin = rot_z(t.gast / 24.0 * tau)
position = mxv(spin, array(rITRF))
velocity = mxv(spin, array(vITRF))
# TODO: This is expensive, and should be extensively trimmed to only
# include the most important terms underlying GA... | def ITRF_to_GCRS2(t, rITRF, vITRF, _high_accuracy=False):
# TODO: wobble
| spin = rot_z(t.gast / 24.0 * tau)
position = mxv(spin, array(rITRF))
velocity = mxv(spin, array(vITRF))
# TODO: This is expensive, and should be extensively trimmed to only
# include the most important terms underlying GAST. But it improves
# the precision by something like 1e5 times when comp... | _to_GCRS(t, rITRF):
# Todo: wobble
spin = rot_z(t.gast / 24.0 * tau)
position = mxv(spin, array(rITRF))
return mxv(t.MT, position)
def ITRF_to_GCRS2(t, rITRF, vITRF, _high_accuracy=False):
# TODO: wobble
| 87 | 87 | 291 | 31 | 56 | benwu95/python-skyfield | skyfield/positionlib.py | Python | ITRF_to_GCRS2 | ITRF_to_GCRS2 | 750 | 777 | 750 | 752 | c82a1147ceaf19971511b33bc5e32393cee83749 | bigcode/the-stack | train |
b9158ce76cfc27af7004bfae | train | class | class Geocentric(ICRF):
"""An (x,y,z) position measured from the center of the Earth.
A geocentric position is the difference between the position of the
Earth at a given instant and the position of a target body at the
same instant, without accounting for light-travel time or the effect
of relativ... | class Geocentric(ICRF):
| """An (x,y,z) position measured from the center of the Earth.
A geocentric position is the difference between the position of the
Earth at a given instant and the position of a target body at the
same instant, without accounting for light-travel time or the effect
of relativity on the light itself.... | from geographic north (so 0 degrees means north, 90 is east, 180
is south, and 270 is west).
By default, Skyfield does not adjust the altitude for
atmospheric refraction. If you want Skyfield to estimate how
high the atmosphere might lift the body's image, give the
argument ``... | 187 | 187 | 624 | 7 | 180 | benwu95/python-skyfield | skyfield/positionlib.py | Python | Geocentric | Geocentric | 647 | 709 | 647 | 647 | 2c6cbba17507ec14a1304a74de0774bcaa7b8b6b | bigcode/the-stack | train |
e5293aa88c6280d4b310a318 | train | class | class ICRF(object):
"""An (x,y,z) position and velocity oriented to the ICRF axes.
The International Coordinate Reference Frame (ICRF) is a permanent
reference frame that is the replacement for J2000. Their axes agree
to within 0.02 arcseconds. It also supersedes older equinox-based
systems like ... | class ICRF(object):
| """An (x,y,z) position and velocity oriented to the ICRF axes.
The International Coordinate Reference Frame (ICRF) is a permanent
reference frame that is the replacement for J2000. Their axes agree
to within 0.02 arcseconds. It also supersedes older equinox-based
systems like B1900 and B1950.
... | if epoch is not None:
position_au = mxv(epoch.MT, position_au)
return build_position(position_au, None, t, center, target, observer_data)
def position_from_radec(ra_hours, dec_degrees, distance=1.0, epoch=None,
t=None, center=None, target=None, observer_data=None):
"""DEPREC... | 256 | 256 | 3,364 | 6 | 250 | benwu95/python-skyfield | skyfield/positionlib.py | Python | ICRF | ICRF | 77 | 446 | 77 | 77 | fba8f29f33bccbb7f890bcf70363d40ede597e08 | bigcode/the-stack | train |
b41ce7948dfb8ce4ccb359eb | train | class | class EFilingPackaging:
def __init__(self):
self.app_name = settings.EFILING_APP_NAME
self.court_level = settings.EFILING_COURT_LEVEL
self.court_class = settings.EFILING_COURT_CLASS
self.court_division = settings.EFILING_COURT_DIVISION
def _resolve_location_code(self, location_n... | class EFilingPackaging:
| def __init__(self):
self.app_name = settings.EFILING_APP_NAME
self.court_level = settings.EFILING_COURT_LEVEL
self.court_class = settings.EFILING_COURT_CLASS
self.court_division = settings.EFILING_COURT_DIVISION
def _resolve_location_code(self, location_name) -> {}:
cour... | # Special thanks to eDivorce for this.
import logging
from django.conf import settings
from .efiling_resources import EFilingResources
logger = logging.getLogger(__name__)
class EFilingPackaging:
| 42 | 132 | 440 | 5 | 37 | marzmehr/representation-grant-app | api/api/efiling/efiling_packaging.py | Python | EFilingPackaging | EFilingPackaging | 9 | 67 | 9 | 9 | 02dcac274adc2db4891f8b07b262ab176b4781d2 | bigcode/the-stack | train |
87aa7f819f091ef873f3fd25 | train | class | class TestOnlyOfType(util.TestCase):
"""Test only of type selectors."""
def test_only_of_type(self):
"""Test only of type."""
markup = """
<div id="0">
<p id="1"></p>
</div>
<span id="2"></span>
<span id="3"></span>
<p id="4"></p>
<sp... | class TestOnlyOfType(util.TestCase):
| """Test only of type selectors."""
def test_only_of_type(self):
"""Test only of type."""
markup = """
<div id="0">
<p id="1"></p>
</div>
<span id="2"></span>
<span id="3"></span>
<p id="4"></p>
<span id="5"></span>
<span id="6... | """Test only of type selectors."""
from .. import util
class TestOnlyOfType(util.TestCase):
| 21 | 64 | 160 | 9 | 11 | kianmeng/soupsieve | tests/test_level3/test_only_of_type.py | Python | TestOnlyOfType | TestOnlyOfType | 5 | 31 | 5 | 5 | b65506f522055e4ccb617876207f83956fa68015 | bigcode/the-stack | train |
0b2c364630687ed3f175b55a | train | class | class Character(object):
"""Character Variables"""
attributes = {'Mind':60, 'Health':80, 'Dignity':100, 'Satiety':100}
language = 'pt'
phase = 'Childhood'
locale = {'pt':{'Mind':'Sanidade','Health':'Saúde','Dignity':'Dignidade','Satiety':'Popularidade'}}
karma = []
"""Init Chara... | class Character(object):
| """Character Variables"""
attributes = {'Mind':60, 'Health':80, 'Dignity':100, 'Satiety':100}
language = 'pt'
phase = 'Childhood'
locale = {'pt':{'Mind':'Sanidade','Health':'Saúde','Dignity':'Dignidade','Satiety':'Popularidade'}}
karma = []
"""Init Character"""
def __init__(... | import datetime
import time
import sys
import json
import random
from pprint import pprint
def say(phrase):
for c in phrase:
sys.stdout.write(c)
time.sleep(0.007)
print(' ')
time.sleep(0.011)
class Character(object):
| 62 | 114 | 383 | 4 | 58 | andreperche/PythonMazeGame | main.py | Python | Character | Character | 17 | 51 | 17 | 17 | 5a2266d25e84f34077a92b745736015951c1817e | bigcode/the-stack | train |
59c15c05677a3eaea094ca97 | train | function | def say(phrase):
for c in phrase:
sys.stdout.write(c)
time.sleep(0.007)
print(' ')
time.sleep(0.011)
| def say(phrase):
| for c in phrase:
sys.stdout.write(c)
time.sleep(0.007)
print(' ')
time.sleep(0.011)
| import datetime
import time
import sys
import json
import random
from pprint import pprint
def say(phrase):
| 25 | 64 | 39 | 5 | 19 | andreperche/PythonMazeGame | main.py | Python | say | say | 9 | 14 | 9 | 9 | 5530a259cb9eec2ba37e6fea2b735daa663f18df | bigcode/the-stack | train |
83fd0afb56f243ec3f289703 | train | class | class Mechanics(object):
"""Mechanics Variables"""
tries = 5
options_path = "\options"
log_path = "\logs"
log_file = ''
language = "pt"
character = object
timestamp = datetime.datetime.now()
opt_y = ['sim','s','sei','y','yes','yep']
opt_n = ['não','n','nao','no','nope']... | class Mechanics(object):
| """Mechanics Variables"""
tries = 5
options_path = "\options"
log_path = "\logs"
log_file = ''
language = "pt"
character = object
timestamp = datetime.datetime.now()
opt_y = ['sim','s','sei','y','yes','yep']
opt_n = ['não','n','nao','no','nope']
phase = 'childhood'
... | (self.name, self.attributes['Mind'], self.attributes['Health'], self.attributes['Dignity'], self.attributes['Satiety'])
else:
return "%s's Status -> Mind:%d | Health:%d | Dignity:%d | Satiety:%d" % (self.name, self.attributes['Mind'], self.attributes['Health'], self.attributes['Dignity'], self.at... | 256 | 256 | 1,319 | 4 | 252 | andreperche/PythonMazeGame | main.py | Python | Mechanics | Mechanics | 62 | 207 | 62 | 62 | 55e69352551471881649d02efbc6c4641d5c4d90 | bigcode/the-stack | train |
66d485a11f922683c8369b44 | train | function | def is_installed():
args = ["psql"] + DEFAULT_ARGS
args += ["-qt", "-c \"select * from pg_tables where schemaname='public';\"", PARAMS["db"]]
cmd = " ".join(args)
logger.info(cmd)
output = subprocess.check_output(cmd, env=DEFAULT_ENV, shell=True)
return "core_" in output
| def is_installed():
| args = ["psql"] + DEFAULT_ARGS
args += ["-qt", "-c \"select * from pg_tables where schemaname='public';\"", PARAMS["db"]]
cmd = " ".join(args)
logger.info(cmd)
output = subprocess.check_output(cmd, env=DEFAULT_ENV, shell=True)
return "core_" in output
| PARAMS.get("port"):
DEFAULT_ARGS.append("--port={}".format(PARAMS["port"]))
DEFAULT_ENV = dict(os.environ)
if PARAMS.get("password"):
DEFAULT_ENV["PGPASSWORD"] = PARAMS["password"]
def engine_name():
return "postgres"
def is_installed():
| 64 | 64 | 82 | 5 | 59 | theshiv303/kegbot-server | pykeg/backup/postgres.py | Python | is_installed | is_installed | 39 | 45 | 39 | 39 | 043332edb4f7228893a2f6542dc4b8c6288e6625 | bigcode/the-stack | train |
d0010162d32dc94de820f281 | train | function | def restore(input_fd):
args = ["psql"] + DEFAULT_ARGS
args.append(PARAMS["db"])
cmd = " ".join(args)
logger.info(cmd)
return subprocess.check_call(cmd, stdin=input_fd, shell=True)
| def restore(input_fd):
| args = ["psql"] + DEFAULT_ARGS
args.append(PARAMS["db"])
cmd = " ".join(args)
logger.info(cmd)
return subprocess.check_call(cmd, stdin=input_fd, shell=True)
|
def dump(output_fd):
args = ["pg_dump"] + DEFAULT_ARGS
args.append(PARAMS["db"])
cmd = " ".join(args)
logger.info(cmd)
return subprocess.check_call(cmd, stdout=output_fd, env=DEFAULT_ENV, shell=True)
def restore(input_fd):
| 64 | 64 | 52 | 5 | 59 | theshiv303/kegbot-server | pykeg/backup/postgres.py | Python | restore | restore | 56 | 61 | 56 | 56 | 6a6339ffd64c2857c90ba5ea736e6092df5feea6 | bigcode/the-stack | train |
67c0adc3a054e25a3d705b3b | train | function | def engine_name():
return "postgres"
| def engine_name():
| return "postgres"
| ={}".format(PARAMS["host"]))
if PARAMS.get("port"):
DEFAULT_ARGS.append("--port={}".format(PARAMS["port"]))
DEFAULT_ENV = dict(os.environ)
if PARAMS.get("password"):
DEFAULT_ENV["PGPASSWORD"] = PARAMS["password"]
def engine_name():
| 63 | 64 | 9 | 4 | 59 | theshiv303/kegbot-server | pykeg/backup/postgres.py | Python | engine_name | engine_name | 35 | 36 | 35 | 35 | 87b0181347f68f3c11b148a6d267e0e413b5d93e | bigcode/the-stack | train |
a05b9ffc13056f240723863d | train | function | def erase():
args = ["psql"] + DEFAULT_ARGS
args += [PARAMS["db"], "-c 'drop schema public cascade; create schema public;'"]
cmd = " ".join(args)
logger.info(cmd)
subprocess.check_call(cmd, shell=True)
| def erase():
| args = ["psql"] + DEFAULT_ARGS
args += [PARAMS["db"], "-c 'drop schema public cascade; create schema public;'"]
cmd = " ".join(args)
logger.info(cmd)
subprocess.check_call(cmd, shell=True)
| , env=DEFAULT_ENV, shell=True)
def restore(input_fd):
args = ["psql"] + DEFAULT_ARGS
args.append(PARAMS["db"])
cmd = " ".join(args)
logger.info(cmd)
return subprocess.check_call(cmd, stdin=input_fd, shell=True)
def erase():
| 64 | 64 | 58 | 3 | 61 | theshiv303/kegbot-server | pykeg/backup/postgres.py | Python | erase | erase | 64 | 69 | 64 | 64 | 30913198c4466b110921c5730fd6234fc48c2cf9 | bigcode/the-stack | train |
4be2b4abae6de148b1943862 | train | function | def dump(output_fd):
args = ["pg_dump"] + DEFAULT_ARGS
args.append(PARAMS["db"])
cmd = " ".join(args)
logger.info(cmd)
return subprocess.check_call(cmd, stdout=output_fd, env=DEFAULT_ENV, shell=True)
| def dump(output_fd):
| args = ["pg_dump"] + DEFAULT_ARGS
args.append(PARAMS["db"])
cmd = " ".join(args)
logger.info(cmd)
return subprocess.check_call(cmd, stdout=output_fd, env=DEFAULT_ENV, shell=True)
| "-c \"select * from pg_tables where schemaname='public';\"", PARAMS["db"]]
cmd = " ".join(args)
logger.info(cmd)
output = subprocess.check_output(cmd, env=DEFAULT_ENV, shell=True)
return "core_" in output
def dump(output_fd):
| 64 | 64 | 58 | 5 | 58 | theshiv303/kegbot-server | pykeg/backup/postgres.py | Python | dump | dump | 48 | 53 | 48 | 48 | 6fd09980d4b4606629e9bc03d9d190d238586fd1 | bigcode/the-stack | train |
fced5a7f4ea5fda52f5a29eb | train | function | def createPortfile( args ):
"""Create vcpkg portfile"""
output = tpl_vcpkg_portfile.format(
optpfx=cfg_cmake_optpfx, usr=args.user, prj=args.project, ref=to_ref(args.version), sha=args.sha, lic=cfg_license )
if args.verbose:
print( "Creating portfile '{f}':".format( f=portfile_path( args ) )... | def createPortfile( args ):
| """Create vcpkg portfile"""
output = tpl_vcpkg_portfile.format(
optpfx=cfg_cmake_optpfx, usr=args.user, prj=args.project, ref=to_ref(args.version), sha=args.sha, lic=cfg_license )
if args.verbose:
print( "Creating portfile '{f}':".format( f=portfile_path( args ) ) )
if args.verbose > 1:
... | ) ) )
if args.verbose > 1:
print( output )
os.makedirs( os.path.dirname( control_path( args ) ), exist_ok=True )
with open( control_path( args ), 'w') as f:
print( output, file=f )
def createPortfile( args ):
| 64 | 64 | 149 | 7 | 57 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | createPortfile | createPortfile | 134 | 144 | 134 | 134 | 7b23019a8541e36843d28e318d8ccf8f0efb4a00 | bigcode/the-stack | train |
21679bc6e5cca980d5729f3b | train | function | def vcpkgRootFrom( path ):
return path if path else './vcpkg'
| def vcpkgRootFrom( path ):
| return path if path else './vcpkg'
| MakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1)
return description if description else cfg_vcpkg_description
def vcpkgRootFrom( path ):
| 64 | 64 | 20 | 9 | 54 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | vcpkgRootFrom | vcpkgRootFrom | 107 | 108 | 107 | 107 | 5dcc8c8911b5b9c836a40b27dcc48f39ba50f48e | bigcode/the-stack | train |
a3955d575fe5b065642d4ec6 | train | function | def versionFrom( filename ):
"""Obtain version from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
version = re.search(r'VERSION\s(\d+\.\d+\.\d+)', content).group(1)
return version
| def versionFrom( filename ):
| """Obtain version from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
version = re.search(r'VERSION\s(\d+\.\d+\.\d+)', content).group(1)
return version
| create-vcpkg --sha={sha}'
- Install package : 'vcpkg install {prj}'"""
tpl_vcpkg_note_install =\
"""
Next actions:
- Install package: 'vcpkg install {prj}'"""
# End of vcpkg templates
def versionFrom( filename ):
| 64 | 64 | 67 | 6 | 57 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | versionFrom | versionFrom | 93 | 98 | 93 | 93 | 9e48a2d031d06d070ecec944315616f1110394b7 | bigcode/the-stack | train |
927701d5280bc519ed15d383 | train | function | def to_ref( version ):
"""Add prefix to version/tag, like v1.2.3"""
return cfg_ref_prefix + version
| def to_ref( version ):
| """Add prefix to version/tag, like v1.2.3"""
return cfg_ref_prefix + version
| content = f.read()
description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1)
return description if description else cfg_vcpkg_description
def vcpkgRootFrom( path ):
return path if path else './vcpkg'
def to_ref( version ):
| 64 | 64 | 30 | 6 | 58 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | to_ref | to_ref | 110 | 112 | 110 | 110 | 94fe3db259a801cf7d0f196be67a02746678b986 | bigcode/the-stack | train |
39f20ca7a5796f85f0839870 | train | function | def createVcpkgFromCommandLine():
"""Collect arguments from the commandline and create vcpkg."""
parser = argparse.ArgumentParser(
description='Create microsoft vcpkg.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-v', '--ver... | def createVcpkgFromCommandLine():
| """Collect arguments from the commandline and create vcpkg."""
parser = argparse.ArgumentParser(
description='Create microsoft vcpkg.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-v', '--verbose',
action='count',
... | _note_install.
format( prj=args.project ) )
def createVcpkg( args ):
print( "Creating vcpkg for '{usr}/{prj}', version '{ver}' in folder '{vcpkg}':".
format( usr=args.user, prj=args.project, ver=args.version, vcpkg=args.vcpkg_root, ) )
createControl( args )
createPortfile( args )
pr... | 103 | 103 | 345 | 9 | 94 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | createVcpkgFromCommandLine | createVcpkgFromCommandLine | 161 | 218 | 161 | 161 | 190c6ebcd5c3bf3349ff8816f369ac198ad8d0be | bigcode/the-stack | train |
68c3601ac18a39672a21f5ec | train | function | def createControl( args ):
"""Create vcpkg CONTROL file"""
output = tpl_vcpkg_control.format(
prj=args.project, ver=args.version, desc=args.description )
if args.verbose:
print( "Creating control file '{f}':".format( f=control_path( args ) ) )
if args.verbose > 1:
print( output ... | def createControl( args ):
| """Create vcpkg CONTROL file"""
output = tpl_vcpkg_control.format(
prj=args.project, ver=args.version, desc=args.description )
if args.verbose:
print( "Creating control file '{f}':".format( f=control_path( args ) ) )
if args.verbose > 1:
print( output )
os.makedirs( os.path.... | kg_root, prj=args.project )
def portfile_path( args ):
"""Create path like vcpks/ports/_project_/portfile.cmake"""
return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project )
def createControl( args ):
| 64 | 64 | 121 | 6 | 58 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | createControl | createControl | 122 | 132 | 122 | 122 | 68950c0fd3540dc51a7e31b9dbe3534ac275f634 | bigcode/the-stack | train |
f598199f524ebbd649e4a88e | train | function | def control_path( args ):
"""Create path like vcpks/ports/_project_/CONTROL"""
return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project )
| def control_path( args ):
| """Create path like vcpks/ports/_project_/CONTROL"""
return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project )
| description else cfg_vcpkg_description
def vcpkgRootFrom( path ):
return path if path else './vcpkg'
def to_ref( version ):
"""Add prefix to version/tag, like v1.2.3"""
return cfg_ref_prefix + version
def control_path( args ):
| 64 | 64 | 45 | 6 | 57 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | control_path | control_path | 114 | 116 | 114 | 114 | 0e29ef6711213546724fab556b3b6c7e324d17e9 | bigcode/the-stack | train |
82f78728a8ae7df46a91bc26 | train | function | def descriptionFrom( filename ):
"""Obtain description from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1)
return description if description else cfg_vcpkg_description
| def descriptionFrom( filename ):
| """Obtain description from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1)
return description if description else cfg_vcpkg_description
| tain version from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
version = re.search(r'VERSION\s(\d+\.\d+\.\d+)', content).group(1)
return version
def descriptionFrom( filename ):
| 64 | 64 | 68 | 6 | 57 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | descriptionFrom | descriptionFrom | 100 | 105 | 100 | 100 | 546bb1f2aeb1f780c0ad22e52262309c8c0412d2 | bigcode/the-stack | train |
b7f5df0ffcc1bd4bc0d52f5e | train | function | def printNotes( args ):
if args.sha == cfg_sha512:
print( tpl_vcpkg_note_sha.
format( prj=args.project, sha='...' ) )
else:
print( tpl_vcpkg_note_install.
format( prj=args.project ) )
| def printNotes( args ):
| if args.sha == cfg_sha512:
print( tpl_vcpkg_note_sha.
format( prj=args.project, sha='...' ) )
else:
print( tpl_vcpkg_note_install.
format( prj=args.project ) )
| ) )
if args.verbose > 1:
print( output )
os.makedirs( os.path.dirname( portfile_path( args ) ), exist_ok=True )
with open( portfile_path( args ), 'w') as f:
print( output, file=f )
def printNotes( args ):
| 64 | 64 | 60 | 6 | 58 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | printNotes | printNotes | 146 | 152 | 146 | 146 | a34bb4ddd941b2b2e2ab5418ed8685890aba536a | bigcode/the-stack | train |
cf0f85149d2126a5d58983e1 | train | function | def portfile_path( args ):
"""Create path like vcpks/ports/_project_/portfile.cmake"""
return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project )
| def portfile_path( args ):
| """Create path like vcpks/ports/_project_/portfile.cmake"""
return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project )
| 2.3"""
return cfg_ref_prefix + version
def control_path( args ):
"""Create path like vcpks/ports/_project_/CONTROL"""
return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project )
def portfile_path( args ):
| 64 | 64 | 50 | 7 | 57 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | portfile_path | portfile_path | 118 | 120 | 118 | 118 | cacf08ea56ccb17e369e3f48d1097b389a141c69 | bigcode/the-stack | train |
7b3340aefeeed23d8cdbb831 | train | function | def createVcpkg( args ):
print( "Creating vcpkg for '{usr}/{prj}', version '{ver}' in folder '{vcpkg}':".
format( usr=args.user, prj=args.project, ver=args.version, vcpkg=args.vcpkg_root, ) )
createControl( args )
createPortfile( args )
printNotes( args )
| def createVcpkg( args ):
| print( "Creating vcpkg for '{usr}/{prj}', version '{ver}' in folder '{vcpkg}':".
format( usr=args.user, prj=args.project, ver=args.version, vcpkg=args.vcpkg_root, ) )
createControl( args )
createPortfile( args )
printNotes( args )
| args ):
if args.sha == cfg_sha512:
print( tpl_vcpkg_note_sha.
format( prj=args.project, sha='...' ) )
else:
print( tpl_vcpkg_note_install.
format( prj=args.project ) )
def createVcpkg( args ):
| 64 | 64 | 82 | 8 | 56 | KimGreenbush/PowerToys__ColorPicker | deps/expected-lite/script/create-vcpkg.py | Python | createVcpkg | createVcpkg | 154 | 159 | 154 | 154 | f6a9dd5ba9b11d35c2762243bd46df0a1b9076e3 | bigcode/the-stack | train |
a93a37ef8b8725c55680991f | train | function | def run_majority_metric(seed=0):
v = spatial.Voters(seed=seed, tol=None)
v.add_random(100)
c = spatial.Candidates(v, seed=seed)
c.add_random(3)
c.add_random(2, sdev=2)
e = spatial.Election(v, c, seed=seed)
e.run('plurality')
# Retrieve output
ties = e.result.ties
w... | def run_majority_metric(seed=0):
| v = spatial.Voters(seed=seed, tol=None)
v.add_random(100)
c = spatial.Candidates(v, seed=seed)
c.add_random(3)
c.add_random(2, sdev=2)
e = spatial.Election(v, c, seed=seed)
e.run('plurality')
# Retrieve output
ties = e.result.ties
winners = e.result.winners
ballots = e.r... | # -*- coding: utf-8 -*-
"""Test to see if the winner_majority metric is working correctly."""
import sys, traceback, pdb
import numpy as np
import votesim
from votesim.models import spatial
from votesim.metrics import ElectionStats
seed = None
def run_majority_metric(seed=0):
| 67 | 101 | 338 | 10 | 56 | johnh865/election_sim | votesim/tests/test_metrics.py | Python | run_majority_metric | run_majority_metric | 13 | 61 | 13 | 15 | 8a6dc8760a4f51fafdd889b181d726ed3fb72095 | bigcode/the-stack | train |
4abebece9adca6654258b427 | train | function | def test_majority_100():
for i in range(100):
run_majority_metric(i)
print(i)
| def test_majority_100():
| for i in range(100):
run_majority_metric(i)
print(i)
| if maxvotes > numvoters / 2:
s = ('there should be majority winner, '
'%s out of %s' % (maxvotes, numvoters))
print(s)
assert stats.candidates.winner_majority in winners
def test_majority_100():
| 62 | 64 | 26 | 7 | 54 | johnh865/election_sim | votesim/tests/test_metrics.py | Python | test_majority_100 | test_majority_100 | 65 | 68 | 65 | 65 | aab1429ba73ee02a59430fbbbc14bc2e46be131a | bigcode/the-stack | train |
91afe644ecc6368ddc5eb4fb | train | class | class TestFullyConvolutionalLinearHead(unittest.TestCase):
def test_fully_convolutional_linear_head(self):
head = fcl.FullyConvolutionalLinearHead(
"default_head",
num_classes=2,
in_plane=3,
pool_size=[1, 3, 3],
activation_func="softmax",
... | class TestFullyConvolutionalLinearHead(unittest.TestCase):
| def test_fully_convolutional_linear_head(self):
head = fcl.FullyConvolutionalLinearHead(
"default_head",
num_classes=2,
in_plane=3,
pool_size=[1, 3, 3],
activation_func="softmax",
use_dropout=False,
)
input = torch.rand(... | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import classy_vision.heads.fully_convolutional_linear_head as fcl
import torch
class TestFullyConvol... | 82 | 185 | 617 | 12 | 69 | jdsgomes/ClassyVision-1 | test/heads_fully_convolutional_linear_head_test.py | Python | TestFullyConvolutionalLinearHead | TestFullyConvolutionalLinearHead | 13 | 80 | 13 | 13 | f10a20cac3ae05cac343ad3a2115a4021d3600cb | bigcode/the-stack | train |
e724e4ccccd6fd737e4f352b | train | class | class TestRenderers(unittest.TestCase):
def _assert_is_labels(self, labels):
self.assertIsInstance(labels, list)
for l in labels:
self.assertIsInstance(l, Label)
def test_concept_adapter(self):
from pyramid_skosprovider.renderers import concept_adapter
c = Concept(
... | class TestRenderers(unittest.TestCase):
| def _assert_is_labels(self, labels):
self.assertIsInstance(labels, list)
for l in labels:
self.assertIsInstance(l, Label)
def test_concept_adapter(self):
from pyramid_skosprovider.renderers import concept_adapter
c = Concept(
id=larch['id'],
l... | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from pyramid import testing
from pyramid.compat import (
text_type
)
from .fixtures.data import (
larch,
chestnut,
species,
trees
)
from skosprovider.skos import (
Concept,
Collection,
Label,
Source
)
import json
i... | 105 | 256 | 1,723 | 8 | 96 | roefem/pyramid_skosprovider | tests/test_renderers.py | Python | TestRenderers | TestRenderers | 34 | 232 | 34 | 35 | c51bc8e17bf784e67637410ed953c9f20ca75ce8 | bigcode/the-stack | train |
0cb7b9352ea2dc8ff4f4921e | train | function | def decode(state: "knx_stack.State", msg: "knx_stack.Msg") -> Iterable[NamedTuple]:
return ind.decode(state, msg)
| def decode(state: "knx_stack.State", msg: "knx_stack.Msg") -> Iterable[NamedTuple]:
| return ind.decode(state, msg)
| from typing import Iterable, NamedTuple
from knx_stack.decode.layer.transport.t_data_broadcast import ind
def decode(state: "knx_stack.State", msg: "knx_stack.Msg") -> Iterable[NamedTuple]:
| 46 | 64 | 32 | 24 | 21 | majamassarini/knx-stack | knx_stack/decode/layer/network/n_data_broadcast/ind.py | Python | decode | decode | 5 | 6 | 5 | 5 | 1c6b3a6db0d3e61afcb5da7823df480fee1768cf | bigcode/the-stack | train |
723a6e8fbdc960fec96e34d1 | train | class | class TLClassifier(object):
def __init__(self):
SIM_MODEL_PATH = 'sim/frozen_inference_graph.pb'
REAL_MODEL_PATH = 'real/frozen_inference_graph.pb'
config_string = rospy.get_param("/traffic_light_config")
config = yaml.load(config_string)
MODEL_PATH = REAL_MODEL_PATH if confi... | class TLClassifier(object):
| def __init__(self):
SIM_MODEL_PATH = 'sim/frozen_inference_graph.pb'
REAL_MODEL_PATH = 'real/frozen_inference_graph.pb'
config_string = rospy.get_param("/traffic_light_config")
config = yaml.load(config_string)
MODEL_PATH = REAL_MODEL_PATH if config['is_site'] else SIM_MODEL_... | import numpy as np
import rospy
import tensorflow as tf
import yaml
from styx_msgs.msg import TrafficLight
class TLClassifier(object):
| 30 | 256 | 883 | 5 | 24 | dooyum/System-Integration-Capstone-Project | ros/src/tl_detector/light_classification/tl_classifier.py | Python | TLClassifier | TLClassifier | 7 | 100 | 7 | 7 | 753e4d28ddb06a90e6e5c9c02b1af8b28d86ef9e | bigcode/the-stack | train |
4e583186e633e86a159b9aa8 | train | class | class TestCase(BaseTest):
def test_subat_1(test):
test.assertEqual('xello', subat("hello", 0, "x"))
test.assertEqual('heLlo', subat("hello", 2, "L"))
test.assertEqual('hiyllo', subat("hello", 1, "iy"))
test.assertEqual('hello', subat("hello", 10, "x"))
test.assertEqual('ello'... | class TestCase(BaseTest):
| def test_subat_1(test):
test.assertEqual('xello', subat("hello", 0, "x"))
test.assertEqual('heLlo', subat("hello", 2, "L"))
test.assertEqual('hiyllo', subat("hello", 1, "iy"))
test.assertEqual('hello', subat("hello", 10, "x"))
test.assertEqual('ello', subat("hello", 0, ""))
... | ##==============================================================#
## SECTION: Imports #
##==============================================================#
import os
from testlib import *
from auxly.stringy import subat, randomize, between
##=================================... | 57 | 142 | 474 | 6 | 51 | jeffrimko/Auxly | tests/stringy_test_1.py | Python | TestCase | TestCase | 14 | 44 | 14 | 14 | fa061a48fb430431bd83c35993cb7eca6204ee88 | bigcode/the-stack | train |
6b3cfb0908351d0f823dd81f | train | function | def create_and_push(token, output):
if token.isdigit():
output.append(int(token))
elif token == "+":
output.append(output.pop() + output.pop())
elif token == "*":
output.append(output.pop() * output.pop())
| def create_and_push(token, output):
| if token.isdigit():
output.append(int(token))
elif token == "+":
output.append(output.pop() + output.pop())
elif token == "*":
output.append(output.pop() * output.pop())
| as puzzle_input_file:
puzzle_input_raw = puzzle_input_file.read()
# Simple Shunting-Yard Implementation:
# see https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail
OPERATORS = {"+": 0, "*": 0}
def create_and_push(token, output):
| 64 | 64 | 52 | 8 | 56 | timofurrer/aoc-2020 | 2020/18/part1.py | Python | create_and_push | create_and_push | 16 | 22 | 16 | 16 | cd4bfe737ca7ef98e9f6643baff64b9d738cf682 | bigcode/the-stack | train |
3e45f948c279fb97914dcd89 | train | class | class MetadataReader(PayloadReader):
def __init__(self):
PayloadReader.__init__(self)
def getMimeType(self):
return "application/metadata"
def getDuration(self):
return 0
def getFormat(self):
return "Metadata"
def consumeData(self, pts):
#print "Packet le... | class MetadataReader(PayloadReader):
| def __init__(self):
PayloadReader.__init__(self)
def getMimeType(self):
return "application/metadata"
def getDuration(self):
return 0
def getFormat(self):
return "Metadata"
def consumeData(self, pts):
#print "Packet length: {}, type: {}".format(len(self.da... | -8
# Copyright 2016 jeoliva author. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
from bitreader import BitReader
from parsers.payloadreader import PayloadReader
class MetadataReader(PayloadReader):
| 64 | 64 | 91 | 7 | 56 | GlennS/hls-analyzer | parsers/metadatareader.py | Python | MetadataReader | MetadataReader | 9 | 25 | 9 | 10 | 8f2c4f3dc99afce6d9789355f6068057b7b514f4 | bigcode/the-stack | train |
67bc83efac4622b51df1243f | train | class | class CRPSFObject(object):
"""
Base class for PSF objects for Cramer-Rao bounds calculations.
"""
def __init__(self, psf_data = None, pixel_size = None, **kwds):
super(CRPSFObject, self).__init__(**kwds)
self.pixel_size = pixel_size
if "normalization" in psf_data:
... | class CRPSFObject(object):
| """
Base class for PSF objects for Cramer-Rao bounds calculations.
"""
def __init__(self, psf_data = None, pixel_size = None, **kwds):
super(CRPSFObject, self).__init__(**kwds)
self.pixel_size = pixel_size
if "normalization" in psf_data:
self.normalization = ... | ostics/cramer_rao/
Hazen 02/17
"""
import numpy
import pickle
import storm_analysis.spliner.spline3D as spline3D
# FIXME: Also handle 2D splines.
class CramerRaoException(Exception):
pass
class CRPSFObject(object):
| 64 | 64 | 144 | 7 | 56 | bintulab/storm-analysis | storm_analysis/spliner/cramer_rao.py | Python | CRPSFObject | CRPSFObject | 25 | 43 | 25 | 25 | c170494c88be0e7e658450b168d9d2faada527e0 | bigcode/the-stack | train |
11cea5b4969e247029f415c5 | train | class | class CramerRaoException(Exception):
pass
| class CramerRaoException(Exception):
| pass
| PSF FFT with
storm_analysis/diagnostics/cramer_rao/
Hazen 02/17
"""
import numpy
import pickle
import storm_analysis.spliner.spline3D as spline3D
# FIXME: Also handle 2D splines.
class CramerRaoException(Exception):
| 64 | 64 | 11 | 8 | 56 | bintulab/storm-analysis | storm_analysis/spliner/cramer_rao.py | Python | CramerRaoException | CramerRaoException | 22 | 23 | 22 | 22 | 0ce694f754ad2e8cd8f13866c5273b7acbf81ce3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.